nanocodex-oai-api 0.3.0

Tower-native OpenAI Responses API and managed context for Nanocodex
Documentation
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
use std::collections::HashSet;

use crate::{
    ContentItem, FunctionOutputBody, FunctionOutputContent, MessageRole, ResponseItem,
    ResponseItemId, Usage, responses::ResponseHistory,
};

use super::compaction;

const TOOL_OUTPUT_TOKEN_LIMIT: usize = 12_000;
// Changing this value would change model-visible IDs and invalidate prompt caches.
const SYNTHETIC_OUTPUT_ID_NAMESPACE: uuid::Uuid =
    uuid::Uuid::from_u128(0x90d38d3e_6a5b_4d52_bfe2_2f1e634bfac4);

/// Typed model-visible transcript. The common prompt path shares its backing
/// allocation; prompt-only repairs allocate only for incomplete call pairs.
#[derive(Clone)]
pub struct ContextManager {
    items: ResponseHistory,
    last_token_usage: Option<Usage>,
    calls: CallIds,
}

#[derive(Clone, Default)]
struct CallIds {
    function_calls: HashSet<Box<str>>,
    function_outputs: HashSet<Box<str>>,
    custom_calls: HashSet<Box<str>>,
    custom_outputs: HashSet<Box<str>>,
    tool_search_calls: HashSet<Box<str>>,
    tool_search_outputs: HashSet<Box<str>>,
    non_server_tool_search_outputs: HashSet<Box<str>>,
}

impl ContextManager {
    #[must_use]
    pub fn new(items: Vec<ResponseItem>) -> Self {
        let mut context = Self {
            items: ResponseHistory::default(),
            last_token_usage: None,
            calls: CallIds::default(),
        };
        context.record_items(items);
        context
    }

    #[must_use]
    pub fn flattened_items(&self) -> Vec<ResponseItem> {
        self.items.iter().cloned().collect()
    }

    #[must_use]
    pub fn shared_items(&self) -> ResponseHistory {
        self.items.clone()
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.items.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    #[must_use]
    pub fn iter(&self) -> impl ExactSizeIterator<Item = &ResponseItem> {
        self.items.iter()
    }

    pub fn record_items(&mut self, items: impl IntoIterator<Item = ResponseItem>) {
        for mut item in items
            .into_iter()
            .filter(is_api_item)
            .map(truncate_tool_output)
        {
            assign_missing_response_item_id(&mut item);
            self.calls.track(&item);
            self.items.push(item);
        }
    }

    pub fn commit_tail(&mut self) {
        self.items.commit_tail();
        if self.calls.is_balanced() {
            self.calls.clear();
        }
    }

    pub fn replace_and_recompute(&mut self, mut items: Vec<ResponseItem>, prefix: &[ResponseItem]) {
        assign_missing_response_item_ids(&mut items);
        self.items.replace(items);
        let total_tokens = prefix
            .iter()
            .chain(self.items.iter())
            .map(compaction::estimate_item_tokens)
            .fold(0, u64::saturating_add);
        self.last_token_usage = Some(Usage {
            total_tokens,
            ..Usage::default()
        });
        self.calls.clear();
        for item in self.items.iter() {
            self.calls.track(item);
        }
    }

    pub fn update_token_info(&mut self, usage: Option<&Usage>) {
        if let Some(usage) = usage {
            self.last_token_usage = Some(usage.clone());
        }
    }

    #[must_use]
    pub fn active_context_tokens(&self, server_reasoning_included: bool) -> u64 {
        let reported = self
            .last_token_usage
            .as_ref()
            .map_or(0, |usage| usage.total_tokens);
        let local_tail = self.items_after_last_model_generated_tokens();
        if server_reasoning_included {
            reported.saturating_add(local_tail)
        } else {
            reported
                .saturating_add(self.non_last_reasoning_tokens())
                .saturating_add(local_tail)
        }
    }

    /// Returns a shared prompt snapshot, allocating a repaired copy only for
    /// missing call outputs or orphan outputs.
    #[must_use]
    pub fn prompt_items(&self) -> ResponseHistory {
        self.prompt_items_with_repair().0
    }

    pub(crate) fn prompt_items_with_repair(&self) -> (ResponseHistory, bool) {
        let needs_repair = !self.calls.is_balanced();
        if !needs_repair {
            return (self.items.clone(), false);
        }

        let mut repaired = Vec::with_capacity(self.items.len() + 2);
        for item in &self.items {
            match item {
                ResponseItem::FunctionCall { id, call_id, .. }
                | ResponseItem::LocalShellCall {
                    id,
                    call_id: Some(call_id),
                    ..
                } => {
                    repaired.push(item.clone());
                    if !self.calls.function_outputs.contains(call_id.as_ref()) {
                        let mut output = ResponseItem::function_call_output(
                            call_id.to_string(),
                            FunctionOutputBody::Text("aborted".into()),
                        );
                        output.set_id(synthetic_output_id("fco", id.as_ref()));
                        repaired.push(output);
                    }
                }
                ResponseItem::CustomToolCall { id, call_id, .. } => {
                    repaired.push(item.clone());
                    if !self.calls.custom_outputs.contains(call_id.as_ref()) {
                        let mut output = ResponseItem::custom_tool_output(
                            call_id.to_string(),
                            None,
                            FunctionOutputBody::Text("aborted".into()),
                        );
                        output.set_id(synthetic_output_id("ctco", id.as_ref()));
                        repaired.push(output);
                    }
                }
                ResponseItem::FunctionCallOutput { call_id, .. }
                    if !self.calls.function_calls.contains(call_id.as_ref()) => {}
                ResponseItem::CustomToolCallOutput { call_id, .. }
                    if !self.calls.custom_calls.contains(call_id.as_ref()) => {}
                ResponseItem::ToolSearchCall {
                    id,
                    call_id: Some(call_id),
                    ..
                } => {
                    repaired.push(item.clone());
                    if !self.calls.tool_search_outputs.contains(call_id.as_ref()) {
                        repaired.push(ResponseItem::ToolSearchOutput {
                            id: synthetic_output_id("tso", id.as_ref()),
                            call_id: Some(call_id.clone()),
                            status: "completed".into(),
                            execution: "client".into(),
                            tools: Vec::new(),
                            internal_chat_message_metadata_passthrough: None,
                        });
                    }
                }
                ResponseItem::ToolSearchOutput {
                    call_id: Some(call_id),
                    execution,
                    ..
                } if execution.as_ref() != "server"
                    && !self.calls.tool_search_calls.contains(call_id.as_ref()) => {}
                _ => repaired.push(item.clone()),
            }
        }
        (ResponseHistory::new(repaired), true)
    }

    pub(crate) fn adopt_prompt_items(&mut self, items: ResponseHistory) {
        self.items = items;
        self.calls.clear();
        for item in self.items.iter() {
            self.calls.track(item);
        }
    }

    fn items_after_last_model_generated_tokens(&self) -> u64 {
        let mut tokens = 0_u64;
        for item in &self.items {
            if is_model_generated_item(item) {
                tokens = 0;
            } else {
                tokens = tokens.saturating_add(compaction::estimate_item_tokens(item));
            }
        }
        tokens
    }

    fn non_last_reasoning_tokens(&self) -> u64 {
        let mut reasoning = 0_u64;
        let mut before_last_user = None;
        for item in &self.items {
            if is_user_turn_boundary(item) {
                before_last_user = Some(reasoning);
            }
            if matches!(
                item,
                ResponseItem::Reasoning {
                    encrypted_content: Some(_),
                    ..
                }
            ) {
                reasoning = reasoning.saturating_add(compaction::estimate_item_tokens(item));
            }
        }
        before_last_user.unwrap_or_default()
    }
}

impl CallIds {
    fn is_balanced(&self) -> bool {
        self.function_calls == self.function_outputs
            && self.custom_calls == self.custom_outputs
            && self.tool_search_calls.is_subset(&self.tool_search_outputs)
            && self
                .non_server_tool_search_outputs
                .is_subset(&self.tool_search_calls)
    }

    fn clear(&mut self) {
        self.function_calls.clear();
        self.function_outputs.clear();
        self.custom_calls.clear();
        self.custom_outputs.clear();
        self.tool_search_calls.clear();
        self.tool_search_outputs.clear();
        self.non_server_tool_search_outputs.clear();
    }

    fn track(&mut self, item: &ResponseItem) {
        match item {
            ResponseItem::FunctionCall { call_id, .. }
            | ResponseItem::LocalShellCall {
                call_id: Some(call_id),
                ..
            } => {
                self.function_calls.insert(call_id.clone());
            }
            ResponseItem::FunctionCallOutput { call_id, .. } => {
                self.function_outputs.insert(call_id.clone());
            }
            ResponseItem::CustomToolCall { call_id, .. } => {
                self.custom_calls.insert(call_id.clone());
            }
            ResponseItem::CustomToolCallOutput { call_id, .. } => {
                self.custom_outputs.insert(call_id.clone());
            }
            ResponseItem::ToolSearchCall {
                call_id: Some(call_id),
                ..
            } => {
                self.tool_search_calls.insert(call_id.clone());
            }
            ResponseItem::ToolSearchOutput {
                call_id: Some(call_id),
                execution,
                ..
            } => {
                self.tool_search_outputs.insert(call_id.clone());
                if execution.as_ref() != "server" {
                    self.non_server_tool_search_outputs.insert(call_id.clone());
                }
            }
            _ => {}
        }
    }
}

pub fn assign_missing_response_item_ids(items: &mut [ResponseItem]) {
    for item in items {
        assign_missing_response_item_id(item);
    }
}

pub fn assign_missing_response_item_id(item: &mut ResponseItem) {
    if item.id().is_some_and(|id| !id.is_empty()) {
        return;
    }
    let Some(prefix) = item.id_prefix() else {
        return;
    };
    item.set_id(Some(new_response_item_id(prefix)));
}

fn new_response_item_id(prefix: &str) -> ResponseItemId {
    ResponseItemId::with_suffix(prefix, uuid::Uuid::now_v7())
}

fn synthetic_output_id(prefix: &str, source_id: Option<&ResponseItemId>) -> Option<ResponseItemId> {
    let source_id = source_id.filter(|id| !id.is_empty())?;
    let name = format!("{prefix}:{}", source_id.as_str());
    Some(ResponseItemId::with_suffix(
        prefix,
        uuid::Uuid::new_v5(&SYNTHETIC_OUTPUT_ID_NAMESPACE, name.as_bytes()),
    ))
}

#[must_use]
pub fn has_well_formed_tool_calls(items: &[ResponseItem]) -> bool {
    let mut function_calls = HashSet::new();
    let mut function_outputs = HashSet::new();
    let mut custom_calls = HashSet::new();
    let mut custom_outputs = HashSet::new();
    let mut search_calls = HashSet::new();
    let mut search_outputs = HashSet::new();
    let mut non_server_search_outputs = HashSet::new();
    for item in items {
        let valid = match item {
            ResponseItem::FunctionCall { call_id, .. }
            | ResponseItem::LocalShellCall {
                call_id: Some(call_id),
                ..
            } => function_calls.insert(call_id.as_ref()),
            ResponseItem::FunctionCallOutput { call_id, .. } => {
                function_calls.contains(call_id.as_ref())
                    && function_outputs.insert(call_id.as_ref())
            }
            ResponseItem::CustomToolCall { call_id, .. } => custom_calls.insert(call_id.as_ref()),
            ResponseItem::CustomToolCallOutput { call_id, .. } => {
                custom_calls.contains(call_id.as_ref()) && custom_outputs.insert(call_id.as_ref())
            }
            ResponseItem::ToolSearchCall {
                call_id: Some(call_id),
                ..
            } => search_calls.insert(call_id.as_ref()),
            ResponseItem::ToolSearchOutput {
                call_id: Some(call_id),
                execution,
                ..
            } => {
                search_outputs.insert(call_id.as_ref());
                execution.as_ref() == "server" || non_server_search_outputs.insert(call_id.as_ref())
            }
            ResponseItem::ToolSearchCall { .. } | ResponseItem::ToolSearchOutput { .. } => true,
            _ => true,
        };
        if !valid {
            return false;
        }
    }
    function_calls == function_outputs
        && custom_calls == custom_outputs
        && search_calls.is_subset(&search_outputs)
        && non_server_search_outputs.is_subset(&search_calls)
}

const fn is_model_generated_item(item: &ResponseItem) -> bool {
    matches!(
        item,
        ResponseItem::Message {
            role: MessageRole::Assistant,
            ..
        } | ResponseItem::AgentMessage { .. }
            | ResponseItem::Reasoning { .. }
            | ResponseItem::LocalShellCall { .. }
            | ResponseItem::FunctionCall { .. }
            | ResponseItem::ToolSearchCall { .. }
            | ResponseItem::CustomToolCall { .. }
            | ResponseItem::WebSearchCall { .. }
            | ResponseItem::ImageGenerationCall { .. }
            | ResponseItem::Compaction { .. }
            | ResponseItem::ContextCompaction { .. }
    )
}

fn is_user_turn_boundary(item: &ResponseItem) -> bool {
    item.is_user_message() && !is_contextual_user_message(item)
}

#[must_use]
pub fn is_contextual_user_message(item: &ResponseItem) -> bool {
    let ResponseItem::Message { content, .. } = item else {
        return false;
    };
    content
        .iter()
        .filter_map(|content| {
            let ContentItem::InputText { text } = content else {
                return None;
            };
            Some(text.as_ref())
        })
        .any(|text| {
            matches_marked_text("# AGENTS.md instructions", "</INSTRUCTIONS>", text)
                || matches_marked_text("<environment_context>", "</environment_context>", text)
                || matches_marked_text("<turn_aborted>", "</turn_aborted>", text)
        })
}

pub(crate) fn is_canonical_context_item(item: &ResponseItem) -> bool {
    match item {
        ResponseItem::Message {
            role: MessageRole::Developer,
            ..
        } => true,
        ResponseItem::Message {
            role: MessageRole::User,
            content,
            ..
        } => content.iter().any(|content| {
            let ContentItem::InputText { text } = content else {
                return false;
            };
            matches_marked_text("# AGENTS.md instructions", "</INSTRUCTIONS>", text)
                || matches_marked_text("<environment_context>", "</environment_context>", text)
        }),
        _ => false,
    }
}

fn matches_marked_text(start: &str, end: &str, text: &str) -> bool {
    let text = text.trim();
    text.get(..start.len())
        .is_some_and(|candidate| candidate.eq_ignore_ascii_case(start))
        && text
            .get(text.len().saturating_sub(end.len())..)
            .is_some_and(|candidate| candidate.eq_ignore_ascii_case(end))
}

const fn is_api_item(item: &ResponseItem) -> bool {
    !matches!(
        item,
        ResponseItem::CompactionTrigger {} | ResponseItem::Other(_)
    )
}

fn truncate_tool_output(mut item: ResponseItem) -> ResponseItem {
    let (ResponseItem::FunctionCallOutput { output, .. }
    | ResponseItem::CustomToolCallOutput { output, .. }) = &mut item
    else {
        return item;
    };
    match output {
        FunctionOutputBody::Text(text) => {
            *text = compaction::truncate_middle_with_token_budget(text, TOOL_OUTPUT_TOKEN_LIMIT)
                .into_boxed_str();
        }
        FunctionOutputBody::Content(content) => {
            truncate_output_content(content, TOOL_OUTPUT_TOKEN_LIMIT);
        }
    }
    item
}

fn truncate_output_content(items: &mut Vec<FunctionOutputContent>, token_limit: usize) {
    let mut remaining = token_limit;
    let mut omitted_text_items = 0usize;
    let mut output = Vec::with_capacity(items.len());
    for mut item in std::mem::take(items) {
        match &mut item {
            FunctionOutputContent::InputText { text } => {
                if remaining == 0 {
                    omitted_text_items += 1;
                    continue;
                }
                let tokens = text.len().div_ceil(4);
                if tokens <= remaining {
                    remaining -= tokens;
                    output.push(item);
                } else {
                    *text = compaction::truncate_middle_with_token_budget(text, remaining)
                        .into_boxed_str();
                    if text.is_empty() {
                        omitted_text_items += 1;
                    } else {
                        output.push(item);
                    }
                    remaining = 0;
                }
            }
            FunctionOutputContent::InputImage { .. }
            | FunctionOutputContent::EncryptedContent { .. } => output.push(item),
            FunctionOutputContent::InputAudio { .. } => {}
        }
    }
    if omitted_text_items > 0 {
        output.push(FunctionOutputContent::InputText {
            text: format!("[omitted {omitted_text_items} text items ...]").into_boxed_str(),
        });
    }
    *items = output;
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn complete_prompt_reuses_the_history_without_repair() {
        let context = ContextManager::new(vec![message("hello")]);
        let prompt = context.prompt_items();
        assert_eq!(prompt.len(), 1);
    }

    #[test]
    fn history_assigns_ids_once_and_preserves_them_across_checkpoints() {
        let mut context = ContextManager::new(vec![message("hello")]);
        let id = context
            .flattened_items()
            .into_iter()
            .next()
            .and_then(|item| item.id().cloned())
            .expect("history item should have an ID");
        assert!(id.as_str().starts_with("msg_"));

        context.commit_tail();
        let checkpoint = context.shared_items();
        assert_eq!(
            checkpoint.iter().next().and_then(ResponseItem::id),
            Some(&id)
        );
    }

    #[test]
    fn prompt_repairs_do_not_mutate_raw_history() {
        let call: ResponseItem = serde_json::from_str(
            r#"{"type":"custom_tool_call","id":"ctc_source","call_id":"missing","name":"exec","input":"code"}"#,
        )
        .unwrap();
        let orphan = ResponseItem::custom_tool_output(
            "orphan".to_owned(),
            None,
            FunctionOutputBody::Text("unused".into()),
        );
        let context = ContextManager::new(vec![call, orphan]);
        let prompt = context.prompt_items();
        let prompt: Vec<_> = prompt.iter().collect();
        assert_eq!(context.flattened_items().len(), 2);
        assert_eq!(prompt.len(), 2);
        assert!(matches!(
            &prompt[1],
            ResponseItem::CustomToolCallOutput {
                id: Some(id),
                call_id,
                output: FunctionOutputBody::Text(text),
                ..
            } if id.as_str() == "ctco_e63f89e2-4637-5644-bf21-01718d2de15e"
                && call_id.as_ref() == "missing"
                && text.as_ref() == "aborted"
        ));
    }

    #[test]
    fn orphan_server_tool_search_output_is_preserved_without_repeated_repair() {
        let mut context = ContextManager::new(vec![tool_search_output("orphan", "server")]);

        let (first, first_repaired) = context.prompt_items_with_repair();
        assert!(!first_repaired);
        assert_eq!(first.len(), 1);
        assert!(has_well_formed_tool_calls(&context.flattened_items()));

        context.commit_tail();
        let (second, second_repaired) = context.prompt_items_with_repair();
        assert!(!second_repaired);
        assert_eq!(second.len(), 1);
    }

    #[test]
    fn server_tool_search_call_gets_a_deterministic_client_output() {
        let call = tool_search_call("missing", "server");
        let orphan = tool_search_output("other", "server");
        let mut context = ContextManager::new(vec![call, orphan]);

        let (first, first_repaired) = context.prompt_items_with_repair();
        assert!(first_repaired);
        assert_eq!(first.len(), 3);
        let synthetic_id = first
            .iter()
            .find_map(|item| match item {
                ResponseItem::ToolSearchOutput {
                    id,
                    call_id: Some(call_id),
                    execution,
                    ..
                } if call_id.as_ref() == "missing" && execution.as_ref() == "client" => id.as_ref(),
                _ => None,
            })
            .expect("missing server call should receive a client output")
            .clone();
        assert!(synthetic_id.as_str().starts_with("tso_"));

        let (repeated, repeated_repaired) = context.prompt_items_with_repair();
        assert!(repeated_repaired);
        assert_eq!(
            repeated.iter().find_map(|item| match item {
                ResponseItem::ToolSearchOutput {
                    id,
                    call_id: Some(call_id),
                    ..
                } if call_id.as_ref() == "missing" => id.as_ref(),
                _ => None,
            }),
            Some(&synthetic_id)
        );

        context.adopt_prompt_items(first);
        let (adopted, adopted_repaired) = context.prompt_items_with_repair();
        assert!(!adopted_repaired);
        assert_eq!(adopted.len(), 3);
        assert!(has_well_formed_tool_calls(&context.flattened_items()));
    }

    #[test]
    fn client_tool_search_call_can_be_paired_by_a_server_output() {
        let context = ContextManager::new(vec![
            tool_search_call("paired", "client"),
            tool_search_output("paired", "server"),
        ]);
        let (prompt, repaired) = context.prompt_items_with_repair();
        assert!(!repaired);
        assert_eq!(prompt.len(), 2);
        assert!(has_well_formed_tool_calls(&context.flattened_items()));
    }

    #[test]
    fn server_tool_search_call_can_be_paired_by_a_client_output() {
        let context = ContextManager::new(vec![
            tool_search_call("paired", "server"),
            tool_search_output("paired", "client"),
        ]);
        let (prompt, repaired) = context.prompt_items_with_repair();
        assert!(!repaired);
        assert_eq!(prompt.len(), 2);
        assert!(has_well_formed_tool_calls(&context.flattened_items()));
    }

    #[test]
    fn orphan_client_tool_search_output_is_removed() {
        let mut context = ContextManager::new(vec![tool_search_output("orphan", "client")]);
        assert!(!has_well_formed_tool_calls(&context.flattened_items()));

        let (prompt, repaired) = context.prompt_items_with_repair();
        assert!(repaired);
        assert!(prompt.is_empty());

        context.adopt_prompt_items(prompt);
        let (adopted, adopted_repaired) = context.prompt_items_with_repair();
        assert!(!adopted_repaired);
        assert!(adopted.is_empty());
    }

    #[test]
    fn history_truncates_tool_text_but_preserves_images() {
        let context = ContextManager::new(vec![ResponseItem::custom_tool_output(
            "call".to_owned(),
            None,
            FunctionOutputBody::Content(vec![
                FunctionOutputContent::InputText {
                    text: "x".repeat(48_004).into_boxed_str(),
                },
                FunctionOutputContent::InputImage {
                    image_url: "data:image/png;base64,a".into(),
                    detail: None,
                },
                FunctionOutputContent::InputText {
                    text: "omitted".into(),
                },
            ]),
        )]);
        let history = context.flattened_items();
        let ResponseItem::CustomToolCallOutput {
            output: FunctionOutputBody::Content(output),
            ..
        } = &history[0]
        else {
            panic!("expected content output")
        };
        assert!(
            matches!(&output[0], FunctionOutputContent::InputText { text } if text.contains("tokens truncated"))
        );
        assert!(matches!(
            &output[1],
            FunctionOutputContent::InputImage { .. }
        ));
        assert!(
            matches!(&output[2], FunctionOutputContent::InputText { text } if text.as_ref() == "[omitted 1 text items ...]")
        );
    }

    #[test]
    fn contextual_messages_require_start_and_end_markers() {
        let agents =
            message("  # agents.md instructions\n\n<INSTRUCTIONS>\nnew\n</instructions>\n");
        assert!(is_contextual_user_message(&agents));
        assert!(is_canonical_context_item(&agents));
        assert!(!is_contextual_user_message(&message(
            "# AGENTS.md instructions are useful"
        )));
        let aborted = message("<turn_aborted>\ninterrupted\n</turn_aborted>");
        assert!(is_contextual_user_message(&aborted));
        assert!(!is_canonical_context_item(&aborted));
    }

    fn message(text: &str) -> ResponseItem {
        ResponseItem::message(
            MessageRole::User,
            [ContentItem::InputText { text: text.into() }],
        )
    }

    fn tool_search_call(call_id: &str, execution: &str) -> ResponseItem {
        ResponseItem::ToolSearchCall {
            id: Some(ResponseItemId::from_server(format!("tsc_{call_id}"))),
            call_id: Some(call_id.into()),
            status: Some("completed".into()),
            execution: execution.into(),
            arguments: serde_json::json!({ "query": "deferred" }).into(),
            internal_chat_message_metadata_passthrough: None,
        }
    }

    fn tool_search_output(call_id: &str, execution: &str) -> ResponseItem {
        ResponseItem::ToolSearchOutput {
            id: Some(ResponseItemId::from_server(format!("tso_{call_id}"))),
            call_id: Some(call_id.into()),
            status: "completed".into(),
            execution: execution.into(),
            tools: Vec::new(),
            internal_chat_message_metadata_passthrough: None,
        }
    }
}