-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathagent_builder.rs
More file actions
1283 lines (1126 loc) · 44.4 KB
/
agent_builder.rs
File metadata and controls
1283 lines (1126 loc) · 44.4 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
// ABOUTME: Factory for creating AutoAgents with CodeGraph-specific configuration
// ABOUTME: Bridges codegraph_ai LLM providers to AutoAgents ChatProvider
// ABOUTME: Builder for tier-aware CodeGraph agents with graph analysis tools
use async_trait::async_trait;
#[cfg(test)]
use autoagents::llm::chat::ChatMessageBuilder;
use autoagents::llm::chat::ChatProvider;
use autoagents::llm::chat::{
ChatMessage, ChatResponse, ChatRole, MessageType, StructuredOutputFormat, Tool,
};
use autoagents::llm::completion::{CompletionProvider, CompletionRequest, CompletionResponse};
use autoagents::llm::embedding::EmbeddingProvider;
use autoagents::llm::error::LLMError;
use autoagents::llm::models::{ModelListRequest, ModelListResponse, ModelsProvider};
use autoagents::llm::{FunctionCall, ToolCall};
use codegraph_ai::llm_provider::{LLMProvider as CodeGraphLLM, Message, MessageRole};
use codegraph_mcp_core::debug_logger::DebugLogger;
use serde::Deserialize;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::Arc;
/// Convert CodeGraph Message to AutoAgents ChatMessage
#[cfg(test)]
pub(crate) fn convert_to_chat_message(msg: &Message) -> ChatMessage {
let builder = match msg.role {
MessageRole::System => ChatMessageBuilder::new(ChatRole::System),
MessageRole::User => ChatMessage::user(),
MessageRole::Assistant => ChatMessage::assistant(),
};
builder.content(&msg.content).build()
}
/// Convert CodeGraph Messages to AutoAgents ChatMessages
#[cfg(test)]
pub(crate) fn convert_messages(messages: &[Message]) -> Vec<ChatMessage> {
messages.iter().map(convert_to_chat_message).collect()
}
/// Default memory window size for all tiers (40 messages)
const DEFAULT_MEMORY_WINDOW: usize = 40;
/// Read memory window size from environment or use default.
/// Uses fixed default of 40 for all tiers (not tier-based).
/// Override via CODEGRAPH_AGENT_MEMORY_WINDOW env var if needed.
/// Memory window of 0 means unlimited history (use with caution).
pub(crate) fn read_memory_window_config() -> usize {
std::env::var("CODEGRAPH_AGENT_MEMORY_WINDOW")
.ok()
.and_then(|s| s.parse::<usize>().ok())
.unwrap_or(DEFAULT_MEMORY_WINDOW)
}
use crate::autoagents::progress_notifier::ProgressCallback;
use codegraph_mcp_core::context_aware_limits::ContextTier;
/// Adapter that bridges codegraph_ai::LLMProvider to AutoAgents ChatProvider
pub struct CodeGraphChatAdapter {
provider: Arc<dyn CodeGraphLLM>,
tier: ContextTier,
progress_callback: Option<ProgressCallback>,
step_counter: Arc<AtomicUsize>,
/// Maximum context size in bytes (derived from CODEGRAPH_CONTEXT_WINDOW)
/// Used as safety valve to prevent accumulated tool results from exceeding model limits
max_context_bytes: usize,
}
impl CodeGraphChatAdapter {
/// Calculate max context bytes from environment or tier
/// Uses ~80% of context window (reserves 20% for response) at ~4 bytes/token
fn calculate_max_context_bytes(tier: ContextTier) -> usize {
// Check env var first
if let Ok(context_window) = std::env::var("CODEGRAPH_CONTEXT_WINDOW")
.ok()
.and_then(|v| v.parse::<usize>().ok())
.ok_or(())
{
// 80% of context window * 4 bytes/token
return context_window * 4 * 8 / 10;
}
// Fall back to tier-based defaults (tokens * 4 bytes * 80%)
match tier {
ContextTier::Small => 50_000 * 4 * 8 / 10, // ~160KB
ContextTier::Medium => 128_000 * 4 * 8 / 10, // ~410KB
ContextTier::Large => 200_000 * 4 * 8 / 10, // ~640KB
ContextTier::Massive => 2_000_000 * 4 * 8 / 10, // ~6.4MB
}
}
pub fn new(provider: Arc<dyn CodeGraphLLM>, tier: ContextTier) -> Self {
let max_context_bytes = Self::calculate_max_context_bytes(tier);
tracing::debug!(
"CodeGraphChatAdapter initialized with max_context_bytes: {} ({:.1}MB)",
max_context_bytes,
max_context_bytes as f64 / 1_000_000.0
);
Self {
provider,
tier,
progress_callback: None,
step_counter: Arc::new(AtomicUsize::new(1)),
max_context_bytes,
}
}
pub fn with_progress_callback(
provider: Arc<dyn CodeGraphLLM>,
tier: ContextTier,
callback: ProgressCallback,
) -> Self {
let max_context_bytes = Self::calculate_max_context_bytes(tier);
tracing::debug!(
"CodeGraphChatAdapter initialized with max_context_bytes: {} ({:.1}MB)",
max_context_bytes,
max_context_bytes as f64 / 1_000_000.0
);
Self {
provider,
tier,
progress_callback: Some(callback),
step_counter: Arc::new(AtomicUsize::new(1)),
max_context_bytes,
}
}
/// Convert AutoAgents Tool to CodeGraph ToolDefinition
fn convert_tools(tools: &[Tool]) -> Vec<codegraph_ai::llm_provider::ToolDefinition> {
tools
.iter()
.map(|tool| {
codegraph_ai::llm_provider::ToolDefinition::function(
&tool.function.name,
&tool.function.description,
tool.function.parameters.clone(),
)
})
.collect()
}
/// Get tier-aware max_tokens, respecting environment variable override
fn get_max_tokens(&self) -> Option<usize> {
// Check for environment variable override first
if let Ok(val) = std::env::var("MCP_CODE_AGENT_MAX_OUTPUT_TOKENS") {
if let Ok(tokens) = val.parse::<usize>() {
tracing::info!("Using MCP_CODE_AGENT_MAX_OUTPUT_TOKENS={}", tokens);
return Some(tokens);
}
}
// Use tier-based defaults
let tokens = match self.tier {
ContextTier::Small => 2048,
ContextTier::Medium => 4096,
ContextTier::Large => 8192,
ContextTier::Massive => 16384,
};
Some(tokens)
}
/// Internal helper that does the actual chat call, with optional structured output
async fn chat_internal(
&self,
messages: &[ChatMessage],
tools: Option<&[Tool]>,
json_schema: Option<StructuredOutputFormat>,
) -> Result<Box<dyn ChatResponse>, LLMError> {
// Log tool and message info
let tool_count = tools.map_or(0, |t| t.len());
tracing::info!(
"📨 chat_internal() called with {} messages, {} tools",
messages.len(),
tool_count
);
// Debug: Log message roles
for (i, msg) in messages.iter().enumerate() {
tracing::debug!(
" Message {}: role={:?}, type={:?}, content_len={}",
i,
msg.role,
msg.message_type,
msg.content.len()
);
}
// Convert AutoAgents messages to CodeGraph messages
let cg_messages: Vec<Message> = messages
.iter()
.map(|msg| {
let content = match &msg.message_type {
MessageType::ToolUse(tool_calls) => {
let tool_calls_json = serde_json::to_string_pretty(tool_calls)
.unwrap_or_else(|_| "[]".to_string());
if msg.content.is_empty() {
format!("[Tool calls made]\n{}", tool_calls_json)
} else {
format!("{}\n\n[Tool calls made]\n{}", msg.content, tool_calls_json)
}
}
MessageType::ToolResult(tool_results) => {
let results_json = serde_json::to_string_pretty(tool_results)
.unwrap_or_else(|_| "[]".to_string());
if msg.content.is_empty() {
format!("[Tool results]\n{}", results_json)
} else {
format!("{}\n\n[Tool results]\n{}", msg.content, results_json)
}
}
MessageType::Text
| MessageType::Image(_)
| MessageType::Pdf(_)
| MessageType::ImageURL(_) => msg.content.clone(),
};
Message {
role: match msg.role {
ChatRole::System => MessageRole::System,
ChatRole::User => MessageRole::User,
ChatRole::Assistant => MessageRole::Assistant,
ChatRole::Tool => MessageRole::User,
},
content,
}
})
.collect();
// Safety valve: Check accumulated context size before sending to LLM
let total_context_bytes: usize = cg_messages.iter().map(|m| m.content.len()).sum();
if total_context_bytes > self.max_context_bytes {
let overflow_ratio = total_context_bytes as f64 / self.max_context_bytes as f64;
tracing::error!(
total_bytes = total_context_bytes,
max_bytes = self.max_context_bytes,
overflow_ratio = format!("{:.1}x", overflow_ratio),
message_count = cg_messages.len(),
"CONTEXT OVERFLOW: Accumulated messages exceed max_context_bytes limit"
);
// Return error instead of letting the API reject with a cryptic message
return Err(LLMError::Generic(format!(
"Context overflow: {} bytes exceeds {} byte limit ({:.1}x). \
Tool results accumulated too much data. Try reducing result limits or query scope.",
total_context_bytes,
self.max_context_bytes,
overflow_ratio
)));
}
// Log context usage for monitoring
let usage_percent = (total_context_bytes as f64 / self.max_context_bytes as f64) * 100.0;
if usage_percent > 70.0 {
tracing::warn!(
total_bytes = total_context_bytes,
max_bytes = self.max_context_bytes,
usage_percent = format!("{:.1}%", usage_percent),
"Context usage above 70% - approaching limit"
);
} else {
tracing::debug!(
total_bytes = total_context_bytes,
max_bytes = self.max_context_bytes,
usage_percent = format!("{:.1}%", usage_percent),
"Context size within limits"
);
}
// Convert AutoAgents tools to CodeGraph ToolDefinitions
let cg_tools = tools.map(Self::convert_tools);
// Debug log tools being passed to provider
if let Some(ref tools) = cg_tools {
tracing::info!(
"🛠️ Converting {} tools to CodeGraph format: {:?}",
tools.len(),
tools.iter().map(|t| &t.function.name).collect::<Vec<_>>()
);
} else {
tracing::info!("🛠️ No tools passed to CodeGraph provider");
}
// Convert AutoAgents StructuredOutputFormat to CodeGraph ResponseFormat
let response_format =
json_schema.map(
|schema| codegraph_ai::llm_provider::ResponseFormat::JsonSchema {
json_schema: codegraph_ai::llm_provider::JsonSchema {
name: schema.name,
schema: schema.schema.unwrap_or_default(),
strict: schema.strict.unwrap_or(true),
},
},
);
// Call CodeGraph LLM provider with native tool calling and structured output
let config = codegraph_ai::llm_provider::GenerationConfig {
temperature: 0.1,
max_tokens: self.get_max_tokens(),
response_format,
..Default::default()
};
let response = self
.provider
.generate_chat_with_tools(&cg_messages, cg_tools.as_deref(), &config)
.await
.map_err(|e| LLMError::Generic(e.to_string()))?;
tracing::info!(
"📬 LLM response: content_len={}, tool_calls={}, finish_reason={:?}",
response.content.len(),
response.tool_calls.as_ref().map_or(0, |tc| tc.len()),
response.finish_reason
);
// Emit step progress notification if callback is configured
if let Some(ref callback) = self.progress_callback {
let step = self.step_counter.fetch_add(1, Ordering::SeqCst);
let tool_names = response
.tool_calls
.as_ref()
.map(|tc| {
tc.iter()
.map(|t| t.function.name.as_str())
.collect::<Vec<_>>()
.join(", ")
})
.filter(|s| !s.is_empty());
let message = match tool_names {
Some(names) => format!("Step {}: Calling {}", step, names),
None => format!("Step {}: Agent reasoning...", step),
};
// Fire-and-forget progress notification (non-blocking)
let cb = callback.clone();
tokio::spawn(async move {
cb(step as f64, Some(message)).await;
});
}
// Wrap response in AutoAgents ChatResponse with native tool calls
Ok(Box::new(CodeGraphChatResponse {
content: response.content,
tool_calls: response.tool_calls,
_total_tokens: response.total_tokens.unwrap_or(0),
step_counter: Arc::new(AtomicU64::new(1)),
}))
}
}
#[async_trait]
impl ChatProvider for CodeGraphChatAdapter {
async fn chat(
&self,
messages: &[ChatMessage],
json_schema: Option<StructuredOutputFormat>,
) -> Result<Box<dyn ChatResponse>, LLMError> {
// Plain chat: no structured output schema
self.chat_internal(messages, None, json_schema).await
}
async fn chat_with_tools(
&self,
messages: &[ChatMessage],
tools: Option<&[Tool]>,
json_schema: Option<StructuredOutputFormat>,
) -> Result<Box<dyn ChatResponse>, LLMError> {
// Full-featured chat: tools + optional structured output
self.chat_internal(messages, tools, json_schema).await
}
async fn chat_stream(
&self,
_messages: &[ChatMessage],
_json_schema: Option<StructuredOutputFormat>,
) -> Result<
std::pin::Pin<Box<dyn futures::Stream<Item = Result<String, LLMError>> + Send>>,
LLMError,
> {
Err(LLMError::Generic("Streaming not supported".to_string()))
}
async fn chat_stream_struct(
&self,
_messages: &[ChatMessage],
_tools: Option<&[Tool]>,
_json_schema: Option<StructuredOutputFormat>,
) -> Result<
std::pin::Pin<
Box<
dyn futures::Stream<Item = Result<autoagents::llm::chat::StreamResponse, LLMError>>
+ Send,
>,
>,
LLMError,
> {
Err(LLMError::Generic(
"Structured streaming not supported".to_string(),
))
}
}
#[async_trait]
impl CompletionProvider for CodeGraphChatAdapter {
async fn complete(
&self,
_req: &CompletionRequest,
_json_schema: Option<StructuredOutputFormat>,
) -> Result<CompletionResponse, LLMError> {
Err(LLMError::Generic(
"Completion not supported - use ChatProvider instead".to_string(),
))
}
}
#[async_trait]
impl EmbeddingProvider for CodeGraphChatAdapter {
async fn embed(&self, _text: Vec<String>) -> Result<Vec<Vec<f32>>, LLMError> {
Err(LLMError::Generic(
"Embedding not supported - CodeGraph uses separate embedding providers".to_string(),
))
}
}
#[async_trait]
impl ModelsProvider for CodeGraphChatAdapter {
async fn list_models(
&self,
_request: Option<&ModelListRequest>,
) -> Result<Box<dyn ModelListResponse>, LLMError> {
Err(LLMError::Generic("Model listing not supported".to_string()))
}
}
// Implement the LLMProvider supertrait (combines all provider traits)
impl autoagents::llm::LLMProvider for CodeGraphChatAdapter {}
/// ChatResponse wrapper for CodeGraph LLM responses
#[derive(Debug)]
struct CodeGraphChatResponse {
content: String,
/// Native tool calls from the LLM provider (OpenAI/Anthropic tool calling)
tool_calls: Option<Vec<codegraph_ai::llm_provider::ToolCall>>,
_total_tokens: usize,
step_counter: Arc<AtomicU64>,
}
impl std::fmt::Display for CodeGraphChatResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.content)
}
}
/// Helper struct to parse CodeGraph LLM response format
#[derive(Debug, Deserialize)]
struct CodeGraphLLMResponse {
#[serde(default)]
#[allow(dead_code)]
reasoning: Option<String>,
#[serde(default)]
tool_call: Option<CodeGraphToolCall>,
}
/// Custom deserializer that accepts parameters as either:
/// - String (OpenAI strict mode): "{ \"query\": \"...\" }"
/// - Object (Ollama/Anthropic): { "query": "..." }
/// Returns a JSON string in both cases for uniform downstream handling
fn deserialize_parameters<'de, D>(deserializer: D) -> Result<String, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::{self, Visitor};
use std::fmt;
struct ParametersVisitor;
impl<'de> Visitor<'de> for ParametersVisitor {
type Value = String;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a JSON string or object for tool parameters")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
// Already a string (OpenAI strict mode)
Ok(value.to_string())
}
fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(value)
}
fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
where
A: de::MapAccess<'de>,
{
// Object - serialize to JSON string (Ollama/Anthropic)
let value = serde_json::Value::deserialize(de::value::MapAccessDeserializer::new(map))
.map_err(de::Error::custom)?;
serde_json::to_string(&value).map_err(de::Error::custom)
}
}
deserializer.deserialize_any(ParametersVisitor)
}
#[derive(Debug, Deserialize)]
struct CodeGraphToolCall {
#[serde(alias = "name", alias = "function", alias = "tool")]
tool_name: String,
/// Parameters as JSON string - accepts both string (OpenAI strict) and object (Ollama/Anthropic)
#[serde(
alias = "parameters",
alias = "arguments",
alias = "args",
deserialize_with = "deserialize_parameters"
)]
parameters_json: String,
}
// Static counter for generating unique tool call IDs
static TOOL_CALL_COUNTER: AtomicU64 = AtomicU64::new(0);
impl ChatResponse for CodeGraphChatResponse {
fn text(&self) -> Option<String> {
Some(self.content.clone())
}
fn tool_calls(&self) -> Option<Vec<ToolCall>> {
tracing::info!(
"tool_calls() called with content length: {}, has native tool_calls: {}",
self.content.len(),
self.tool_calls.is_some()
);
// First, check for native tool calls from provider (OpenAI/Anthropic tool calling API)
if let Some(ref native_calls) = self.tool_calls {
if !native_calls.is_empty() {
tracing::info!(
"Using {} native tool calls from provider",
native_calls.len()
);
let step_number = self.step_counter.fetch_add(1, Ordering::SeqCst) as usize;
let tool_names: Vec<&str> = native_calls
.iter()
.map(|t| t.function.name.as_str())
.collect();
DebugLogger::log_reasoning_step(
step_number,
"Native tool calling",
Some(&tool_names.join(", ")),
);
// Convert CodeGraph ToolCall to AutoAgents ToolCall
let autoagents_calls: Vec<ToolCall> = native_calls
.iter()
.map(|tc| ToolCall {
id: tc.id.clone(),
call_type: tc.call_type.clone(),
function: FunctionCall {
name: tc.function.name.clone(),
arguments: tc.function.arguments.clone(),
},
})
.collect();
for call in &autoagents_calls {
tracing::info!(
"Returning native tool call: name='{}', args='{}', id='{}'",
call.function.name,
call.function.arguments,
call.id
);
}
return Some(autoagents_calls);
}
}
// Fallback: Try to parse JSON response (legacy prompt-based tool calling)
tracing::debug!(
"No native tool calls, trying JSON parsing. Content preview: {}",
&self.content.chars().take(200).collect::<String>()
);
match serde_json::from_str::<CodeGraphLLMResponse>(&self.content) {
Ok(parsed) => {
tracing::info!(
"Parsed legacy JSON format. has_tool_call={}",
parsed.tool_call.is_some()
);
let step_number = self.step_counter.fetch_add(1, Ordering::SeqCst) as usize;
let thought = parsed.reasoning.as_deref().unwrap_or("");
let action = parsed.tool_call.as_ref().map(|t| t.tool_name.as_str());
DebugLogger::log_reasoning_step(step_number, thought, action);
// If there's a tool_call, execute it
if let Some(tool_call) = parsed.tool_call {
let arguments = tool_call.parameters_json.clone();
let call_id = TOOL_CALL_COUNTER.fetch_add(1, Ordering::SeqCst);
let autoagents_tool_call = ToolCall {
id: format!("call_{}", call_id),
call_type: "function".to_string(),
function: FunctionCall {
name: tool_call.tool_name.clone(),
arguments: arguments.clone(),
},
};
tracing::info!(
"Returning legacy tool call: name='{}', args='{}', id='{}'",
tool_call.tool_name,
arguments,
autoagents_tool_call.id
);
return Some(vec![autoagents_tool_call]);
} else {
tracing::info!("No tool_call field in parsed response");
}
}
Err(e) => {
// Not a JSON response - that's expected with native tool calling
tracing::debug!(
"Response is not JSON format (expected with native tool calling): {}",
e
);
}
}
tracing::info!("tool_calls() returning None - agent should complete");
None
}
}
// ============================================================================
// Tier-Aware ReAct Agent Wrapper
// ============================================================================
use autoagents::core::agent::prebuilt::executor::ReActAgent;
use autoagents::core::agent::{
AgentDeriveT, AgentExecutor, AgentHooks, Context, DirectAgentHandle, ExecutorConfig,
};
use autoagents::core::tool::{shared_tools_to_boxes, ToolT};
/// Wrapper around ReActAgent that overrides max_turns configuration
/// This allows tier-aware max_turns without forking AutoAgents
#[derive(Debug)]
pub struct TierAwareReActAgent<T: AgentDeriveT> {
inner: ReActAgent<T>,
inner_derive: Arc<T>,
max_turns: usize,
}
impl<T: AgentDeriveT + AgentHooks + Clone> TierAwareReActAgent<T> {
pub fn new(agent: T, max_turns: usize) -> Self {
let agent_arc = Arc::new(agent);
Self {
inner: ReActAgent::new((*agent_arc).clone()),
inner_derive: agent_arc,
max_turns,
}
}
}
impl<T: AgentDeriveT + AgentHooks + Clone> AgentDeriveT for TierAwareReActAgent<T> {
type Output = T::Output;
fn description(&self) -> &str {
self.inner_derive.description()
}
fn name(&self) -> &str {
self.inner_derive.name()
}
fn output_schema(&self) -> Option<serde_json::Value> {
self.inner_derive.output_schema()
}
fn tools(&self) -> Vec<Box<dyn ToolT>> {
self.inner_derive.tools()
}
}
impl<T: AgentDeriveT + AgentHooks + Clone> AgentHooks for TierAwareReActAgent<T> {}
impl<T: AgentDeriveT + AgentHooks + Clone> Clone for TierAwareReActAgent<T> {
fn clone(&self) -> Self {
Self {
inner: ReActAgent::new((*self.inner_derive).clone()),
inner_derive: Arc::clone(&self.inner_derive),
max_turns: self.max_turns,
}
}
}
#[async_trait]
impl<T: AgentDeriveT + AgentHooks + Clone> AgentExecutor for TierAwareReActAgent<T> {
type Output = <ReActAgent<T> as AgentExecutor>::Output;
type Error = <ReActAgent<T> as AgentExecutor>::Error;
fn config(&self) -> ExecutorConfig {
ExecutorConfig {
max_turns: self.max_turns,
}
}
async fn execute(
&self,
task: &autoagents::core::agent::task::Task,
context: Arc<Context>,
) -> Result<Self::Output, Self::Error> {
self.inner.execute(task, context).await
}
async fn execute_stream(
&self,
task: &autoagents::core::agent::task::Task,
context: Arc<Context>,
) -> Result<
std::pin::Pin<Box<dyn futures::Stream<Item = Result<Self::Output, Self::Error>> + Send>>,
Self::Error,
> {
self.inner.execute_stream(task, context).await
}
}
// ============================================================================
// Agent Builder
// ============================================================================
use crate::autoagents::tier_plugin::TierAwarePromptPlugin;
use crate::autoagents::tools::graph_tools::*;
use crate::autoagents::tools::tool_executor_adapter::GraphToolFactory;
use codegraph_mcp_core::analysis::AnalysisType;
use codegraph_mcp_tools::GraphToolExecutor;
use crate::autoagents::codegraph_agent::CodeGraphAgentOutput;
use autoagents::core::agent::memory::SlidingWindowMemory;
use autoagents::core::agent::AgentBuilder;
use autoagents::core::error::Error as AutoAgentsError;
/// Agent implementation for CodeGraph with manual tool registration
#[derive(Debug, Clone)]
pub struct CodeGraphReActAgent {
tools: Vec<Arc<dyn ToolT>>,
system_prompt: String,
analysis_type: AnalysisType,
#[allow(dead_code)]
max_iterations: usize,
}
impl AgentDeriveT for CodeGraphReActAgent {
type Output = CodeGraphAgentOutput;
fn description(&self) -> &str {
&self.system_prompt
}
fn name(&self) -> &str {
"codegraph_agent"
}
fn output_schema(&self) -> Option<serde_json::Value> {
use codegraph_ai::agentic_schemas::*;
use schemars::schema_for;
// Return the appropriate schema based on analysis type
let schema = match self.analysis_type {
AnalysisType::CodeSearch => schema_for!(CodeSearchOutput),
AnalysisType::DependencyAnalysis => schema_for!(DependencyAnalysisOutput),
AnalysisType::CallChainAnalysis => schema_for!(CallChainOutput),
AnalysisType::ArchitectureAnalysis => schema_for!(ArchitectureAnalysisOutput),
AnalysisType::ApiSurfaceAnalysis => schema_for!(APISurfaceOutput),
AnalysisType::ContextBuilder => schema_for!(ContextBuilderOutput),
AnalysisType::SemanticQuestion => schema_for!(SemanticQuestionOutput),
AnalysisType::ComplexityAnalysis => schema_for!(ComplexityAnalysisOutput),
};
serde_json::to_value(schema).ok()
}
fn tools(&self) -> Vec<Box<dyn ToolT>> {
shared_tools_to_boxes(&self.tools)
}
}
impl AgentHooks for CodeGraphReActAgent {}
/// Builder for CodeGraph AutoAgents workflows
pub struct CodeGraphAgentBuilder {
llm_adapter: Arc<CodeGraphChatAdapter>,
tool_factory: GraphToolFactory,
tier: ContextTier,
analysis_type: AnalysisType,
}
impl CodeGraphAgentBuilder {
pub fn new(
llm_provider: Arc<dyn codegraph_ai::llm_provider::LLMProvider>,
tool_executor: Arc<GraphToolExecutor>,
tier: ContextTier,
analysis_type: AnalysisType,
) -> Self {
Self {
llm_adapter: Arc::new(CodeGraphChatAdapter::new(llm_provider, tier)),
tool_factory: GraphToolFactory::new(tool_executor),
tier,
analysis_type,
}
}
/// Create builder with progress callback for step-by-step notifications
pub fn with_progress_callback(
llm_provider: Arc<dyn codegraph_ai::llm_provider::LLMProvider>,
tool_executor: Arc<GraphToolExecutor>,
tier: ContextTier,
analysis_type: AnalysisType,
callback: ProgressCallback,
) -> Self {
Self {
llm_adapter: Arc::new(CodeGraphChatAdapter::with_progress_callback(
llm_provider,
tier,
callback,
)),
tool_factory: GraphToolFactory::new(tool_executor),
tier,
analysis_type,
}
}
pub async fn build(self) -> Result<AgentHandle, AutoAgentsError> {
// Get tier-aware configuration and system prompt
let tier_plugin = TierAwarePromptPlugin::new(self.analysis_type, self.tier);
let system_prompt = tier_plugin
.get_system_prompt()
.map_err(|e| AutoAgentsError::CustomError(e.to_string()))?;
// Create memory with fixed default of 40 messages for all tiers.
// 40 messages allows proper multi-step analysis without context issues.
let memory_size = read_memory_window_config();
tracing::debug!(
memory_window = memory_size,
tier = ?self.tier,
"Agent memory window configured"
);
let memory = Box::new(SlidingWindowMemory::new(memory_size));
// Get executor adapter for tool construction
let executor_adapter = self.tool_factory.adapter();
// Manually construct all tools with the executor (Arc-wrapped for sharing)
let tools: Vec<Arc<dyn ToolT>> = vec![
Arc::new(SemanticCodeSearch::new(executor_adapter.clone())),
Arc::new(GetTransitiveDependencies::new(executor_adapter.clone())),
Arc::new(GetReverseDependencies::new(executor_adapter.clone())),
Arc::new(TraceCallChain::new(executor_adapter.clone())),
Arc::new(DetectCycles::new(executor_adapter.clone())),
Arc::new(CalculateCoupling::new(executor_adapter.clone())),
Arc::new(GetHubNodes::new(executor_adapter.clone())),
Arc::new(FindComplexityHotspots::new(executor_adapter.clone())),
];
// Get tier-aware (or env-overridden) max iterations
let max_iterations = tier_plugin.get_max_iterations();
tracing::info!(
"Setting ReActAgent max_turns={} for tier={:?}",
max_iterations,
self.tier
);
// Create CodeGraph agent with tools and tier-aware system prompt
let codegraph_agent = CodeGraphReActAgent {
tools,
system_prompt,
analysis_type: self.analysis_type,
max_iterations,
};
// Wrap in TierAwareReActAgent to override max_turns configuration
let tier_aware_agent = TierAwareReActAgent::new(codegraph_agent, max_iterations);
// Build full agent with configuration
// System prompt injected via AgentDeriveT::description() using Box::leak pattern
use autoagents::core::agent::DirectAgent;
let agent = AgentBuilder::<_, DirectAgent>::new(tier_aware_agent)
.llm(self.llm_adapter)
.memory(memory)
.build()
.await?;
Ok(AgentHandle {
agent,
tier: self.tier,
analysis_type: self.analysis_type,
})
}
}
/// Handle for executing CodeGraph agent
pub struct AgentHandle {
pub agent: DirectAgentHandle<TierAwareReActAgent<CodeGraphReActAgent>>,
pub tier: ContextTier,
pub analysis_type: AnalysisType,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_message_conversion_user() {
let cg_msg = Message {
role: MessageRole::User,
content: "Hello".to_string(),
};
let aa_msg = convert_to_chat_message(&cg_msg);
assert_eq!(aa_msg.role, ChatRole::User);
assert_eq!(aa_msg.content, "Hello");
}
#[test]
fn test_message_conversion_system() {
let cg_msg = Message {
role: MessageRole::System,
content: "You are helpful".to_string(),
};
let aa_msg = convert_to_chat_message(&cg_msg);
assert_eq!(aa_msg.role, ChatRole::System);
}
#[test]
fn test_message_conversion_assistant() {
let cg_msg = Message {
role: MessageRole::Assistant,
content: "I can help".to_string(),
};
let aa_msg = convert_to_chat_message(&cg_msg);
assert_eq!(aa_msg.role, ChatRole::Assistant);
}
#[test]
fn test_convert_messages_batch() {
let cg_messages = vec![
Message {
role: MessageRole::System,
content: "System".to_string(),
},
Message {
role: MessageRole::User,
content: "User".to_string(),
},
];
let aa_messages = convert_messages(&cg_messages);
assert_eq!(aa_messages.len(), 2);
assert_eq!(aa_messages[0].role, ChatRole::System);
assert_eq!(aa_messages[1].role, ChatRole::User);
}
#[test]
fn test_tool_calls_accepts_name_arguments_fields() {
let response = CodeGraphChatResponse {
content: r#"{
"reasoning": "Plan",
"tool_call": {
"name": "get_hub_nodes",
"arguments": {
"min_degree": 4
}
}
}"#
.to_string(),
tool_calls: None,
_total_tokens: 0,
step_counter: Arc::new(AtomicU64::new(1)),
};
let tool_calls = response.tool_calls().expect("tool call not parsed");
assert_eq!(tool_calls.len(), 1);