-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Expand file tree
/
Copy pathmod.rs
More file actions
900 lines (786 loc) · 31.4 KB
/
mod.rs
File metadata and controls
900 lines (786 loc) · 31.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
use crate::conversation::message::{ActionRequiredData, MessageMetadata};
use crate::conversation::message::{Message, MessageContent};
use crate::conversation::{merge_consecutive_messages, Conversation};
use crate::prompt_template::render_template;
#[cfg(test)]
use crate::providers::base::{stream_from_single_message, MessageStream};
use crate::providers::base::{Provider, ProviderUsage};
use crate::providers::errors::ProviderError;
use crate::{config::Config, token_counter::create_token_counter};
use anyhow::Result;
use indoc::indoc;
use rmcp::model::Role;
use serde::Serialize;
use std::sync::Arc;
use tokio::task::JoinHandle;
use tracing::info;
use tracing::log::warn;
pub const DEFAULT_COMPACTION_THRESHOLD: f64 = 0.8;
/// Feature flag to enable/disable tool pair summarization.
/// Set to `false` to disable summarizing old tool call/response pairs.
/// TODO: Re-enable once tool summarization stability issues are resolved.
const ENABLE_TOOL_PAIR_SUMMARIZATION: bool = false;
const CONVERSATION_CONTINUATION_TEXT: &str =
"Your context was compacted. The previous message contains a summary of the conversation so far.
Do not mention that you read a summary or that conversation summarization occurred.
Just continue the conversation naturally based on the summarized context.";
const TOOL_LOOP_CONTINUATION_TEXT: &str =
"Your context was compacted. The previous message contains a summary of the conversation so far.
Do not mention that you read a summary or that conversation summarization occurred.
Continue calling tools as necessary to complete the task.";
const MANUAL_COMPACT_CONTINUATION_TEXT: &str =
"Your context was compacted at the user's request. The previous message contains a summary of the conversation so far.
Do not mention that you read a summary or that conversation summarization occurred.
Just continue the conversation naturally based on the summarized context.";
#[derive(Serialize)]
struct SummarizeContext {
messages: String,
}
/// Compact messages by summarizing them
///
/// This function performs the actual compaction by summarizing messages and updating
/// their visibility metadata. It does not check thresholds - use `check_if_compaction_needed`
/// first to determine if compaction is necessary.
///
/// # Arguments
/// * `provider` - The provider to use for summarization
/// * `session_id` - The session to use for summarization
/// * `conversation` - The current conversation history
/// * `manual_compact` - If true, this is a manual compaction (don't preserve user message)
///
/// # Returns
/// * A tuple containing:
/// - `Conversation`: The compacted messages
/// - `ProviderUsage`: Provider usage from summarization
pub async fn compact_messages(
provider: &dyn Provider,
session_id: &str,
conversation: &Conversation,
manual_compact: bool,
) -> Result<(Conversation, ProviderUsage)> {
info!("Performing message compaction");
let messages = conversation.messages();
let has_text_only = |msg: &Message| {
let has_text = msg
.content
.iter()
.any(|c| matches!(c, MessageContent::Text(_)));
let has_tool_content = msg.content.iter().any(|c| {
matches!(
c,
MessageContent::ToolRequest(_) | MessageContent::ToolResponse(_)
)
});
has_text && !has_tool_content
};
let extract_text = |msg: &Message| -> Option<String> {
let text_parts: Vec<String> = msg
.content
.iter()
.filter_map(|c| {
if let MessageContent::Text(text) = c {
Some(text.text.clone())
} else {
None
}
})
.collect();
if text_parts.is_empty() {
None
} else {
Some(text_parts.join("\n"))
}
};
// Find and preserve the most recent user message for non-manual compacts
let (preserved_user_message, is_most_recent) = if !manual_compact {
let found_msg = messages.iter().enumerate().rev().find(|(_, msg)| {
msg.is_agent_visible()
&& matches!(msg.role, rmcp::model::Role::User)
&& has_text_only(msg)
});
if let Some((idx, msg)) = found_msg {
let is_last = idx == messages.len() - 1;
(Some(msg.clone()), is_last)
} else {
(None, false)
}
} else {
(None, false)
};
let messages_to_compact = messages.as_slice();
let (summary_message, summarization_usage) =
do_compact(provider, session_id, messages_to_compact).await?;
// Create the final message list with updated visibility metadata:
// 1. Original messages become user_visible but not agent_visible
// 2. Summary message becomes agent_visible but not user_visible
// 3. Assistant messages to continue the conversation are also agent_visible but not user_visible
let mut final_messages = Vec::new();
for (idx, msg) in messages_to_compact.iter().enumerate() {
let updated_metadata = if is_most_recent
&& idx == messages_to_compact.len() - 1
&& preserved_user_message.is_some()
{
// This is the most recent message and we're preserving it by adding a fresh copy
MessageMetadata::invisible()
} else {
msg.metadata.with_agent_invisible()
};
let updated_msg = msg.clone().with_metadata(updated_metadata);
final_messages.push(updated_msg);
}
let summary_msg = summary_message.with_metadata(MessageMetadata::agent_only());
let mut continuation_messages = vec![summary_msg];
let continuation_text = if manual_compact {
MANUAL_COMPACT_CONTINUATION_TEXT
} else if is_most_recent {
CONVERSATION_CONTINUATION_TEXT
} else {
TOOL_LOOP_CONTINUATION_TEXT
};
let continuation_msg = Message::assistant()
.with_text(continuation_text)
.with_metadata(MessageMetadata::agent_only());
continuation_messages.push(continuation_msg);
let (merged_continuation, _issues) = merge_consecutive_messages(continuation_messages);
final_messages.extend(merged_continuation);
if let Some(user_msg) = preserved_user_message {
if let Some(text) = extract_text(&user_msg) {
final_messages.push(Message::user().with_text(&text));
}
}
Ok((
Conversation::new_unvalidated(final_messages),
summarization_usage,
))
}
/// Check if messages exceed the auto-compaction threshold
pub async fn check_if_compaction_needed(
provider: &dyn Provider,
conversation: &Conversation,
threshold_override: Option<f64>,
session: &crate::session::Session,
) -> Result<bool> {
let messages = conversation.messages();
let config = Config::global();
let threshold = threshold_override.unwrap_or_else(|| {
config
.get_param::<f64>("GOOSE_AUTO_COMPACT_THRESHOLD")
.unwrap_or(DEFAULT_COMPACTION_THRESHOLD)
});
let context_limit = provider.get_model_config().context_limit();
let (current_tokens, _token_source) = match session.total_tokens {
Some(tokens) => (tokens as usize, "session metadata"),
None => {
let token_counter = create_token_counter()
.await
.map_err(|e| anyhow::anyhow!("Failed to create token counter: {}", e))?;
let token_counts: Vec<_> = messages
.iter()
.filter(|m| m.is_agent_visible())
.map(|msg| token_counter.count_chat_tokens("", std::slice::from_ref(msg), &[]))
.collect();
(token_counts.iter().sum(), "estimated")
}
};
let usage_ratio = current_tokens as f64 / context_limit as f64;
let needs_compaction = if threshold <= 0.0 || threshold >= 1.0 {
false // Auto-compact is disabled.
} else {
usage_ratio > threshold
};
Ok(needs_compaction)
}
fn filter_tool_responses(messages: &[Message], remove_percent: u32) -> Vec<&Message> {
fn has_tool_response(msg: &Message) -> bool {
msg.content
.iter()
.any(|c| matches!(c, MessageContent::ToolResponse(_)))
}
if remove_percent == 0 {
return messages.iter().collect();
}
let tool_indices: Vec<usize> = messages
.iter()
.enumerate()
.filter(|(_, msg)| has_tool_response(msg))
.map(|(i, _)| i)
.collect();
if tool_indices.is_empty() {
return messages.iter().collect();
}
let num_to_remove = ((tool_indices.len() * remove_percent as usize) / 100).max(1);
let middle = tool_indices.len() / 2;
let mut indices_to_remove = Vec::new();
// Middle out
for i in 0..num_to_remove {
if i % 2 == 0 {
let offset = i / 2;
if middle > offset {
indices_to_remove.push(tool_indices[middle - offset - 1]);
}
} else {
let offset = i / 2;
if middle + offset < tool_indices.len() {
indices_to_remove.push(tool_indices[middle + offset]);
}
}
}
messages
.iter()
.enumerate()
.filter(|(i, _)| !indices_to_remove.contains(i))
.map(|(_, msg)| msg)
.collect()
}
async fn do_compact(
provider: &dyn Provider,
session_id: &str,
messages: &[Message],
) -> Result<(Message, ProviderUsage), anyhow::Error> {
let agent_visible_messages: Vec<Message> = messages
.iter()
.filter(|msg| msg.is_agent_visible())
.map(|msg| msg.agent_visible_content())
.collect();
// Try progressively removing more tool response messages from the middle to reduce context length
let removal_percentages = [0, 10, 20, 50, 100];
for (attempt, &remove_percent) in removal_percentages.iter().enumerate() {
let filtered_messages = filter_tool_responses(&agent_visible_messages, remove_percent);
let messages_text = filtered_messages
.iter()
.map(|&msg| format_message_for_compacting(msg))
.collect::<Vec<_>>()
.join("\n");
let context = SummarizeContext {
messages: messages_text,
};
let system_prompt = render_template("compaction.md", &context)?;
let user_message = Message::user()
.with_text("Please summarize the conversation history provided in the system prompt.");
let summarization_request = vec![user_message];
match provider
.complete_fast(session_id, &system_prompt, &summarization_request, &[])
.await
{
Ok((mut response, mut provider_usage)) => {
response.role = Role::User;
provider_usage
.ensure_tokens(&system_prompt, &summarization_request, &response, &[])
.await
.map_err(|e| anyhow::anyhow!("Failed to ensure usage tokens: {}", e))?;
return Ok((response, provider_usage));
}
Err(e) => {
if matches!(e, ProviderError::ContextLengthExceeded(_)) {
if attempt < removal_percentages.len() - 1 {
continue;
} else {
return Err(anyhow::anyhow!(
"Failed to compact: context limit exceeded even after removing all tool responses"
));
}
}
return Err(e.into());
}
}
}
Err(anyhow::anyhow!(
"Unexpected: exhausted all attempts without returning"
))
}
fn format_message_for_compacting(msg: &Message) -> String {
let content_parts: Vec<String> = msg
.content
.iter()
.filter_map(|content| match content {
MessageContent::Text(text) => Some(text.text.clone()),
MessageContent::Image(img) => Some(format!("[image: {}]", img.mime_type)),
MessageContent::ToolRequest(req) => {
if let Ok(call) = &req.tool_call {
Some(format!(
"tool_request({}): {}",
call.name,
serde_json::to_string(&call.arguments)
.unwrap_or_else(|_| "<<invalid json>>".to_string())
))
} else {
Some("tool_request: [error]".to_string())
}
}
MessageContent::ToolResponse(res) => {
if let Ok(result) = &res.tool_result {
let text_items: Vec<String> = result
.content
.iter()
.filter_map(|content| {
content.as_text().map(|text_str| text_str.text.clone())
})
.collect();
if !text_items.is_empty() {
Some(format!("tool_response: {}", text_items.join("\n")))
} else {
Some("tool_response: [non-text content]".to_string())
}
} else {
Some("tool_response: [error]".to_string())
}
}
MessageContent::ToolConfirmationRequest(req) => {
Some(format!("tool_confirmation_request: {}", req.tool_name))
}
MessageContent::ActionRequired(action) => match &action.data {
ActionRequiredData::ToolConfirmation { tool_name, .. } => {
Some(format!("action_required(tool_confirmation): {}", tool_name))
}
ActionRequiredData::Elicitation { message, .. } => {
Some(format!("action_required(elicitation): {}", message))
}
ActionRequiredData::ElicitationResponse { id, .. } => {
Some(format!("action_required(elicitation_response): {}", id))
}
},
MessageContent::FrontendToolRequest(req) => {
if let Ok(call) = &req.tool_call {
Some(format!("frontend_tool_request: {}", call.name))
} else {
Some("frontend_tool_request: [error]".to_string())
}
}
MessageContent::Thinking(_) => None,
MessageContent::RedactedThinking(_) => None,
MessageContent::SystemNotification(notification) => {
Some(format!("system_notification: {}", notification.msg))
}
MessageContent::Reasoning(_) => None,
})
.collect();
let role_str = match msg.role {
Role::User => "user",
Role::Assistant => "assistant",
};
if content_parts.is_empty() {
format!("[{}]: <empty message>", role_str)
} else {
format!("[{}]: {}", role_str, content_parts.join("\n"))
}
}
/// Find the id of a tool call to summarize. We only do this if we have more than
/// cutoff tool calls that aren't summarized yet
pub fn tool_id_to_summarize(conversation: &Conversation, cutoff: usize) -> Option<String> {
let messages = conversation.messages();
let mut tool_call_count = 0;
let mut first_tool_call_id = None;
for msg in messages.iter() {
if !msg.is_agent_visible() {
continue;
}
for content in &msg.content {
if let MessageContent::ToolRequest(req) = content {
if first_tool_call_id.is_none() {
first_tool_call_id = Some(req.id.clone());
}
tool_call_count += 1;
if tool_call_count > cutoff {
return first_tool_call_id;
}
}
}
}
None
}
pub async fn summarize_tool_call(
provider: &dyn Provider,
session_id: &str,
conversation: &Conversation,
tool_id: &str,
) -> Result<Message> {
let messages = conversation.messages();
let matching_messages: Vec<&Message> = messages
.iter()
.filter(|m| {
m.content.iter().any(|c| match c {
MessageContent::ToolRequest(req) => req.id == tool_id,
MessageContent::ToolResponse(resp) => resp.id == tool_id,
_ => false,
})
})
.collect();
if matching_messages.is_empty() {
return Err(anyhow::anyhow!(
"No messages found for tool id: {}",
tool_id
));
}
let formatted = matching_messages
.iter()
.map(|msg| format_message_for_compacting(msg))
.collect::<Vec<_>>()
.join("\n");
let user_message = Message::user().with_text(formatted);
let summarization_request = vec![user_message];
let system_prompt = indoc! {r#"
Your task is to summarize a tool call & response pair to save tokens
reply with a single message that describe what happened. Typically a toolcall
is asks for something using a bunch of parameters and then the result is also some
structured output. So the tool might ask to look up something on github and the
reply might be a json document. So you could reply with something like:
"A call to github was made to get the project status"
if that is what it was.
"#};
let (mut response, _) = provider
.complete_fast(session_id, system_prompt, &summarization_request, &[])
.await?;
response.role = Role::User;
response.created = matching_messages.last().unwrap().created;
response.metadata = MessageMetadata::agent_only();
Ok(response.with_generated_id())
}
pub fn maybe_summarize_tool_pair(
provider: Arc<dyn Provider>,
session_id: String,
conversation: Conversation,
cutoff: usize,
) -> JoinHandle<Option<(Message, String)>> {
tokio::spawn(async move {
// Tool pair summarization is currently disabled via feature flag.
// See ENABLE_TOOL_PAIR_SUMMARIZATION constant above.
if !ENABLE_TOOL_PAIR_SUMMARIZATION {
return None;
}
if let Some(tool_id) = tool_id_to_summarize(&conversation, cutoff) {
match summarize_tool_call(provider.as_ref(), &session_id, &conversation, &tool_id).await
{
Ok(summary) => Some((summary, tool_id)),
Err(e) => {
warn!("Failed to summarize tool pair: {}", e);
None
}
}
} else {
None
}
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
model::ModelConfig,
providers::{base::Usage, errors::ProviderError},
};
use async_trait::async_trait;
use rmcp::model::{AnnotateAble, CallToolRequestParams, RawContent, Tool};
struct MockProvider {
message: Message,
config: ModelConfig,
max_tool_responses: Option<usize>,
}
impl MockProvider {
fn new(message: Message, context_limit: usize) -> Self {
Self {
message,
config: ModelConfig {
model_name: "test".to_string(),
context_limit: Some(context_limit),
temperature: None,
max_tokens: None,
toolshim: false,
toolshim_model: None,
fast_model_config: None,
request_params: None,
reasoning: None,
},
max_tool_responses: None,
}
}
fn with_max_tool_responses(mut self, max: usize) -> Self {
self.max_tool_responses = Some(max);
self
}
}
#[async_trait]
impl Provider for MockProvider {
fn get_name(&self) -> &str {
"mock"
}
async fn stream(
&self,
_model_config: &ModelConfig,
_session_id: &str,
_system: &str,
messages: &[Message],
_tools: &[Tool],
) -> Result<MessageStream, ProviderError> {
// If max_tool_responses is set, fail if we have too many
if let Some(max) = self.max_tool_responses {
let tool_response_count = messages
.iter()
.filter(|m| {
m.content
.iter()
.any(|c| matches!(c, MessageContent::ToolResponse(_)))
})
.count();
if tool_response_count > max {
return Err(ProviderError::ContextLengthExceeded(format!(
"Too many tool responses: {} > {}",
tool_response_count, max
)));
}
}
let message = self.message.clone();
let usage = ProviderUsage::new("mock-model".to_string(), Usage::default());
Ok(stream_from_single_message(message, usage))
}
fn get_model_config(&self) -> ModelConfig {
self.config.clone()
}
}
#[tokio::test]
async fn test_keeps_tool_request() {
let response_message = Message::assistant().with_text("<mock summary>");
let provider = MockProvider::new(response_message, 1);
let basic_conversation = vec![
Message::user().with_text("read hello.txt"),
Message::assistant()
.with_tool_request("tool_0", Ok(CallToolRequestParams::new("read_file"))),
Message::user().with_tool_response(
"tool_0",
Ok(rmcp::model::CallToolResult::success(vec![
RawContent::text("hello, world").no_annotation(),
])),
),
];
let conversation = Conversation::new_unvalidated(basic_conversation);
let (compacted_conversation, _usage) =
compact_messages(&provider, "test-session-id", &conversation, false)
.await
.unwrap();
let agent_conversation = compacted_conversation.agent_visible_messages();
let _ = Conversation::new(agent_conversation)
.expect("compaction should produce a valid conversation");
}
#[tokio::test]
async fn test_progressive_removal_on_context_exceeded() {
let response_message = Message::assistant().with_text("<mock summary>");
// Set max to 2 tool responses - will trigger progressive removal
let provider = MockProvider::new(response_message, 1000).with_max_tool_responses(2);
// Create a conversation with many tool responses
let mut messages = vec![Message::user().with_text("start")];
for i in 0..10 {
messages.push(Message::assistant().with_tool_request(
format!("tool_{}", i),
Ok(CallToolRequestParams::new("read_file")),
));
messages.push(Message::user().with_tool_response(
format!("tool_{}", i),
Ok(rmcp::model::CallToolResult::success(vec![
RawContent::text(format!("response{}", i)).no_annotation(),
])),
));
}
let conversation = Conversation::new_unvalidated(messages);
let result = compact_messages(&provider, "test-session-id", &conversation, false).await;
assert!(
result.is_ok(),
"Should succeed with progressive removal: {:?}",
result.err()
);
}
#[tokio::test]
async fn test_tool_pair_summarization_workflow() {
fn create_tool_pair(
call_id: &str,
response_id: &str,
tool_name: &str,
response_text: &str,
) -> Vec<Message> {
vec![
Message::assistant()
.with_tool_request(
call_id,
Ok(CallToolRequestParams::new(tool_name.to_string())),
)
.with_id(call_id),
Message::user()
.with_tool_response(
call_id,
Ok(rmcp::model::CallToolResult::success(vec![
RawContent::text(response_text).no_annotation(),
])),
)
.with_id(response_id),
]
}
let summary_response = Message::assistant()
.with_text("Tool call to list files and response with file listing");
let provider = MockProvider::new(summary_response, 1000);
let mut messages = vec![Message::user().with_text("list files").with_id("msg_1")];
messages.extend(create_tool_pair(
"call1",
"response1",
"shell",
"file1.txt\nfile2.txt",
));
messages.extend(create_tool_pair(
"call2",
"response2",
"read_file",
"content of file1",
));
messages.extend(create_tool_pair(
"call3",
"response3",
"read_file",
"content of file2",
));
let conversation = Conversation::new_unvalidated(messages);
let result = tool_id_to_summarize(&conversation, 2);
assert!(
result.is_some(),
"Should return a pair to summarize when tool calls exceed cutoff"
);
let tool_call_id = result.unwrap();
assert_eq!(tool_call_id, "call1");
let summary = summarize_tool_call(&provider, "test-session", &conversation, &tool_call_id)
.await
.unwrap();
assert_eq!(summary.role, Role::User);
assert!(summary.metadata.agent_visible);
assert!(!summary.metadata.user_visible);
let mut updated_messages = conversation.messages().clone();
for msg in updated_messages.iter_mut() {
let has_matching_content = msg.content.iter().any(|c| match c {
MessageContent::ToolRequest(req) => req.id == tool_call_id,
MessageContent::ToolResponse(resp) => resp.id == tool_call_id,
_ => false,
});
if has_matching_content {
msg.metadata = msg.metadata.with_agent_invisible();
}
}
updated_messages.push(summary);
let updated_conversation = Conversation::new_unvalidated(updated_messages);
let messages = updated_conversation.messages();
let call1_msg = messages
.iter()
.find(|m| m.id.as_deref() == Some("call1"))
.unwrap();
assert!(
!call1_msg.is_agent_visible(),
"Original call should not be agent visible"
);
let response1_msg = messages
.iter()
.find(|m| m.id.as_deref() == Some("response1"))
.unwrap();
assert!(
!response1_msg.is_agent_visible(),
"Original response should not be agent visible"
);
let summary_msg = messages
.iter()
.find(|m| {
m.metadata.agent_visible
&& !m.metadata.user_visible
&& m.as_concat_text().contains("Tool call")
})
.unwrap();
assert!(
!summary_msg.is_user_visible(),
"Summary should not be user visible"
);
let result = tool_id_to_summarize(&updated_conversation, 3);
assert!(result.is_none(), "Nothing left to summarize");
}
// Control test: after compaction + appending new tool calls, fix_conversation
// produces zero issues. Proves compaction output is structurally clean and
// compatible with the fix pipeline when new tool pairs are added.
#[tokio::test]
async fn test_compaction_output_with_new_tool_pair_is_valid() {
let response_message = Message::assistant().with_text("<mock summary>");
let provider = MockProvider::new(response_message, 1000);
// Pre-compaction conversation: user text, 3 tool pairs, user text at end
let mut messages = vec![Message::user().with_text("Help me with a task")];
for i in 0..3 {
messages.push(Message::assistant().with_tool_request(
format!("old_tool_{}", i),
Ok(CallToolRequestParams::new("some_tool")),
));
messages.push(Message::user().with_tool_response(
format!("old_tool_{}", i),
Ok(rmcp::model::CallToolResult::success(vec![
RawContent::text(format!("result {}", i)).no_annotation(),
])),
));
}
messages.push(Message::user().with_text("Now do something else"));
let conversation = Conversation::new_unvalidated(messages);
let (compacted, _usage) =
compact_messages(&provider, "test-session-id", &conversation, false)
.await
.unwrap();
// Simulate post-compaction agent loop: LLM makes a new tool call, tool executes
let new_asst = Message::assistant()
.with_text("I'll run a new tool")
.with_tool_request("new_tool_1", Ok(CallToolRequestParams::new("new_tool")));
let new_tool_resp = Message::user().with_tool_response(
"new_tool_1",
Ok(rmcp::model::CallToolResult::success(vec![
RawContent::text("new result").no_annotation(),
])),
);
// Rebuild conversation from compacted messages + new tool pair.
// Can't use Conversation::push() because it merges by ID, and we need
// the messages to be separate entries.
let mut all_msgs = compacted.messages().clone();
all_msgs.push(new_asst);
all_msgs.push(new_tool_resp);
let compacted = Conversation::new_unvalidated(all_msgs);
// fix_conversation should produce zero issues — the conversation is valid
let (fixed, issues) = crate::conversation::fix_conversation(compacted.clone());
assert!(
issues.is_empty(),
"Compacted conversation + new tool pair should have no issues, but found: {:?}",
issues
);
// The new tool pair should be intact in the visible messages
let visible = fixed.agent_visible_messages();
let has_new_tool_request = visible.iter().any(|m| {
m.content
.iter()
.any(|c| matches!(c, MessageContent::ToolRequest(tr) if tr.id == "new_tool_1"))
});
let has_new_tool_response = visible.iter().any(|m| {
m.content
.iter()
.any(|c| matches!(c, MessageContent::ToolResponse(tr) if tr.id == "new_tool_1"))
});
assert!(
has_new_tool_request,
"New tool request should be in visible messages"
);
assert!(
has_new_tool_response,
"New tool response should be in visible messages"
);
// The old tool pairs should still exist as non-visible messages
let all_msgs = fixed.messages();
let non_visible_tool_count = all_msgs
.iter()
.filter(|m| {
!m.metadata.agent_visible
&& m.content.iter().any(|c| {
matches!(
c,
MessageContent::ToolRequest(_) | MessageContent::ToolResponse(_)
)
})
})
.count();
assert!(
non_visible_tool_count > 0,
"Old tool pairs should be preserved as non-visible messages"
);
}
}