mentra 0.28.0

An agent runtime for tool-using LLM applications
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
use std::{
    collections::{BTreeMap, BTreeSet},
    path::PathBuf,
    time::Duration,
};

#[cfg(test)]
use std::sync::atomic::{AtomicU64, Ordering};

use serde::{Deserialize, Serialize};

use crate::compaction::CompactionMode;
#[cfg(test)]
use crate::provider::ToolSearchMode;
use crate::provider::{ProviderRequestOptions, ToolChoice};

#[cfg(test)]
static NEXT_TEST_TRANSCRIPT_DIR_ID: AtomicU64 = AtomicU64::new(1);

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TaskConfig {
    pub tasks_dir: PathBuf,
    pub reminder_threshold: usize,
}

impl Default for TaskConfig {
    fn default() -> Self {
        Self {
            tasks_dir: default_tasks_dir(),
            reminder_threshold: 3,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TeamAutonomyConfig {
    pub enabled: bool,
    pub poll_interval: Duration,
    pub idle_timeout: Duration,
}

impl Default for TeamAutonomyConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            poll_interval: Duration::from_secs(5),
            idle_timeout: Duration::from_secs(60),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TeamConfig {
    pub team_dir: PathBuf,
    pub autonomy: TeamAutonomyConfig,
}

impl Default for TeamConfig {
    fn default() -> Self {
        Self {
            team_dir: default_team_dir(),
            autonomy: TeamAutonomyConfig::default(),
        }
    }
}

/// A hard aggregate budget for tool-result content in a main model request.
///
/// This counts only final provider-neutral [`ToolResultContent`](crate::tool::ToolResultContent)
/// body bytes. It is not a total request or wire-size limit. Recent results
/// receive allocation priority but remain inside `max_bytes`; text previews
/// include their omission separator in `max_preview_bytes`.
///
/// There is deliberately no [`Default`] implementation: enabling a lossy
/// policy requires a host to state every byte limit explicitly.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectedToolResultBudget {
    pub max_bytes: usize,
    pub prioritize_recent_results: usize,
    pub max_preview_bytes: usize,
}

/// Which signal decides that a run auto-compacts, and — separately from any
/// number — whether it auto-compacts at all.
///
/// Before this existed, [`CompactionConfig::auto_compact_threshold_tokens`]
/// carried two meanings at once: the fallback used when the model's context
/// window is unknown, *and* the master off switch. That left one policy
/// unspellable — "compact at a share of the window, and do nothing when the
/// window is unknown" — because clearing the absolute number to opt out of it
/// turned the whole feature off. A host that wanted window-relative behavior
/// had to invent an absolute token count it did not believe in, and that
/// invented number went live in exactly the case where a wrong guess does
/// damage: [`ModelInfo::context_window`](crate::ModelInfo::context_window) is
/// `None` by default, so an unlisted model gets the guess.
///
/// Each variant names one policy, and every reachable state is nameable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum AutoCompactTrigger {
    /// Resolve the threshold from the two numbers, exactly as mentra did
    /// before this enum existed: the window share when the window and the
    /// percentage are both known, otherwise
    /// [`auto_compact_threshold_tokens`](CompactionConfig::auto_compact_threshold_tokens)
    /// — and off entirely when that is `None`.
    ///
    /// The default, so a config stored before this field existed keeps
    /// resolving to the same threshold at every window size.
    #[default]
    Thresholds,
    /// Never auto-compact, whatever the two numbers say.
    ///
    /// The off switch stated on its own, so turning auto-compaction off does
    /// not mean discarding the thresholds a host would want back when it turns
    /// the feature on again.
    Off,
    /// Compact at
    /// [`auto_compact_threshold_percent`](CompactionConfig::auto_compact_threshold_percent)
    /// of a *known* context window, and do not auto-compact at all when the
    /// window is unknown.
    ///
    /// [`auto_compact_threshold_tokens`](CompactionConfig::auto_compact_threshold_tokens)
    /// is not consulted, so it may keep whatever value it holds. With no
    /// percentage set there is nothing to take a share of and this is off —
    /// deliberately, rather than falling back onto the absolute number this
    /// variant exists to opt out of.
    WindowShareOnly,
}

/// Controls request-only tool-result projection and canonical summary compaction.
///
/// These mechanisms are separate. Request-only elision changes a cloned main
/// model request and does not further change the persisted transcript. Summary
/// compaction replaces canonical transcript items and persists the result.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CompactionConfig {
    /// How many of the most recent tool results remain unchanged when the
    /// history is rebuilt for a provider request.
    ///
    /// Every older result larger than 100 bytes is replaced by a
    /// `[Previous: used <tool>]` marker. When
    /// `projected_tool_result_budget` is `None`, that rewrite runs before every
    /// main model request, at any context size, and the projected history is
    /// also what the auto-compaction threshold measures. Each changed request emits
    /// [`AgentEvent::RequestToolResultsElided`](crate::agent::AgentEvent::RequestToolResultsElided).
    ///
    /// This is a count heuristic, not a request-size bound: the newest results
    /// can be arbitrarily large, old results of at most 100 bytes survive, and
    /// non-tool content is unaffected. `usize::MAX` disables the rewrite and is
    /// the default. Lower it only for a workload whose old tool results are
    /// genuinely disposable.
    pub keep_recent_tool_results: usize,
    /// Optional strict aggregate budget for projected tool-result bodies.
    ///
    /// When set, this policy is used exclusively and
    /// `keep_recent_tool_results` is not consulted. `None` preserves the exact
    /// legacy recent-count behavior. Auto-compaction measures this same
    /// budget-shaped main-request projection. Budgeting adds no retrieval
    /// mechanism; tool-result paging remains an independent, live-agent-only
    /// feature.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub projected_tool_result_budget: Option<ProjectedToolResultBudget>,
    /// Which signal decides that a run auto-compacts. See
    /// [`AutoCompactTrigger`]; the default reproduces the pre-0.24 resolution
    /// of the two numbers below exactly, including `None` tokens meaning off.
    #[serde(default)]
    pub auto_compact_trigger: AutoCompactTrigger,
    /// The token count above which a run compacts, when the model's context
    /// window is unknown.
    ///
    /// Under the default [`AutoCompactTrigger::Thresholds`], `None` here
    /// disables auto-compaction outright, whatever the window is — this field
    /// is both the fallback and the off switch, which is why
    /// [`AutoCompactTrigger`] exists. Under
    /// [`AutoCompactTrigger::WindowShareOnly`] this field is not consulted at
    /// all, and under [`AutoCompactTrigger::Off`] neither is anything else.
    pub auto_compact_threshold_tokens: Option<usize>,
    /// The percentage of the model's context window to compact at, when the
    /// window *is* known.
    ///
    /// A single absolute token count is the one model-dependent constant that
    /// cannot be model-independent: 50k is most of a 64k window and a rounding
    /// error in a 1M one, so a fixed number either compacts a large model far
    /// too eagerly or leaves a small one to overflow. When
    /// [`ModelInfo::context_window`](crate::ModelInfo::context_window) is
    /// known, this percentage of it wins; otherwise
    /// `auto_compact_threshold_tokens` does. `None` here always uses the
    /// absolute number — or, under
    /// [`AutoCompactTrigger::WindowShareOnly`], means off. Values above 100
    /// are treated as 100.
    #[serde(default = "default_auto_compact_threshold_percent")]
    pub auto_compact_threshold_percent: Option<u8>,
    pub transcript_dir: PathBuf,
    pub summary_max_input_chars: usize,
    pub summary_max_output_tokens: u32,
    #[serde(default)]
    pub mode: CompactionMode,
    pub preserve_recent_user_tokens: usize,
    pub preserve_recent_delegation_results: usize,
    pub max_persisted_transcripts: Option<usize>,
}

impl Default for CompactionConfig {
    fn default() -> Self {
        Self {
            keep_recent_tool_results: usize::MAX,
            projected_tool_result_budget: None,
            auto_compact_trigger: AutoCompactTrigger::default(),
            auto_compact_threshold_tokens: Some(50_000),
            auto_compact_threshold_percent: default_auto_compact_threshold_percent(),
            transcript_dir: default_transcript_dir(),
            summary_max_input_chars: 80_000,
            summary_max_output_tokens: 2_000,
            mode: CompactionMode::LocalOnly,
            preserve_recent_user_tokens: 20_000,
            preserve_recent_delegation_results: 8,
            max_persisted_transcripts: Some(10),
        }
    }
}

fn default_auto_compact_threshold_percent() -> Option<u8> {
    // Leaves a quarter of the window for the turn that follows the compaction:
    // the summary, the next user message, and whatever tool results that turn
    // produces all have to fit after the threshold is crossed.
    Some(75)
}

impl CompactionConfig {
    /// Resolves the token count at which a run compacts, for a model whose
    /// context window is `context_window`. `None` means this run does not
    /// auto-compact.
    ///
    /// Every outcome, by [`auto_compact_trigger`](Self::auto_compact_trigger):
    ///
    /// - [`Off`](AutoCompactTrigger::Off) — `None`, always.
    /// - [`WindowShareOnly`](AutoCompactTrigger::WindowShareOnly) — the
    ///   percentage of a known `context_window`; `None` when the window or the
    ///   percentage is unknown. The absolute number is never consulted.
    /// - [`Thresholds`](AutoCompactTrigger::Thresholds) — `None` when
    ///   [`auto_compact_threshold_tokens`](Self::auto_compact_threshold_tokens)
    ///   is `None`; otherwise the percentage of a known `context_window` when
    ///   both are set, and that absolute number in every remaining case.
    ///
    /// A percentage above 100 is treated as 100, so the threshold can never
    /// exceed the window it is a share of.
    pub fn auto_compact_threshold(&self, context_window: Option<usize>) -> Option<usize> {
        match self.auto_compact_trigger {
            AutoCompactTrigger::Off => None,
            AutoCompactTrigger::WindowShareOnly => Some(window_share(
                context_window?,
                self.auto_compact_threshold_percent?,
            )),
            AutoCompactTrigger::Thresholds => {
                let fallback = self.auto_compact_threshold_tokens?;

                match (context_window, self.auto_compact_threshold_percent) {
                    (Some(window), Some(percent)) => Some(window_share(window, percent)),
                    _ => Some(fallback),
                }
            }
        }
    }

    /// Whether auto-compaction can fire at all, for *some* context window.
    ///
    /// The off state is otherwise only observable by resolving the threshold
    /// against a window and finding `None`, which a host cannot do
    /// window-independently without reimplementing
    /// [`auto_compact_threshold`](Self::auto_compact_threshold). `true` does
    /// not promise this run compacts: under
    /// [`AutoCompactTrigger::WindowShareOnly`] a model with no declared
    /// context window still never reaches a threshold.
    pub fn auto_compact_enabled(&self) -> bool {
        match self.auto_compact_trigger {
            AutoCompactTrigger::Off => false,
            AutoCompactTrigger::WindowShareOnly => self.auto_compact_threshold_percent.is_some(),
            AutoCompactTrigger::Thresholds => self.auto_compact_threshold_tokens.is_some(),
        }
    }
}

/// `percent` of `window`, saturating, with `percent` clamped to 100 so a
/// threshold can never land past the window it bounds.
fn window_share(window: usize, percent: u8) -> usize {
    window.saturating_mul(percent.min(100) as usize) / 100
}

/// Bounds how much of an oversized tool result enters the model's view.
///
/// A result at or below `threshold_bytes` is inserted byte-identically to a
/// run without paging. Above it, the transcript receives the first window
/// (at most `page_bytes`, cut on a line boundary) plus a trailer naming the
/// `read_tool_result` call that returns the next window; the full result is
/// retained in memory for the life of the agent so nothing is lost.
///
/// Paging is applied *after* the runtime's own tool-result limiter
/// (`RuntimePolicy::with_max_tool_result_bytes` /
/// `with_max_tool_result_lines`), so a `threshold_bytes` above those caps
/// never triggers — the limiter clamps the result first. Enabling paging
/// therefore means raising the policy caps to whatever a tool may legitimately
/// return and leaving them as the anti-abuse backstop.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolResultPagingConfig {
    /// Results at or below this size are inserted whole. Default 64 KiB.
    pub threshold_bytes: usize,
    /// Maximum bytes per inserted page/window. Default 32 KiB.
    pub page_bytes: usize,
}

impl Default for ToolResultPagingConfig {
    fn default() -> Self {
        Self {
            threshold_bytes: 64 * 1024,
            page_bytes: 32 * 1024,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkspaceConfig {
    pub base_dir: PathBuf,
    pub auto_route_shell: bool,
}

impl Default for WorkspaceConfig {
    fn default() -> Self {
        let base_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        Self {
            base_dir,
            auto_route_shell: true,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MemoryConfig {
    pub auto_recall_enabled: bool,
    pub auto_recall_limit: usize,
    pub auto_recall_char_budget: usize,
    pub tool_search_limit: usize,
    pub write_tools_enabled: bool,
}

impl Default for MemoryConfig {
    fn default() -> Self {
        Self {
            auto_recall_enabled: true,
            auto_recall_limit: 3,
            auto_recall_char_budget: 2_000,
            tool_search_limit: 10,
            write_tools_enabled: true,
        }
    }
}

#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolProfile {
    #[serde(default)]
    pub allowed_tools: Option<BTreeSet<String>>,
    #[serde(default)]
    pub hidden_tools: BTreeSet<String>,
}

impl ToolProfile {
    pub fn all() -> Self {
        Self::default()
    }

    pub fn only<I, S>(tools: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            allowed_tools: Some(tools.into_iter().map(Into::into).collect()),
            hidden_tools: BTreeSet::new(),
        }
    }

    pub fn hide<I, S>(tools: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            allowed_tools: None,
            hidden_tools: tools.into_iter().map(Into::into).collect(),
        }
    }

    pub fn allows(&self, tool_name: &str) -> bool {
        if let Some(allowed_tools) = &self.allowed_tools
            && !allowed_tools.contains(tool_name)
        {
            return false;
        }

        !self.hidden_tools.contains(tool_name)
    }
}

#[cfg(not(test))]
fn default_team_dir() -> PathBuf {
    crate::default_paths::workspace_default_paths().team_dir
}

#[cfg(test)]
fn default_team_dir() -> PathBuf {
    let suffix = NEXT_TEST_TRANSCRIPT_DIR_ID.fetch_add(1, Ordering::Relaxed);
    std::env::temp_dir()
        .join("mentra-test-team")
        .join(format!("process-{}-{suffix}", std::process::id()))
}

#[cfg(not(test))]
fn default_transcript_dir() -> PathBuf {
    crate::default_paths::workspace_default_paths().transcripts_dir
}

#[cfg(not(test))]
fn default_tasks_dir() -> PathBuf {
    crate::default_paths::workspace_default_paths().tasks_dir
}

#[cfg(test)]
fn default_tasks_dir() -> PathBuf {
    let suffix = NEXT_TEST_TRANSCRIPT_DIR_ID.fetch_add(1, Ordering::Relaxed);
    std::env::temp_dir()
        .join("mentra-test-tasks")
        .join(format!("process-{}-{suffix}", std::process::id()))
}

#[cfg(test)]
fn default_transcript_dir() -> PathBuf {
    let suffix = NEXT_TEST_TRANSCRIPT_DIR_ID.fetch_add(1, Ordering::Relaxed);
    std::env::temp_dir()
        .join("mentra-test-transcripts")
        .join(format!("process-{}-{suffix}", std::process::id()))
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
    pub system: Option<String>,
    pub tool_choice: Option<ToolChoice>,
    #[serde(default)]
    pub tool_profile: ToolProfile,
    pub temperature: Option<f32>,
    pub max_output_tokens: Option<u32>,
    pub metadata: BTreeMap<String, String>,
    #[serde(default)]
    pub provider_request_options: ProviderRequestOptions,
    pub team: TeamConfig,
    pub task: TaskConfig,
    pub workspace: WorkspaceConfig,
    #[serde(default)]
    pub memory: MemoryConfig,
    #[serde(alias = "context_compaction")]
    pub compaction: CompactionConfig,
    /// `None` (the default) preserves the unpaged behaviour exactly: every
    /// tool result enters the transcript as produced, and `read_tool_result`
    /// is absent from the agent's tool roster.
    #[serde(default)]
    pub tool_result_paging: Option<ToolResultPagingConfig>,
}

impl Default for AgentConfig {
    fn default() -> Self {
        Self {
            system: None,
            tool_choice: Some(ToolChoice::default()),
            tool_profile: ToolProfile::default(),
            temperature: None,
            max_output_tokens: Some(8192),
            metadata: BTreeMap::new(),
            provider_request_options: ProviderRequestOptions::default(),
            team: TeamConfig::default(),
            task: TaskConfig::default(),
            workspace: WorkspaceConfig::default(),
            memory: MemoryConfig::default(),
            compaction: CompactionConfig::default(),
            tool_result_paging: None,
        }
    }
}

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

    use crate::provider::{ReasoningEffort, ReasoningOptions};

    #[test]
    fn a_known_context_window_sets_the_threshold_not_a_constant() {
        // 50k is most of a 64k window and a rounding error in a 1M one. The
        // same config has to mean something different for each.
        let compaction = CompactionConfig::default();

        assert_eq!(
            compaction.auto_compact_threshold(Some(1_048_576)),
            Some(786_432)
        );
        assert_eq!(
            compaction.auto_compact_threshold(Some(64_000)),
            Some(48_000)
        );
    }

    #[test]
    fn an_unknown_context_window_falls_back_to_the_absolute_threshold() {
        let compaction = CompactionConfig::default();

        assert_eq!(compaction.auto_compact_threshold(None), Some(50_000));
    }

    #[test]
    fn under_the_threshold_trigger_a_missing_token_count_is_still_off() {
        // The default trigger is the pre-0.24 resolution, where the absolute
        // number doubles as the off switch. A stored config that used it that
        // way keeps meaning off, and a known window must not switch it back on.
        let compaction = CompactionConfig {
            auto_compact_threshold_tokens: None,
            ..Default::default()
        };

        assert_eq!(
            compaction.auto_compact_trigger,
            AutoCompactTrigger::Thresholds
        );
        assert_eq!(compaction.auto_compact_threshold(Some(200_000)), None);
        assert_eq!(compaction.auto_compact_threshold(None), None);
        assert!(!compaction.auto_compact_enabled());
    }

    #[test]
    fn the_window_share_trigger_compacts_on_the_window_and_never_on_a_constant() {
        // The state basis could not spell: compact at 75% of a window that is
        // known, and do nothing at all when it is not — without inventing an
        // absolute token count that goes live exactly when the guess is worst.
        let compaction = CompactionConfig {
            auto_compact_trigger: AutoCompactTrigger::WindowShareOnly,
            ..Default::default()
        };

        assert_eq!(
            compaction.auto_compact_threshold(Some(200_000)),
            Some(150_000)
        );
        assert_eq!(compaction.auto_compact_threshold(None), None);
        assert!(compaction.auto_compact_enabled());
    }

    #[test]
    fn the_window_share_trigger_ignores_the_absolute_number_entirely() {
        let compaction = CompactionConfig {
            auto_compact_trigger: AutoCompactTrigger::WindowShareOnly,
            auto_compact_threshold_tokens: Some(9),
            ..Default::default()
        };

        assert_eq!(compaction.auto_compact_threshold(None), None);
        assert_eq!(
            compaction.auto_compact_threshold(Some(64_000)),
            Some(48_000)
        );
    }

    #[test]
    fn the_window_share_trigger_without_a_percentage_never_compacts() {
        // Nothing left to take a share of: the honest answer is off, not a
        // silent fall back onto the absolute number the host opted out of.
        let compaction = CompactionConfig {
            auto_compact_trigger: AutoCompactTrigger::WindowShareOnly,
            auto_compact_threshold_percent: None,
            ..Default::default()
        };

        assert_eq!(compaction.auto_compact_threshold(Some(200_000)), None);
        assert_eq!(compaction.auto_compact_threshold(None), None);
        assert!(!compaction.auto_compact_enabled());
    }

    #[test]
    fn the_explicit_off_switch_survives_both_threshold_numbers() {
        let compaction = CompactionConfig {
            auto_compact_trigger: AutoCompactTrigger::Off,
            auto_compact_threshold_tokens: Some(1),
            auto_compact_threshold_percent: Some(1),
            ..Default::default()
        };

        assert_eq!(compaction.auto_compact_threshold(Some(200_000)), None);
        assert_eq!(compaction.auto_compact_threshold(None), None);
        assert!(!compaction.auto_compact_enabled());
    }

    #[test]
    fn a_stored_config_without_the_trigger_field_keeps_the_pre_0_24_resolution() {
        for tokens in [Some(50_000), None] {
            for percent in [Some(75u8), None] {
                let expected = CompactionConfig {
                    auto_compact_threshold_tokens: tokens,
                    auto_compact_threshold_percent: percent,
                    ..Default::default()
                };
                let mut stored = serde_json::to_value(&expected).unwrap();
                stored
                    .as_object_mut()
                    .unwrap()
                    .remove("auto_compact_trigger");

                let loaded: CompactionConfig = serde_json::from_value(stored).unwrap();

                assert_eq!(loaded.auto_compact_trigger, AutoCompactTrigger::Thresholds);
                for window in [Some(200_000), Some(64_000), None] {
                    assert_eq!(
                        loaded.auto_compact_threshold(window),
                        expected.auto_compact_threshold(window),
                        "tokens={tokens:?} percent={percent:?} window={window:?}"
                    );
                }
            }
        }
    }

    #[test]
    fn the_trigger_round_trips_through_serde() {
        for trigger in [
            AutoCompactTrigger::Thresholds,
            AutoCompactTrigger::Off,
            AutoCompactTrigger::WindowShareOnly,
        ] {
            let config = CompactionConfig {
                auto_compact_trigger: trigger,
                ..Default::default()
            };
            let round_tripped: CompactionConfig =
                serde_json::from_value(serde_json::to_value(&config).unwrap()).unwrap();

            assert_eq!(round_tripped.auto_compact_trigger, trigger);
        }
    }

    #[test]
    fn clearing_the_percentage_pins_the_threshold_to_the_absolute_number() {
        let compaction = CompactionConfig {
            auto_compact_threshold_percent: None,
            ..Default::default()
        };

        assert_eq!(
            compaction.auto_compact_threshold(Some(1_000_000)),
            Some(50_000)
        );
    }

    #[test]
    fn compaction_keeps_every_tool_result_by_default() {
        let compaction = CompactionConfig::default();

        assert_eq!(compaction.keep_recent_tool_results, usize::MAX);
        assert_eq!(compaction.projected_tool_result_budget, None);
        assert!(
            serde_json::to_value(compaction)
                .unwrap()
                .get("projected_tool_result_budget")
                .is_none(),
            "the disabled additive policy preserves the pre-0.22 JSON shape"
        );
    }

    #[test]
    fn compaction_config_without_the_budget_field_keeps_legacy_policy() {
        let mut stored = serde_json::to_value(CompactionConfig {
            keep_recent_tool_results: 2,
            ..Default::default()
        })
        .unwrap();
        stored
            .as_object_mut()
            .unwrap()
            .remove("projected_tool_result_budget");

        let restored: CompactionConfig = serde_json::from_value(stored).unwrap();

        assert_eq!(restored.keep_recent_tool_results, 2);
        assert_eq!(restored.projected_tool_result_budget, None);
    }

    #[test]
    fn projected_tool_result_budget_round_trips_zero_and_nonzero_limits() {
        for projected_tool_result_budget in [
            ProjectedToolResultBudget {
                max_bytes: 0,
                prioritize_recent_results: 0,
                max_preview_bytes: 0,
            },
            ProjectedToolResultBudget {
                max_bytes: 32 * 1024,
                prioritize_recent_results: 4,
                max_preview_bytes: 2048,
            },
        ] {
            let config = CompactionConfig {
                keep_recent_tool_results: 1,
                projected_tool_result_budget: Some(projected_tool_result_budget),
                ..Default::default()
            };

            let restored: CompactionConfig =
                serde_json::from_value(serde_json::to_value(&config).unwrap()).unwrap();

            assert_eq!(restored, config);
        }
    }

    #[test]
    fn tool_profile_defaults_to_allowing_everything() {
        let profile = ToolProfile::default();

        assert!(profile.allows("shell"));
        assert!(profile.allows("files"));
    }

    #[test]
    fn tool_profile_only_restricts_to_allowlist() {
        let profile = ToolProfile::only(["shell", "files"]);

        assert!(profile.allows("shell"));
        assert!(profile.allows("files"));
        assert!(!profile.allows("task"));
    }

    #[test]
    fn tool_profile_hide_blocks_named_tools() {
        let profile = ToolProfile::hide(["shell", "background_run"]);

        assert!(!profile.allows("shell"));
        assert!(!profile.allows("background_run"));
        assert!(profile.allows("files"));
    }

    #[test]
    fn tool_profile_respects_allowlist_and_hidden_overrides() {
        let profile = ToolProfile {
            allowed_tools: Some(["shell", "files"].into_iter().map(str::to_string).collect()),
            hidden_tools: ["shell"].into_iter().map(str::to_string).collect(),
        };

        assert!(!profile.allows("shell"));
        assert!(profile.allows("files"));
        assert!(!profile.allows("task"));
    }

    #[test]
    fn agent_config_deserializes_without_tool_profile_field() {
        let config: AgentConfig = serde_json::from_value(json!({
            "system": null,
            "tool_choice": serde_json::to_value(ToolChoice::Auto).expect("serialize tool choice"),
            "temperature": null,
            "max_output_tokens": 8192,
            "metadata": {},
            "provider_request_options": {},
            "team": TeamConfig::default(),
            "task": TaskConfig::default(),
            "workspace": WorkspaceConfig::default(),
            "memory": MemoryConfig::default(),
            "context_compaction": CompactionConfig::default()
        }))
        .expect("deserialize config without tool profile");

        assert_eq!(config.tool_profile, ToolProfile::default());
    }

    #[test]
    fn provider_request_options_default_to_disabled_tool_search() {
        let options = ProviderRequestOptions::default();

        assert_eq!(options.tool_search_mode, ToolSearchMode::Disabled);
        assert_eq!(options.reasoning, None);
    }

    #[test]
    fn agent_config_deserializes_without_tool_search_mode() {
        let config: AgentConfig = serde_json::from_value(json!({
            "system": null,
            "tool_choice": serde_json::to_value(ToolChoice::Auto).expect("serialize tool choice"),
            "temperature": null,
            "max_output_tokens": 8192,
            "metadata": {},
            "provider_request_options": {
                "responses": {
                    "parallel_tool_calls": true
                }
            },
            "team": TeamConfig::default(),
            "task": TaskConfig::default(),
            "workspace": WorkspaceConfig::default(),
            "memory": MemoryConfig::default(),
            "context_compaction": CompactionConfig::default()
        }))
        .expect("deserialize config without tool search mode");

        assert_eq!(
            config.provider_request_options.tool_search_mode,
            ToolSearchMode::Disabled
        );
        assert_eq!(
            config
                .provider_request_options
                .responses
                .parallel_tool_calls,
            Some(true)
        );
    }

    #[test]
    fn tool_result_paging_is_disabled_by_default() {
        assert_eq!(AgentConfig::default().tool_result_paging, None);
    }

    #[test]
    fn tool_result_paging_defaults_to_64_kib_threshold_and_32_kib_pages() {
        let paging = ToolResultPagingConfig::default();

        assert_eq!(paging.threshold_bytes, 64 * 1024);
        assert_eq!(paging.page_bytes, 32 * 1024);
    }

    #[test]
    fn agent_config_deserializes_without_tool_result_paging_field() {
        let config: AgentConfig = serde_json::from_value(json!({
            "system": null,
            "tool_choice": serde_json::to_value(ToolChoice::Auto).expect("serialize tool choice"),
            "temperature": null,
            "max_output_tokens": 8192,
            "metadata": {},
            "provider_request_options": {},
            "team": TeamConfig::default(),
            "task": TaskConfig::default(),
            "workspace": WorkspaceConfig::default(),
            "memory": MemoryConfig::default(),
            "context_compaction": CompactionConfig::default()
        }))
        .expect("deserialize config persisted before paging existed");

        assert_eq!(config.tool_result_paging, None);
    }

    #[test]
    fn agent_config_round_trips_tool_result_paging() {
        let config = AgentConfig {
            tool_result_paging: Some(ToolResultPagingConfig {
                threshold_bytes: 4_096,
                page_bytes: 1_024,
            }),
            ..Default::default()
        };

        let restored: AgentConfig =
            serde_json::from_value(serde_json::to_value(&config).expect("serialize config"))
                .expect("deserialize config");

        assert_eq!(restored.tool_result_paging, config.tool_result_paging);
    }

    #[test]
    fn agent_config_deserializes_reasoning_options() {
        let config: AgentConfig = serde_json::from_value(json!({
            "system": null,
            "tool_choice": serde_json::to_value(ToolChoice::Auto).expect("serialize tool choice"),
            "temperature": null,
            "max_output_tokens": 8192,
            "metadata": {},
            "provider_request_options": {
                "reasoning": {
                    "effort": "high"
                }
            },
            "team": TeamConfig::default(),
            "task": TaskConfig::default(),
            "workspace": WorkspaceConfig::default(),
            "memory": MemoryConfig::default(),
            "context_compaction": CompactionConfig::default()
        }))
        .expect("deserialize config with reasoning options");

        assert_eq!(
            config.provider_request_options.reasoning,
            Some(ReasoningOptions {
                effort: Some(ReasoningEffort::High),
                summary: None,
            })
        );
    }
}