adk-core 3.0.0

Core traits and types for Rust Agent Development Kit (ADK-Rust) agents, tools, sessions, and events
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
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
//! Auto-compaction: when an agent's history is compacted during a run, the token estimate
//! that decides it, and the hook an agent calls before each model call.
//!
//! [`IntraCompactionConfig`] sets the threshold: by default a fraction of the model's
//! context window ([`Llm::context_window`]), or
//! [`DEFAULT_TOKEN_THRESHOLD`](crate::intra_compaction::DEFAULT_TOKEN_THRESHOLD) when the model
//! reports none. [`HistoryCompactor`] is the hook: the runner installs one on
//! [`RunConfig::history_compactor`](crate::RunConfig::history_compactor) at the start of each
//! run, and `LlmAgent` and `CodeActAgent` call it before every model call, and once more when
//! the model rejects a request as longer than its context window
//! ([`is_context_limit_error`](crate::intra_compaction::is_context_limit_error)).
//!
//! The session-level [`EventsCompactionConfig`](crate::EventsCompactionConfig) compacts after
//! every N invocations instead; both summarize through
//! [`BaseEventsSummarizer`](crate::BaseEventsSummarizer).

use std::sync::Arc;

use async_trait::async_trait;

use crate::{
    AdkError, Content, ErrorCategory, ErrorComponent, Event, GenerateContentConfig,
    InvocationContext, Llm, LlmRequest, Part, ToolDeclarations,
};

/// The threshold, in estimated tokens, when the model reports no context window.
///
/// The smallest context window of a current hosted model is about 128,000 tokens; this stays
/// below it.
pub const DEFAULT_TOKEN_THRESHOLD: u64 = 100_000;

/// The share of the model's context window a request may reach before it is compacted.
///
/// The rest leaves room for the response and for the error of a character-based estimate.
pub const DEFAULT_CONTEXT_WINDOW_FRACTION: f64 = 0.8;

/// The share of the threshold at which a background compaction starts
/// ([`IntraCompactionConfig::background`]).
pub const DEFAULT_BACKGROUND_FRACTION: f64 = 0.7;

/// When an agent's history is compacted during a run.
///
/// Before each model call, `LlmAgent` and `CodeActAgent` ask the run's
/// [`HistoryCompactor`] to compact their history once the estimated request
/// ([`estimate_content_tokens`]) or the prompt size the provider reported for the previous
/// call passes [`threshold_for`](Self::threshold_for) the model. The runner's compactor
/// summarizes all but the most recent history entries: at most `overlap_event_count` of
/// them, within half the threshold.
///
/// The default is on: the threshold is [`DEFAULT_CONTEXT_WINDOW_FRACTION`] of the model's
/// context window, or [`DEFAULT_TOKEN_THRESHOLD`] when the model reports none. A fixed
/// `token_threshold` takes precedence over the window.
///
/// # Example
///
/// ```rust
/// use adk_core::IntraCompactionConfig;
/// use adk_core::intra_compaction::DEFAULT_TOKEN_THRESHOLD;
///
/// // On by default, at 80% of a 1,000,000-token window.
/// let config = IntraCompactionConfig::default();
/// assert_eq!(config.threshold_for(Some(1_000_000)), 800_000);
/// assert_eq!(config.threshold_for(None), DEFAULT_TOKEN_THRESHOLD);
///
/// // A fixed threshold, whatever the window.
/// let fixed = IntraCompactionConfig::at_tokens(50_000);
/// assert_eq!(fixed.threshold_for(Some(1_000_000)), 50_000);
///
/// assert!(!IntraCompactionConfig::disabled().enabled);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct IntraCompactionConfig {
    /// Whether history is compacted during a run.
    pub enabled: bool,
    /// A fixed threshold in estimated tokens. `None` derives it from the model's context
    /// window.
    pub token_threshold: Option<u64>,
    /// The share of the model's context window a request may reach, when `token_threshold`
    /// is `None` and the model reports its window. Values outside `(0, 1]` use
    /// [`DEFAULT_CONTEXT_WINDOW_FRACTION`].
    pub context_window_fraction: f64,
    /// The most recent history entries kept as they are, within half the threshold.
    pub overlap_event_count: usize,
    /// Characters per token for the estimate (default: 4).
    pub chars_per_token: u32,
    /// Whether a model whose provider compacts conversations itself
    /// ([`Llm::native_compaction`]) writes the summary, in place of the runner's summarizer
    /// (default: `true`). A summarizer or strategy configured on the runner takes precedence.
    pub native: bool,
    /// Whether the summary is written off the critical path (default: `false`): once a request
    /// passes `background_fraction` of the threshold, the runner starts the summary while the
    /// agent goes on, and swaps it in before a later model call, in this run or the session's
    /// next. A request that reaches the threshold first waits for it.
    pub background: bool,
    /// The share of the threshold at which a background compaction starts. Values outside
    /// `(0, 1)` use [`DEFAULT_BACKGROUND_FRACTION`].
    pub background_fraction: f64,
}

impl Default for IntraCompactionConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            token_threshold: None,
            context_window_fraction: DEFAULT_CONTEXT_WINDOW_FRACTION,
            overlap_event_count: 10,
            chars_per_token: 4,
            native: true,
            background: false,
            background_fraction: DEFAULT_BACKGROUND_FRACTION,
        }
    }
}

impl IntraCompactionConfig {
    /// Compaction turned off.
    pub fn disabled() -> Self {
        Self { enabled: false, ..Self::default() }
    }

    /// Compaction once a request passes `threshold` estimated tokens, whatever the model's
    /// window.
    pub fn at_tokens(threshold: u64) -> Self {
        Self { token_threshold: Some(threshold), ..Self::default() }
    }

    /// Compaction once a request passes `fraction` of the model's context window.
    pub fn at_window_fraction(fraction: f64) -> Self {
        Self { context_window_fraction: fraction, ..Self::default() }
    }

    /// Keeps the `count` most recent history entries as they are.
    pub fn with_overlap_event_count(mut self, count: usize) -> Self {
        self.overlap_event_count = count;
        self
    }

    /// Whether a model whose provider compacts conversations itself writes the summary.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::IntraCompactionConfig;
    ///
    /// // Always summarize with the runner's summarizer, even on a model that compacts natively.
    /// let config = IntraCompactionConfig::default().with_native(false);
    /// assert!(!config.native);
    /// ```
    pub fn with_native(mut self, native: bool) -> Self {
        self.native = native;
        self
    }

    /// Writes summaries off the critical path, starting each once a request passes `fraction`
    /// of the threshold.
    ///
    /// The summary costs a model call that may come earlier than the threshold requires, and
    /// it is swapped in only when the history still starts with the entries it covers.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_core::IntraCompactionConfig;
    ///
    /// // Start summarizing at 60% of the threshold, so the next turn rarely waits for it.
    /// let config = IntraCompactionConfig::default().in_background(0.6);
    /// assert!(config.background);
    /// assert_eq!(config.background_threshold_for(Some(1_000_000)), 480_000);
    /// ```
    pub fn in_background(mut self, fraction: f64) -> Self {
        self.background = true;
        self.background_fraction = fraction;
        self
    }

    /// The estimated tokens at which a background compaction starts, for a model with
    /// `context_window` tokens: `background_fraction` of [`threshold_for`](Self::threshold_for).
    pub fn background_threshold_for(&self, context_window: Option<u64>) -> u64 {
        let fraction = if self.background_fraction > 0.0 && self.background_fraction < 1.0 {
            self.background_fraction
        } else {
            DEFAULT_BACKGROUND_FRACTION
        };
        (self.threshold_for(context_window) as f64 * fraction) as u64
    }

    /// The threshold, in estimated tokens, for a model with `context_window` tokens.
    ///
    /// A fixed `token_threshold` wins; otherwise the window times
    /// `context_window_fraction`, or [`DEFAULT_TOKEN_THRESHOLD`] for an unknown window.
    pub fn threshold_for(&self, context_window: Option<u64>) -> u64 {
        if let Some(threshold) = self.token_threshold {
            return threshold;
        }
        let Some(window) = context_window else {
            return DEFAULT_TOKEN_THRESHOLD;
        };
        let fraction = if self.context_window_fraction > 0.0 && self.context_window_fraction <= 1.0
        {
            self.context_window_fraction
        } else {
            DEFAULT_CONTEXT_WINDOW_FRACTION
        };
        (window as f64 * fraction) as u64
    }
}

/// Why an agent asks its run's [`HistoryCompactor`] to compact.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompactionTrigger {
    /// Before a model call: compacts when the request has passed the threshold.
    BeforeModelCall,
    /// The model rejected the request as longer than its context window
    /// ([`is_context_limit_error`]): compacts whatever the estimate says, so the call can be
    /// sent once more.
    ContextLimitExceeded,
}

/// What an agent asks its run's [`HistoryCompactor`] to compact.
///
/// # Example
///
/// ```rust
/// use adk_core::{CompactionTrigger, Content, HistoryCompactionRequest, ToolDeclarations};
///
/// let instructions = [Content::new("system").with_text("You are a release assistant.")];
/// let history = [Content::new("user").with_text("Draft the release notes.")];
/// let tools = ToolDeclarations::new();
/// let request = HistoryCompactionRequest::new(&history, CompactionTrigger::BeforeModelCall)
///     .with_preamble(&instructions)
///     .with_tools(&tools)
///     .with_reported_prompt_tokens(Some(12_000));
/// assert_eq!(request.preamble.len(), 1);
/// assert_eq!(request.reported_prompt_tokens, Some(12_000));
/// ```
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct HistoryCompactionRequest<'a> {
    /// Contents sent with every request and never compacted, such as the agent's
    /// instructions. They count toward the estimate.
    pub preamble: &'a [Content],
    /// The conversation the agent continues from, which compaction may shorten.
    pub history: &'a [Content],
    /// The prompt tokens the provider reported for the agent's previous request in this run,
    /// a lower bound on the size of the next one until the history is compacted.
    pub reported_prompt_tokens: Option<u64>,
    /// Why compaction is asked for.
    pub trigger: CompactionTrigger,
    /// The tools the agent's next request declares. A provider that compacts natively reads
    /// them with the conversation, and binds the kept turns' thinking to them.
    pub tools: Option<&'a ToolDeclarations>,
    /// The generation config of the agent's next request: its thinking and output settings.
    pub config: Option<&'a GenerateContentConfig>,
}

impl<'a> HistoryCompactionRequest<'a> {
    /// A request to compact `history`, with no preamble, tools or config.
    pub fn new(history: &'a [Content], trigger: CompactionTrigger) -> Self {
        Self {
            preamble: &[],
            history,
            reported_prompt_tokens: None,
            trigger,
            tools: None,
            config: None,
        }
    }

    /// Contents sent ahead of the history and never compacted, such as instructions.
    pub fn with_preamble(mut self, preamble: &'a [Content]) -> Self {
        self.preamble = preamble;
        self
    }

    /// The prompt tokens the provider reported for the agent's previous request.
    pub fn with_reported_prompt_tokens(mut self, tokens: Option<u64>) -> Self {
        self.reported_prompt_tokens = tokens;
        self
    }

    /// The tools the agent's next request declares.
    pub fn with_tools(mut self, tools: &'a ToolDeclarations) -> Self {
        self.tools = Some(tools);
        self
    }

    /// The generation config of the agent's next request.
    pub fn with_config(mut self, config: Option<&'a GenerateContentConfig>) -> Self {
        self.config = config;
        self
    }
}

/// A compacted history.
#[derive(Debug, Clone)]
pub struct CompactedHistory {
    /// What replaces [`HistoryCompactionRequest::history`]: a summary, then the most recent
    /// entries as they were.
    pub history: Vec<Content>,
    /// The event that records the compaction in the session
    /// ([`EventActions::compaction`](crate::EventActions::compaction)), so later runs start
    /// from the summary. The agent yields it. `None` when the compaction is kept to this
    /// agent's working history.
    pub event: Option<Event>,
}

/// Compacts an agent's history before a model call.
///
/// The runner installs one on [`RunConfig::history_compactor`](crate::RunConfig::history_compactor)
/// at the start of each run, from [`IntraCompactionConfig`] and a summarizer or compaction
/// strategy. `LlmAgent` and `CodeActAgent` call it before every model call
/// ([`CompactionTrigger::BeforeModelCall`]) and once after a model rejects a request as too
/// long ([`CompactionTrigger::ContextLimitExceeded`]); an agent that calls a model itself does
/// the same. `Ok(None)` leaves the history as it is.
///
/// A compactor never separates a function response from its call
/// ([`balanced_content_cut`](crate::history::balanced_content_cut)), keeps a call still held
/// for confirmation and everything after it
/// ([`held_call_content_limit`](crate::history::held_call_content_limit)), and makes any model
/// call inside a [`ModelCallScope`](crate::ModelCallScope) for `ctx`, so it counts against the
/// run's budget and spend ledger.
///
/// # Example
///
/// ```rust
/// use adk_core::intra_compaction::{
///     CompactedHistory, HistoryCompactionRequest, HistoryCompactor,
/// };
/// use adk_core::{InvocationContext, Llm, Result, async_trait};
/// use std::sync::Arc;
///
/// /// Keeps the 20 most recent entries once there are more than 40.
/// #[derive(Debug)]
/// struct KeepRecent;
///
/// #[async_trait]
/// impl HistoryCompactor for KeepRecent {
///     async fn compact(
///         &self,
///         _ctx: Arc<dyn InvocationContext>,
///         _model: Arc<dyn Llm>,
///         request: HistoryCompactionRequest<'_>,
///     ) -> Result<Option<CompactedHistory>> {
///         let history = request.history;
///         if history.len() <= 40 {
///             return Ok(None);
///         }
///         let cut = adk_core::history::balanced_content_cut(history, history.len() - 20);
///         let note = adk_core::history::system_notice("Earlier turns were removed.");
///         let kept = std::iter::once(note).chain(history[cut..].iter().cloned()).collect();
///         Ok(Some(CompactedHistory { history: kept, event: None }))
///     }
/// }
/// # let _: Arc<dyn HistoryCompactor> = Arc::new(KeepRecent);
/// ```
#[async_trait]
pub trait HistoryCompactor: Send + Sync + std::fmt::Debug {
    /// Compacts `request.history` for a call to `model` by the agent `ctx` runs, or returns
    /// `Ok(None)` to leave it as it is.
    ///
    /// # Errors
    ///
    /// An error ends the agent's turn with it. The runner's compactor returns none: a summary
    /// that fails leaves the history as it is.
    async fn compact(
        &self,
        ctx: Arc<dyn InvocationContext>,
        model: Arc<dyn Llm>,
        request: HistoryCompactionRequest<'_>,
    ) -> crate::Result<Option<CompactedHistory>>;
}

/// The first line of every compaction summary [`compaction_summary`] builds.
pub const COMPACTION_SUMMARY_HEADING: &str =
    "The earlier conversation was compacted to fit the model's context window. Summary:";

/// The history entry a compaction summary takes: a
/// [system notice](crate::history::system_notice) headed [`COMPACTION_SUMMARY_HEADING`].
///
/// A user-role notice, so a request that starts with it is valid on every provider, and it
/// never stands in for the person's last message.
///
/// # Example
///
/// ```rust
/// use adk_core::history::is_system_notice;
/// use adk_core::intra_compaction::compaction_summary;
///
/// let summary = compaction_summary("The user asked for the Q3 figures; two were found.");
/// assert!(is_system_notice(&summary));
/// ```
pub fn compaction_summary(summary: &str) -> Content {
    crate::history::system_notice(&format!("{COMPACTION_SUMMARY_HEADING}\n{summary}"))
}

/// The text of a compaction summary: [`COMPACTION_SUMMARY_HEADING`], then `summary`.
///
/// A provider-native compaction ([`is_native_compaction`]) carries it as the text every
/// provider reads, next to the signed copy only its own provider reads.
///
/// # Example
///
/// ```rust
/// use adk_core::intra_compaction::{COMPACTION_SUMMARY_HEADING, compaction_summary_text};
///
/// let text = compaction_summary_text("Two invoices were found.");
/// assert_eq!(text, format!("{COMPACTION_SUMMARY_HEADING}\nTwo invoices were found."));
/// ```
pub fn compaction_summary_text(summary: &str) -> String {
    format!("{COMPACTION_SUMMARY_HEADING}\n{summary}")
}

/// Key a provider sets to `true` in the replay-only copy
/// ([`REPLAY_ONLY_KEY`](crate::history::REPLAY_ONLY_KEY)) of a compaction it wrote itself.
pub const NATIVE_COMPACTION_KEY: &str = "adk_native_compaction";

/// Whether `content` is a compaction a provider wrote itself: a model turn holding the
/// summary as text ([`compaction_summary_text`]) and the provider's signed copy, flagged
/// [`NATIVE_COMPACTION_KEY`].
///
/// The copy is a native item: it reaches only the provider and model that wrote it
/// ([`retain_replayable`](crate::history::retain_replayable)); every other provider reads
/// the text.
///
/// # Example
///
/// ```rust
/// use adk_core::intra_compaction::{compaction_summary_text, is_native_compaction};
/// use adk_core::{Content, Part};
///
/// let mut compaction = Content::new("model").with_text(compaction_summary_text("Done so far."));
/// assert!(!is_native_compaction(&compaction));
/// compaction.parts.push(Part::ServerToolResponse {
///     server_tool_response: serde_json::json!({
///         "type": "anthropic_message",
///         "adk_replay_only": true,
///         "adk_native_compaction": true,
///         "content": [{"type": "compaction", "content": "Done so far.", "signature": "sig"}],
///     }),
/// });
/// assert!(is_native_compaction(&compaction));
/// ```
pub fn is_native_compaction(content: &Content) -> bool {
    matches!(content.role.as_str(), "model" | "assistant")
        && content.parts.iter().any(|part| {
            let (Part::ServerToolCall { server_tool_call: payload }
            | Part::ServerToolResponse { server_tool_response: payload }) = part
            else {
                return false;
            };
            payload.get(NATIVE_COMPACTION_KEY).and_then(serde_json::Value::as_bool) == Some(true)
        })
}

/// Asks a model for its provider's own compaction of a request's conversation, in place of
/// a reply.
///
/// The runner's auto-compaction sends it to a model that reports
/// [`Llm::native_compaction`]: the request carries the conversation to summarize with the
/// agent's instructions, tools and config, and the response's content is the compaction
/// ([`is_native_compaction`]). A model that does not compact natively ignores it.
///
/// Carried in the request's `config.extensions` under [`EXTENSION_KEY`](Self::EXTENSION_KEY).
///
/// # Example
///
/// ```rust
/// use adk_core::LlmRequest;
/// use adk_core::intra_compaction::NativeCompactionRequest;
///
/// let mut request = LlmRequest::new("claude-sonnet-5-5", vec![]);
/// assert_eq!(NativeCompactionRequest::of(&request), None);
/// NativeCompactionRequest::new().with_instructions("Keep every order number.").apply(&mut request);
/// assert_eq!(
///     NativeCompactionRequest::of(&request).and_then(|ask| ask.instructions),
///     Some("Keep every order number.".to_string())
/// );
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct NativeCompactionRequest {
    /// A summarization prompt that replaces the provider's own.
    pub instructions: Option<String>,
}

impl NativeCompactionRequest {
    /// Key of the request in `GenerateContentConfig::extensions`.
    pub const EXTENSION_KEY: &'static str = "adk_native_compaction";

    /// A compaction with the provider's own summarization prompt.
    pub fn new() -> Self {
        Self::default()
    }

    /// Replaces the provider's summarization prompt with `instructions`.
    pub fn with_instructions(mut self, instructions: impl Into<String>) -> Self {
        self.instructions = Some(instructions.into());
        self
    }

    /// Marks `request` as asking for this compaction.
    pub fn apply(&self, request: &mut LlmRequest) {
        let mut ask = serde_json::Map::new();
        if let Some(instructions) = &self.instructions {
            ask.insert("instructions".to_string(), serde_json::Value::from(instructions.clone()));
        }
        request
            .config
            .get_or_insert_with(GenerateContentConfig::default)
            .extensions
            .insert(Self::EXTENSION_KEY.to_string(), serde_json::Value::Object(ask));
    }

    /// The compaction `request` asks for, if any.
    pub fn of(request: &LlmRequest) -> Option<Self> {
        let ask = request.config.as_ref()?.extensions.get(Self::EXTENSION_KEY)?.as_object()?;
        Some(Self {
            instructions: ask
                .get("instructions")
                .and_then(serde_json::Value::as_str)
                .map(str::to_string),
        })
    }
}

/// Whether `err` is a model's refusal of a request longer than its context window.
///
/// Providers report it as a client error (`InvalidInput`) with their own wording: Anthropic's
/// "prompt is too long", OpenAI's `context_length_exceeded` ("maximum context length"),
/// Gemini's "input token count exceeds the maximum number of tokens allowed", and the
/// runner's own `runner.context_overflow`.
///
/// # Example
///
/// ```rust
/// use adk_core::{AdkError, ErrorCategory, ErrorComponent};
/// use adk_core::intra_compaction::is_context_limit_error;
///
/// let too_long = AdkError::new(
///     ErrorComponent::Model,
///     ErrorCategory::InvalidInput,
///     "model.anthropic.api_error",
///     "400: prompt is too long: 1048577 tokens > 1000000 maximum (invalid_request_error)",
/// );
/// assert!(is_context_limit_error(&too_long));
/// assert!(!is_context_limit_error(&AdkError::model("connection refused")));
/// ```
pub fn is_context_limit_error(err: &AdkError) -> bool {
    if err.component != ErrorComponent::Model || err.category != ErrorCategory::InvalidInput {
        return false;
    }
    if err.code == "runner.context_overflow" {
        return true;
    }
    let message = err.message.to_lowercase();
    [
        "prompt is too long",
        "context length",
        "context_length_exceeded",
        "context window",
        "context limit",
        "maximum context",
        "too many tokens",
        "input is too long",
        "input too long",
        "input token count",
        "exceeds the maximum number of tokens",
        "request payload size exceeds",
        "reduce the length of the messages",
    ]
    .iter()
    .any(|pattern| message.contains(pattern))
}

/// Estimate token count from a list of events using a character heuristic.
///
/// Sums the character lengths of all text parts and serialized function call/response
/// actions across all events, then divides by `chars_per_token` (integer division).
///
/// # Arguments
///
/// * `events` - The conversation events to estimate tokens for.
/// * `chars_per_token` - The character-to-token ratio (e.g., 4 means ~4 chars per token).
///
/// # Returns
///
/// Estimated token count. Returns 0 if `chars_per_token` is 0 or events are empty.
///
/// # Example
///
/// ```rust
/// use adk_core::intra_compaction::estimate_tokens;
/// use adk_core::{Event, Content, Part};
///
/// let mut event = Event::new("inv-1");
/// event.set_content(Content::new("user").with_text("Hello, world!"));
/// let tokens = estimate_tokens(&[event], 4);
/// assert_eq!(tokens, 3); // 13 chars / 4 = 3
/// ```
pub fn estimate_tokens(events: &[Event], chars_per_token: u32) -> u64 {
    if chars_per_token == 0 {
        return 0;
    }
    let total_chars: u64 = events.iter().map(|e| estimate_event_chars(e) as u64).sum();
    total_chars / chars_per_token as u64
}

/// Estimate the token count of model contents with the [`estimate_tokens`] heuristic.
///
/// # Example
///
/// ```rust
/// use adk_core::Content;
/// use adk_core::intra_compaction::estimate_content_tokens;
///
/// let history = [Content::new("user").with_text("Hello, world!")];
/// assert_eq!(estimate_content_tokens(&history, 4), 3);
/// ```
pub fn estimate_content_tokens(contents: &[Content], chars_per_token: u32) -> u64 {
    if chars_per_token == 0 {
        return 0;
    }
    let chars: u64 = contents
        .iter()
        .flat_map(|content| &content.parts)
        .map(|part| estimate_part_chars(part) as u64)
        .sum();
    chars / chars_per_token as u64
}

/// Estimate the character count of a single event.
///
/// Counts characters from:
/// - Text parts (text length)
/// - Thinking parts (thinking text length)
/// - Function call parts (serialized args length + name length)
/// - Function response parts (serialized response length + name length)
/// - A compaction event's summary, which stands in for the events it covers
/// - Serialized actions (state_delta as JSON)
fn estimate_event_chars(event: &Event) -> usize {
    let mut chars = 0;

    let summary = event.actions.compaction.as_ref().map(|compaction| &compaction.compacted_content);
    for content in event.llm_response.content.iter().chain(summary) {
        for part in &content.parts {
            chars += estimate_part_chars(part);
        }
    }

    // Count serialized actions (state_delta)
    if !event.actions.state_delta.is_empty() {
        chars += json_len(&event.actions.state_delta);
    }

    chars
}

/// Estimate the character count of a single content part.
fn estimate_part_chars(part: &Part) -> usize {
    match part {
        Part::Text { text } => text.len(),
        Part::Thinking { thinking, .. } => thinking.len(),
        Part::FunctionCall { name, args, .. } => name.len() + json_len(args),
        Part::FunctionResponse { function_response, .. } => {
            function_response.name.len() + json_len(&function_response.response)
        }
        // Binary/file data and server tool calls contribute minimally to text token count
        Part::InlineData { .. } | Part::FileData { .. } => 0,
        Part::ServerToolCall { server_tool_call } => json_len(server_tool_call),
        Part::ServerToolResponse { server_tool_response } => json_len(server_tool_response),
        Part::EmbeddedResource { resource } => json_len(resource),
    }
}

/// The serialized JSON length of `value`, counted without building the string, since the
/// estimate runs before every model call.
fn json_len<T: serde::Serialize + ?Sized>(value: &T) -> usize {
    struct Count(usize);
    impl std::io::Write for Count {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            self.0 += bytes.len();
            Ok(bytes.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }
    let mut count = Count(0);
    serde_json::to_writer(&mut count, value).map_or(0, |()| count.0)
}

/// A one-line rendering of `part` for a summarizer prompt; `None` for thinking and for
/// provider-native items (server-side tool calls and results).
///
/// Text is kept as it is. Function calls and responses keep their name and JSON payload,
/// data and file parts their type and reference, and embedded resources their URI, so a
/// summary keeps the facts a tool returned. The session compaction summarizer
/// (`LlmEventSummarizer`) and the runner's `SummarisationCompaction` both render events with
/// it.
///
/// # Example
///
/// ```rust
/// use adk_core::intra_compaction::render_part_for_summary;
/// use adk_core::{FunctionResponseData, Part};
/// use serde_json::json;
///
/// let result = Part::FunctionResponse {
///     function_response: FunctionResponseData::new("lookup", json!({"status": "shipped"})),
///     id: None,
///     annotations: None,
/// };
/// assert_eq!(
///     render_part_for_summary(&result).as_deref(),
///     Some(r#"[function response] lookup: {"status":"shipped"}"#)
/// );
/// let thought = Part::Thinking { thinking: "hmm".into(), signature: None };
/// assert_eq!(render_part_for_summary(&thought), None);
/// let native = Part::ServerToolResponse { server_tool_response: json!({"type": "anthropic_message"}) };
/// assert_eq!(render_part_for_summary(&native), None);
/// ```
pub fn render_part_for_summary(part: &Part) -> Option<String> {
    let json = |value: &serde_json::Value| value.to_string();
    Some(match part {
        Part::Text { text } => text.clone(),
        // Provider-native items are private to the provider that produced them; a payload can
        // hold its reasoning, and the summary is sent to whichever model summarizes.
        Part::Thinking { .. } | Part::ServerToolCall { .. } | Part::ServerToolResponse { .. } => {
            return None;
        }
        Part::FunctionCall { name, args, .. } => format!("[function call] {name}({})", json(args)),
        Part::FunctionResponse { function_response, .. } => {
            let mut rendered = format!(
                "[function response] {}: {}",
                function_response.name,
                json(&function_response.response)
            );
            for data in &function_response.inline_data {
                rendered.push_str(&format!(" [inline data: {}]", data.mime_type));
            }
            for file in &function_response.file_data {
                rendered.push_str(&format!(" [file: {} ({})]", file.file_uri, file.mime_type));
            }
            rendered
        }
        Part::InlineData { mime_type, data, .. } => {
            format!("[inline data: {mime_type}, {} bytes]", data.len())
        }
        Part::FileData { mime_type, file_uri, .. } => format!("[file: {file_uri} ({mime_type})]"),
        Part::EmbeddedResource { resource } => match resource {
            crate::EmbeddedResource::Text(text) => format!("[resource {}] {}", text.uri, text.text),
            crate::EmbeddedResource::Blob(blob) => format!(
                "[resource {}: {}, {} bytes]",
                blob.uri,
                blob.mime_type.as_deref().unwrap_or("application/octet-stream"),
                blob.data.len()
            ),
        },
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Content, FunctionResponseData};

    #[test]
    fn the_default_is_on_at_a_fraction_of_the_window() {
        assert_eq!(
            IntraCompactionConfig::default(),
            IntraCompactionConfig {
                enabled: true,
                token_threshold: None,
                context_window_fraction: 0.8,
                overlap_event_count: 10,
                chars_per_token: 4,
                native: true,
                background: false,
                background_fraction: DEFAULT_BACKGROUND_FRACTION,
            }
        );
    }

    #[test]
    fn a_fixed_threshold_wins_and_a_bad_fraction_falls_back() {
        let config = IntraCompactionConfig::default();
        assert_eq!(config.threshold_for(Some(200_000)), 160_000);
        assert_eq!(config.threshold_for(None), DEFAULT_TOKEN_THRESHOLD);
        assert_eq!(IntraCompactionConfig::at_tokens(5).threshold_for(Some(200_000)), 5);
        for fraction in [0.0, -1.0, 1.5, f64::NAN] {
            let config = IntraCompactionConfig::at_window_fraction(fraction);
            assert_eq!(config.threshold_for(Some(100)), 80, "fraction {fraction}");
        }
        assert_eq!(IntraCompactionConfig::at_window_fraction(0.5).threshold_for(Some(100)), 50);
    }

    #[test]
    fn context_limit_errors_are_told_from_other_client_errors() {
        let model_error = |message: &str| {
            AdkError::new(
                ErrorComponent::Model,
                ErrorCategory::InvalidInput,
                "model.api_error",
                message.to_string(),
            )
        };
        for message in [
            "400: prompt is too long: 1048577 tokens > 1000000 maximum (invalid_request_error)",
            "This model's maximum context length is 128000 tokens",
            "context_length_exceeded",
            "input length and `max_tokens` exceed context limit: 190000 + 32000 > 200000",
            "The input token count (1100000) exceeds the maximum number of tokens allowed (1048576).",
        ] {
            assert!(is_context_limit_error(&model_error(message)), "{message}");
        }
        for message in [
            "max_tokens: 200000 > 128000, which is the maximum allowed number of output tokens",
            "invalid x-api-key",
            "tools.0.name: String should match pattern",
        ] {
            assert!(!is_context_limit_error(&model_error(message)), "{message}");
        }
        let unavailable = AdkError::new(
            ErrorComponent::Model,
            ErrorCategory::Unavailable,
            "model.api_error",
            "prompt is too long",
        );
        assert!(!is_context_limit_error(&unavailable));
    }

    #[test]
    fn contents_are_estimated_like_events() {
        let call = Content {
            role: "model".to_string(),
            parts: vec![Part::FunctionCall {
                name: "get_weather".to_string(),
                args: serde_json::json!({"city": "NYC"}),
                id: None,
                thought_signature: None,
            }],
        };
        let mut event = Event::new("inv-1");
        event.set_content(call.clone());
        // "get_weather" (11) + {"city":"NYC"} (14) = 25 chars.
        assert_eq!(estimate_content_tokens(&[call], 1), 25);
        assert_eq!(estimate_tokens(&[event], 1), 25);
    }

    #[test]
    fn test_estimate_tokens_empty() {
        assert_eq!(estimate_tokens(&[], 4), 0);
    }

    #[test]
    fn test_estimate_tokens_zero_ratio() {
        let mut event = Event::new("inv-1");
        event.set_content(Content::new("user").with_text("Hello"));
        assert_eq!(estimate_tokens(&[event], 0), 0);
    }

    #[test]
    fn test_estimate_tokens_text_only() {
        let mut event = Event::new("inv-1");
        // "Hello" = 5 chars, 5 / 4 = 1
        event.set_content(Content::new("user").with_text("Hello"));
        assert_eq!(estimate_tokens(&[event], 4), 1);
    }

    #[test]
    fn test_estimate_tokens_multiple_events() {
        let mut e1 = Event::new("inv-1");
        e1.set_content(Content::new("user").with_text("Hello")); // 5 chars
        let mut e2 = Event::new("inv-1");
        e2.set_content(Content::new("model").with_text("World!")); // 6 chars
        // Total: 11 chars / 4 = 2
        assert_eq!(estimate_tokens(&[e1, e2], 4), 2);
    }

    #[test]
    fn test_estimate_tokens_with_function_call() {
        let mut event = Event::new("inv-1");
        event.llm_response.content = Some(Content {
            role: "model".to_string(),
            parts: vec![Part::FunctionCall {
                name: "get_weather".to_string(),
                args: serde_json::json!({"city": "NYC"}),
                id: None,
                thought_signature: None,
            }],
        });
        let tokens = estimate_tokens(&[event], 4);
        // "get_weather" = 11 chars + {"city":"NYC"} serialized
        assert!(tokens > 0);
    }

    #[test]
    fn a_compaction_summary_counts_toward_the_estimate() {
        let mut event = Event::new("inv-1");
        event.actions.compaction = Some(crate::EventCompaction {
            start_timestamp: chrono::Utc::now(),
            end_timestamp: chrono::Utc::now(),
            compacted_content: Content::new("model").with_text("a".repeat(40)),
        });
        assert_eq!(estimate_tokens(&[event], 4), 10);
    }

    #[test]
    fn test_estimate_tokens_with_function_response() {
        let mut event = Event::new("inv-1");
        event.llm_response.content = Some(Content {
            role: "function".to_string(),
            parts: vec![Part::FunctionResponse {
                function_response: FunctionResponseData::new(
                    "get_weather",
                    serde_json::json!({"temp": 72}),
                ),
                id: None,
                annotations: None,
            }],
        });
        let tokens = estimate_tokens(&[event], 4);
        assert!(tokens > 0);
    }
}