ag-session 0.19.5

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
926
//! Agent provider kinds, models, and selections, with persisted-value parsing
//! and model resolution against available providers.

use std::fmt;
use std::str::FromStr;
use std::sync::{Mutex, OnceLock, PoisonError};

use ag_contracts::{ReasoningLevel, SpeedMode};
use rustc_hash::FxHashMap;

/// Supported agent provider families.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentKind {
    /// Google Antigravity CLI/backend.
    Antigravity,
    /// Anthropic Claude Code CLI/backend.
    Claude,
    /// `OpenAI` Codex CLI/backend.
    Codex,
    /// Native in-process `ag-harness` backend, which has no CLI executable.
    Harness,
}

// Resolve a catalog entry's short display name, defaulting to its id.
macro_rules! model_short_name {
    ($id:literal) => {
        $id
    };
    ($id:literal, $short_name:literal) => {
        $short_name
    };
}

// Generate typed identities, exhaustive metadata, and ordered provider lists
// from the same declaration so adding a model cannot omit one of those
// surfaces. A model without an explicit `short_name` displays its id.
macro_rules! define_model_catalog {
    ($($provider:ident { $(
        $(#[$attribute:meta])*
        $model:ident = $discriminant:literal => {
            id: $id:literal,
            $(short_name: $short_name:literal,)?
            description: $description:literal,
            fast: $fast:literal,
        },
    )* })*) => {
        /// Supported agent model names across all providers.
        ///
        /// Provider ownership lives on [`AgentSelection`] because some
        /// providers share models. Removing a variant is a Rust source API
        /// change even when [`AgentModel::retired_replacement`] preserves saved ids.
        #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
        #[repr(u8)]
        pub enum AgentModel {
            $($( $(#[$attribute])* $model = $discriminant, )*)*
            /// Model a local or self-hosted OpenAI-compatible server, such as
            /// Ollama, serves to the native harness. Its id is
            /// `openai-compatible/<served model>`, such as
            /// `openai-compatible/qwen3:latest`.
            OpenAiCompatible(ServedModel) = 18,
        }

        impl AgentModel {
            /// All fixed catalog models, grouped in catalog provider order.
            /// Served [`AgentModel::OpenAiCompatible`] models are discovered at
            /// runtime and never listed here.
            pub const ALL: &[Self] = &[$($(Self::$model,)*)*];

            /// Returns the provider whose catalog declares this model.
            ///
            /// Shared ids, such as the Claude models Antigravity also serves,
            /// keep this provider as their owner, so provider resolution
            /// prefers it whenever it is available.
            #[must_use]
            pub const fn owner_kind(self) -> AgentKind {
                match self {
                    $($(Self::$model => AgentKind::$provider,)*)*
                    Self::OpenAiCompatible(_) => AgentKind::Harness,
                }
            }

            const fn descriptor(self) -> ModelDescriptor {
                match self {
                    $($(Self::$model => ModelDescriptor {
                        description: $description,
                        id: $id,
                        short_name: model_short_name!($id $(, $short_name)?),
                        supports_fast_mode: $fast,
                    },)*)*
                    Self::OpenAiCompatible(served) => ModelDescriptor {
                        description: "Model served by a local or self-hosted \
                                      OpenAI-compatible server, such as Ollama.",
                        id: served.id(),
                        short_name: served.id(),
                        supports_fast_mode: false,
                    },
                }
            }
        }

        impl AgentKind {
            /// Returns the models declared under this provider's catalog
            /// block, without the models it shares with another provider.
            const fn declared_models(self) -> &'static [AgentModel] {
                match self {
                    $(Self::$provider => &[$(AgentModel::$model,)*],)*
                }
            }
        }
    };
}

define_model_catalog! {
    Antigravity {
        /// Gemini Argon model backed by `gemini-4-argon`.
        Gemini4Argon = 17 => {
            id: "gemini-4-argon",
            description: "Gemini 4 Argon model.",
            fast: false,
        },
        /// Gemini Hydrogen model backed by `gemini-4-hydrogen`.
        Gemini4Hydrogen = 30 => {
            id: "gemini-4-hydrogen",
            description: "Gemini 4 Hydrogen model with extra-high reasoning effort.",
            fast: false,
        },
        /// Antigravity orchestrator backed by `gemini-pro-orchestrator-g1-pro`,
        /// which Antigravity labels Orchestrator (Argon).
        GeminiProOrchestrator = 31 => {
            id: "gemini-pro-orchestrator-g1-pro",
            description: "Orchestrator (Argon) model that coordinates subagents.",
            fast: false,
        },
        /// Fast Gemini model backed by `gemini-3.8-flash`.
        Gemini38Flash = 4 => {
            id: "gemini-3.8-flash",
            description: "Fast Gemini model for agentic and multimodal tasks.",
            fast: false,
        },
        /// Open-weight `OpenAI` model backed by `gpt-oss-120b`.
        GptOss120b = 32 => {
            id: "gpt-oss-120b",
            description: "Open-weight GPT-OSS 120B model served through Antigravity.",
            fast: false,
        },
    }
    Claude {
        /// Claude Fable model backed by `claude-fable-5-2`.
        ClaudeFable52 = 10 => {
            id: "claude-fable-5-2",
            short_name: "fable-5.2",
            description: "Claude Fable model for creative, narrative-heavy tasks.",
            fast: false,
        },
        /// Claude Opus model backed by `claude-opus-5-5`.
        ClaudeOpus55 = 8 => {
            id: "claude-opus-5-5",
            short_name: "opus-5.5",
            description: "Latest Claude Opus model for complex agentic tasks.",
            fast: true,
        },
        /// Claude Sonnet model backed by `claude-sonnet-5-5`.
        ClaudeSonnet55 = 9 => {
            id: "claude-sonnet-5-5",
            short_name: "sonnet-5.5",
            description: "Balanced Claude model for quality and latency.",
            fast: false,
        },
        /// Claude Haiku model backed by `claude-haiku-5-5`.
        ClaudeHaiku55 = 11 => {
            id: "claude-haiku-5-5",
            short_name: "haiku-5.5",
            description: "Fast Claude model for lighter tasks.",
            fast: false,
        },
    }
    Codex {
        /// Codex Astra model backed by `gpt-6-astra`.
        Gpt6Astra = 0 => {
            id: "gpt-6-astra",
            description: "Most capable Codex model for the hardest end-to-end work.",
            fast: true,
        },
        /// Codex Sol model backed by `gpt-6.1-sol`.
        Gpt61Sol = 1 => {
            id: "gpt-6.1-sol",
            description: "Near-Astra Codex model for complex work at a lower cost.",
            fast: true,
        },
        /// Codex Luna model backed by `gpt-6-luna`.
        Gpt6Luna = 2 => {
            id: "gpt-6-luna",
            description: "Efficient Codex model for focused, high-volume tasks.",
            fast: true,
        },
        /// Codex Terra model backed by `gpt-5.6-terra`.
        Gpt56Terra = 3 => {
            id: "gpt-5.6-terra",
            description: "Current Codex model for balanced coding performance.",
            fast: true,
        },
        /// Codex spark model backed by `gpt-5.3-codex-spark`.
        Gpt53CodexSpark = 7 => {
            id: "gpt-5.3-codex-spark",
            description: "Codex spark model for quick coding iterations.",
            fast: false,
        },
    }
    Harness {
        /// Muse model backed by `muse-spark-1.3`.
        MuseSpark13 = 12 => {
            id: "muse-spark-1.3",
            description: "Muse Spark model served through the native harness.",
            fast: false,
        },
        /// Discounted Muse model backed by `muse-spark-1.3-contributor`,
        /// whose prompts and completions Meta may use for training.
        MuseSpark13Contributor = 19 => {
            id: "muse-spark-1.3-contributor",
            description: "Cheap Muse Spark tier; Meta may train on its prompts and completions.",
            fast: false,
        },
        /// Kimi model backed by `kimi-k3`.
        KimiK3 = 13 => {
            id: "kimi-k3",
            description: "Latest Kimi model served through the native harness.",
            fast: false,
        },
        /// Kimi model backed by `kimi-k2.6`.
        KimiK26 = 14 => {
            id: "kimi-k2.6",
            description: "Previous Kimi model served through the native harness.",
            fast: false,
        },
        /// Qwen model backed by `qwen3.8-max`.
        Qwen38Max = 15 => {
            id: "qwen3.8-max",
            description: "Most capable Qwen model served through the native harness.",
            fast: false,
        },
        /// Qwen model backed by `qwen-plus`.
        QwenPlus = 16 => {
            id: "qwen-plus",
            description: "Balanced Qwen model served through the native harness.",
            fast: false,
        },
        /// Cheap Qwen model backed by `qwen3.8-flash`.
        Qwen38Flash = 20 => {
            id: "qwen3.8-flash",
            description: "Cheap Qwen model for simple tasks such as titles and commit messages.",
            fast: false,
        },
        /// Cheapest Qwen model backed by `qwen3.7-flash`.
        Qwen37Flash = 21 => {
            id: "qwen3.7-flash",
            description: "Cheapest Qwen model for short, simple tasks.",
            fast: false,
        },
        /// `gpt-6.1-sol` billed to the user's `ChatGPT` plan.
        ChatGptGpt61Sol = 22 => {
            id: "chatgpt/gpt-6.1-sol",
            description: "GPT-6.1 Sol billed to your ChatGPT plan instead of API credits.",
            fast: false,
        },
        /// `gpt-6.1-terra` billed to the user's `ChatGPT` plan.
        ChatGptGpt61Terra = 23 => {
            id: "chatgpt/gpt-6.1-terra",
            description: "GPT-6.1 Terra billed to your ChatGPT plan instead of API credits.",
            fast: false,
        },
        /// `gpt-6-astra` billed to the user's `ChatGPT` plan.
        ChatGptGpt6Astra = 24 => {
            id: "chatgpt/gpt-6-astra",
            description: "GPT-6 Astra billed to your ChatGPT plan instead of API credits.",
            fast: false,
        },
        /// `gpt-6-sol` billed to the user's `ChatGPT` plan.
        ChatGptGpt6Sol = 25 => {
            id: "chatgpt/gpt-6-sol",
            description: "GPT-6 Sol billed to your ChatGPT plan instead of API credits.",
            fast: false,
        },
        /// `gpt-6-luna` billed to the user's `ChatGPT` plan.
        ChatGptGpt6Luna = 26 => {
            id: "chatgpt/gpt-6-luna",
            description: "GPT-6 Luna billed to your ChatGPT plan instead of API credits.",
            fast: false,
        },
        /// `gpt-5.6-sol` billed to the user's `ChatGPT` plan.
        ChatGptGpt56Sol = 27 => {
            id: "chatgpt/gpt-5.6-sol",
            description: "GPT-5.6 Sol billed to your ChatGPT plan instead of API credits.",
            fast: false,
        },
        /// `gpt-5.6-terra` billed to the user's `ChatGPT` plan.
        ChatGptGpt56Terra = 28 => {
            id: "chatgpt/gpt-5.6-terra",
            description: "GPT-5.6 Terra billed to your ChatGPT plan instead of API credits.",
            fast: false,
        },
        /// `gpt-5.6-luna` billed to the user's `ChatGPT` plan.
        ChatGptGpt56Luna = 29 => {
            id: "chatgpt/gpt-5.6-luna",
            description: "GPT-5.6 Luna billed to your ChatGPT plan instead of API credits.",
            fast: false,
        },
    }
}

/// Models the Antigravity CLI serves, in its `agy models` display order: its
/// own catalog models with the Claude models it shares with
/// [`AgentKind::Claude`] placed before GPT-OSS.
const ANTIGRAVITY_MODELS: &[AgentModel] = &[
    AgentModel::Gemini4Argon,
    AgentModel::Gemini4Hydrogen,
    AgentModel::GeminiProOrchestrator,
    AgentModel::Gemini38Flash,
    AgentModel::ClaudeOpus55,
    AgentModel::ClaudeSonnet55,
    AgentModel::GptOss120b,
];

/// Hosted models the native harness serves, in display order: its own
/// catalog models, then the Codex models `OpenAI`'s Responses API also
/// serves, which the harness shares with [`AgentKind::Codex`]. Served
/// [`AgentModel::OpenAiCompatible`] models are discovered at runtime and
/// listed before these.
///
/// ChatGPT-plan models carry a `chatgpt/` id prefix, distinct from the bare
/// ids of the same models on the API-billed `OpenAI` provider, so choosing
/// one never bills API credits. They precede the `OpenAI` models, which come
/// last because `OPENAI_API_KEY` is often set for other tools, so its mere
/// presence must not move sessions from a deliberately configured harness
/// provider to paid `OpenAI` usage. The
/// harness library also catalogs the deprecated `gpt-5.3-codex`, which
/// Agentty retires to [`AgentModel::Gpt61Sol`] instead of offering it. Cheap
/// tiers follow their provider's other models, so adding one never changes
/// which configured model a new session starts on.
const HARNESS_MODELS: &[AgentModel] = &[
    AgentModel::MuseSpark13,
    AgentModel::MuseSpark13Contributor,
    AgentModel::KimiK3,
    AgentModel::KimiK26,
    AgentModel::Qwen38Max,
    AgentModel::QwenPlus,
    AgentModel::Qwen38Flash,
    AgentModel::Qwen37Flash,
    AgentModel::ChatGptGpt61Sol,
    AgentModel::ChatGptGpt61Terra,
    AgentModel::ChatGptGpt6Astra,
    AgentModel::ChatGptGpt6Sol,
    AgentModel::ChatGptGpt6Luna,
    AgentModel::ChatGptGpt56Sol,
    AgentModel::ChatGptGpt56Terra,
    AgentModel::ChatGptGpt56Luna,
    AgentModel::Gpt61Sol,
    AgentModel::Gpt6Astra,
    AgentModel::Gpt6Luna,
    AgentModel::Gpt56Terra,
];

/// Id prefix of every [`AgentModel::OpenAiCompatible`] model.
const OPENAI_COMPATIBLE_ID: &str = "openai-compatible";

struct ModelDescriptor {
    description: &'static str,
    id: &'static str,
    short_name: &'static str,
    supports_fast_mode: bool,
}

/// Model an OpenAI-compatible server serves, identified as
/// `openai-compatible/<served model>`.
///
/// Servers name their models at runtime, so each distinct id is interned once
/// and kept for the process lifetime, which keeps [`AgentModel`] `Copy` and
/// one pointer wide. A process interns only the names its servers report and
/// its sessions store.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct ServedModel(&'static &'static str);

impl ServedModel {
    /// Model named by the host's `OPENAI_COMPATIBLE_MODEL`, stored under the
    /// bare `openai-compatible` id.
    pub const CONFIGURED: Self = Self(&OPENAI_COMPATIBLE_ID);

    /// Returns the served model `name`, such as `qwen3:latest`, or `None`
    /// for a blank name.
    #[must_use]
    pub fn new(name: &str) -> Option<Self> {
        let name = name.trim();
        if name.is_empty() {
            return None;
        }

        Some(Self(intern(format!("{OPENAI_COMPATIBLE_ID}/{name}"))))
    }

    /// Returns the stable model id, such as `openai-compatible/qwen3:latest`.
    #[must_use]
    pub const fn id(self) -> &'static str {
        self.0
    }

    /// Returns the name the server serves, or `None` for
    /// [`Self::CONFIGURED`], whose name the host environment supplies.
    #[must_use]
    pub fn name(self) -> Option<&'static str> {
        self.id()
            .strip_prefix(OPENAI_COMPATIBLE_ID)?
            .strip_prefix('/')
    }

    /// Parses an `openai-compatible` or `openai-compatible/<name>` id.
    fn parse(id: &str) -> Option<Self> {
        if id == OPENAI_COMPATIBLE_ID {
            return Some(Self::CONFIGURED);
        }

        Self::new(id.strip_prefix(OPENAI_COMPATIBLE_ID)?.strip_prefix('/')?)
    }
}

/// Returns the process-lifetime copy of `id`, leaking it on first use.
fn intern(id: String) -> &'static &'static str {
    static INTERNED: OnceLock<Mutex<FxHashMap<&str, &&str>>> = OnceLock::new();
    let mut interned = INTERNED
        .get_or_init(Mutex::default)
        .lock()
        .unwrap_or_else(PoisonError::into_inner);
    if let Some(existing) = interned.get(id.as_str()) {
        return existing;
    }
    let leaked: &'static &'static str = Box::leak(Box::new(&*Box::leak(id.into_boxed_str())));
    interned.insert(leaked, leaked);

    leaked
}

/// Session-level agent selection that keeps provider kind and model together.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AgentSelection {
    kind: AgentKind,
    model: AgentModel,
}

impl AgentSelection {
    /// Creates a coherent session agent selection.
    ///
    /// If `model` is not supported by `kind`, the provider's default model is
    /// used so the selection never carries unrelated provider/model values.
    #[must_use]
    pub fn new(kind: AgentKind, model: AgentModel) -> Self {
        let model = if kind.supports_model(model) {
            model
        } else {
            kind.default_model()
        };

        Self { kind, model }
    }

    /// Returns the selected agent provider kind.
    #[must_use]
    pub fn kind(self) -> AgentKind {
        self.kind
    }

    /// Returns the selected agent model.
    #[must_use]
    pub fn model(self) -> AgentModel {
        self.model
    }

    /// Returns whether this exact provider/model pair supports Fast mode,
    /// which needs a provider with a speed control; the harness serves Codex
    /// models without one.
    #[must_use]
    pub fn supports_fast_mode(self) -> bool {
        self.kind.supports_speed_mode() && self.model.descriptor().supports_fast_mode
    }

    /// Returns the compatible provider/model pair for one speed preference.
    ///
    /// Fast Claude requests require Opus, while incompatible Codex models move
    /// to the provider's default model. Providers without a speed control and
    /// already compatible selections remain unchanged.
    #[must_use]
    pub fn compatible_with_speed_mode(self, speed_mode: SpeedMode) -> Self {
        if speed_mode == SpeedMode::Normal || self.supports_fast_mode() {
            return self;
        }

        match self.kind {
            AgentKind::Claude => Self::new(AgentKind::Claude, AgentModel::ClaudeOpus55),
            AgentKind::Codex => Self::new(AgentKind::Codex, AgentKind::Codex.default_model()),
            AgentKind::Antigravity | AgentKind::Harness => self,
        }
    }
}

/// Human-readable metadata for slash-menu selectable items.
pub trait AgentSelectionMetadata {
    /// Returns a stable item name shown in menus.
    fn name(&self) -> &'static str;

    /// Returns a short descriptive subtitle shown in menus.
    fn description(&self) -> &'static str;
}

impl AgentModel {
    /// Returns the stable wire/model identifier used in persistence and CLI
    /// invocations.
    pub const fn as_str(self) -> &'static str {
        self.descriptor().id
    }

    /// Returns the compact name shown in dense views such as the session
    /// list, such as `opus-5.5` for `claude-opus-5-5`.
    ///
    /// Models without a shorter catalog name, including
    /// [`AgentModel::OpenAiCompatible`] models, display their menu name.
    #[must_use]
    pub fn short_name(self) -> &'static str {
        match self {
            Self::OpenAiCompatible(_) => self.name(),
            _ => self.descriptor().short_name,
        }
    }

    /// Returns the model identifier passed to provider transports.
    ///
    /// Callers route ids shared by several providers through the provider
    /// stored on [`AgentSelection`].
    pub fn provider_model_str(self) -> &'static str {
        self.as_str()
    }

    /// Parses one persisted model identifier and upgrades retired ids to
    /// their replacement models.
    ///
    /// Stored retired Gemini, Claude, and Codex ids are migrated forward
    /// through [`AgentModel::retired_replacement`] so existing projects and
    /// sessions continue loading after model retirements.
    ///
    /// # Errors
    /// Returns an error when `value` is not a known current or retired model
    /// identifier.
    pub fn parse_persisted(value: &str) -> Result<Self, String> {
        if let Some(replacement) = Self::retired_replacement(value) {
            return Ok(replacement);
        }

        value.parse()
    }

    /// Returns the current replacement model for a retired persisted model
    /// id, or `None` when `value` is not a retired id.
    ///
    /// This registry is the single source of truth for model retirement.
    /// Retiring a model means removing its selectable [`AgentModel`] variant
    /// and mapping its persisted id to the replacement model here. Retired
    /// ids never appear in selectable model lists. Persisted selections resolve
    /// to the replacement, and sessions that are still active are switched to
    /// it automatically. Database migrations may also normalize saved ids.
    #[must_use]
    pub fn retired_replacement(value: &str) -> Option<Self> {
        const RETIRED_MODEL_REPLACEMENTS: &[(&str, AgentModel)] = &[
            ("gemini-3-pro-preview", AgentModel::Gemini4Argon),
            ("gemini-3.1-pro", AgentModel::Gemini4Argon),
            ("gemini-3.1-pro-preview", AgentModel::Gemini4Argon),
            ("gemini-3-flash-preview", AgentModel::Gemini38Flash),
            ("gemini-3.7-flash", AgentModel::Gemini38Flash),
            ("gemini-3.6-flash", AgentModel::Gemini38Flash),
            ("gemini-3.5-flash", AgentModel::Gemini38Flash),
            ("gemini-3.5-flash-lite", AgentModel::Gemini38Flash),
            ("gemini-3.1-flash-lite-preview", AgentModel::Gemini38Flash),
            ("claude-fable-5", AgentModel::ClaudeFable52),
            ("claude-fable-5-1", AgentModel::ClaudeFable52),
            ("claude-opus-5", AgentModel::ClaudeOpus55),
            ("claude-haiku-4-5-20251001", AgentModel::ClaudeHaiku55),
            ("gpt-6-sol", AgentModel::Gpt61Sol),
            ("gpt-5.6-sol", AgentModel::Gpt61Sol),
            ("gpt-5.6-luna", AgentModel::Gpt6Luna),
            ("claude-opus-4-8", AgentModel::ClaudeOpus55),
            ("claude-opus-4-6", AgentModel::ClaudeOpus55),
            ("claude-opus-4-7", AgentModel::ClaudeOpus55),
            ("claude-sonnet-4-6", AgentModel::ClaudeSonnet55),
            ("claude-sonnet-5", AgentModel::ClaudeSonnet55),
            ("gpt-5.5", AgentModel::Gpt61Sol),
            ("gpt-5.4-mini", AgentModel::Gpt6Luna),
            ("gpt-5.4", AgentModel::Gpt61Sol),
            ("gpt-5.3-codex", AgentModel::Gpt61Sol),
            ("gpt-5.2-codex", AgentModel::Gpt53CodexSpark),
        ];

        RETIRED_MODEL_REPLACEMENTS
            .iter()
            .find(|(retired_id, _)| *retired_id == value)
            .map(|(_, replacement)| *replacement)
    }
}

/// Parses one persisted session agent/model pair without deriving the agent
/// from the model when the saved agent kind is available.
///
/// Existing databases did not persist `agent`, so rows with a missing or
/// invalid agent value fall back to a compatibility provider inferred from
/// the persisted model string. Raw `gemini-*` rows belong to Antigravity,
/// the only provider serving those models.
pub fn parse_persisted_session_agent_model(
    agent_value: Option<&str>,
    model_value: &str,
) -> AgentSelection {
    let parsed_agent = agent_value
        .filter(|value| !value.trim().is_empty())
        .and_then(|value| value.parse::<AgentKind>().ok());

    if let Some(agent_kind) = parsed_agent {
        return parse_model_for_persisted_agent(agent_kind, model_value);
    }

    let model = AgentModel::parse_persisted(model_value)
        .unwrap_or_else(|_| AgentKind::Antigravity.default_model());
    let agent_kind = legacy_agent_kind_for_model_value(model_value, model);

    AgentSelection::new(agent_kind, model)
}

/// Parses a persisted model using the already persisted agent kind as the
/// source of truth for provider ownership.
fn parse_model_for_persisted_agent(agent_kind: AgentKind, model_value: &str) -> AgentSelection {
    if let Some(model) = agent_kind.parse_model(model_value) {
        return AgentSelection::new(agent_kind, model);
    }

    if let Ok(model) = AgentModel::parse_persisted(model_value)
        && agent_kind.supports_model(model)
    {
        return AgentSelection::new(agent_kind, model);
    }

    AgentSelection::new(agent_kind, agent_kind.default_model())
}

/// Returns the provider used for legacy rows that predate explicit session
/// agent persistence.
///
/// Current ids belong to their owning provider; retired and unknown ids fall
/// back to the provider their id prefix names.
fn legacy_agent_kind_for_model_value(model_value: &str, model: AgentModel) -> AgentKind {
    if model.as_str() == model_value {
        return model.owner_kind();
    }

    if model_value.starts_with("claude-") {
        return AgentKind::Claude;
    }

    if model_value.starts_with("gpt-") {
        return AgentKind::Codex;
    }

    if model_value.starts_with("gemini-") {
        return AgentKind::Antigravity;
    }

    model.owner_kind()
}

/// Resolves one model against the currently available agent kinds.
///
/// When `model` is unsupported by every available provider, this prefers
/// `fallback_model` when any available provider supports it and otherwise falls
/// back to the first available provider default in `agent_kinds`. When no
/// providers are available, it returns `fallback_model` unchanged.
#[must_use]
pub fn resolve_model_for_available_agent_kinds(
    model: AgentModel,
    agent_kinds: &[AgentKind],
    fallback_model: AgentModel,
) -> AgentModel {
    if agent_kinds
        .iter()
        .any(|agent_kind| agent_kind.supports_model(model))
    {
        return model;
    }

    if agent_kinds
        .iter()
        .any(|agent_kind| agent_kind.supports_model(fallback_model))
    {
        return fallback_model;
    }

    agent_kinds
        .first()
        .copied()
        .map_or(fallback_model, AgentKind::default_model)
}

/// Resolves a provider kind that can run `model` from the available provider
/// list.
///
/// Shared model ids, such as the Codex models the harness also serves, can be
/// run by several providers. This helper prefers the model's
/// [`AgentModel::owner_kind`] when it is available, then uses the order of
/// `agent_kinds` as the tie-breaker, and returns `fallback_agent_kind` when no
/// available provider supports `model`.
#[must_use]
pub fn resolve_agent_kind_for_model(
    model: AgentModel,
    agent_kinds: &[AgentKind],
    fallback_agent_kind: AgentKind,
) -> AgentKind {
    let owner_kind = model.owner_kind();
    if agent_kinds.contains(&owner_kind) {
        return owner_kind;
    }

    agent_kinds
        .iter()
        .copied()
        .find(|agent_kind| agent_kind.supports_model(model))
        .unwrap_or(fallback_agent_kind)
}

/// Resolves an [`AgentSelection`] for a model-only setting.
///
/// `preferred_agent_kind` is kept when it can run `model`, which preserves the
/// current session provider for shared model ids. Otherwise the
/// available provider order decides the owning provider, falling back to
/// `preferred_agent_kind` when no available provider supports the model.
#[must_use]
pub fn resolve_agent_selection_for_model(
    model: AgentModel,
    preferred_agent_kind: AgentKind,
    agent_kinds: &[AgentKind],
) -> AgentSelection {
    let agent_kind = if preferred_agent_kind.supports_model(model) {
        preferred_agent_kind
    } else {
        resolve_agent_kind_for_model(model, agent_kinds, preferred_agent_kind)
    };

    AgentSelection::new(agent_kind, model)
}

/// Resolves the agent kind used for prompt-side `/model` selection.
///
/// This preserves `session_agent_kind` when that backend is still available
/// and otherwise falls back to the first available backend. When no backends
/// are available, it returns `None`.
#[must_use]
pub fn resolve_prompt_model_agent_kind(
    session_agent_kind: AgentKind,
    agent_kinds: &[AgentKind],
) -> Option<AgentKind> {
    if agent_kinds.contains(&session_agent_kind) {
        return Some(session_agent_kind);
    }

    agent_kinds.first().copied()
}

impl FromStr for AgentModel {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::ALL
            .iter()
            .copied()
            .find(|model| model.as_str() == value)
            .or_else(|| ServedModel::parse(value).map(Self::OpenAiCompatible))
            .ok_or_else(|| format!("unknown model: {value}"))
    }
}

impl AgentSelectionMetadata for AgentModel {
    /// Returns the model id, or the bare served name of an
    /// [`AgentModel::OpenAiCompatible`] model, such as `qwen3:latest`.
    fn name(&self) -> &'static str {
        match self {
            Self::OpenAiCompatible(served) => served.name().unwrap_or(served.id()),
            _ => (*self).provider_model_str(),
        }
    }

    fn description(&self) -> &'static str {
        self.descriptor().description
    }
}

impl AgentKind {
    /// All CLI-backed agent kinds, in display order.
    ///
    /// [`AgentKind::Harness`] runs in process, so it is never discovered from
    /// `PATH` and stays out of this list.
    pub const ALL: &[AgentKind] = &[AgentKind::Antigravity, AgentKind::Claude, AgentKind::Codex];

    /// Returns the provider CLI executable name, or `None` for the in-process
    /// harness.
    pub fn executable_name(self) -> Option<&'static str> {
        match self {
            Self::Antigravity => Some("agy"),
            Self::Claude => Some("claude"),
            Self::Codex => Some("codex"),
            Self::Harness => None,
        }
    }

    /// Returns this provider's models in their catalog display order.
    ///
    /// Antigravity also serves Claude Opus and Sonnet, and the harness serves
    /// the Codex models available through `OpenAI`'s Responses API, beside
    /// their own.
    pub fn models(self) -> &'static [AgentModel] {
        match self {
            Self::Antigravity => ANTIGRAVITY_MODELS,
            Self::Harness => HARNESS_MODELS,
            Self::Claude | Self::Codex => self.declared_models(),
        }
    }

    /// Returns the default model for this agent kind.
    pub fn default_model(self) -> AgentModel {
        match self {
            Self::Antigravity => AgentModel::Gemini4Argon,
            Self::Claude => AgentModel::ClaudeFable52,
            Self::Codex => AgentModel::Gpt61Sol,
            Self::Harness => AgentModel::MuseSpark13,
        }
    }

    /// Parses a provider-specific model string for this agent kind.
    pub fn parse_model(self, value: &str) -> Option<AgentModel> {
        let model = value.parse::<AgentModel>().ok()?;
        if !self.supports_model(model) {
            return None;
        }

        Some(model)
    }

    /// Returns whether this provider can run the given model. Only
    /// [`AgentKind::Harness`] runs served [`AgentModel::OpenAiCompatible`]
    /// models.
    pub fn supports_model(self, model: AgentModel) -> bool {
        match model {
            AgentModel::OpenAiCompatible(_) => self == Self::Harness,
            _ => self.models().contains(&model),
        }
    }

    /// Returns whether this provider exposes a response-speed control.
    ///
    /// Claude and Codex accept a per-turn speed selection, so `/speed` offers
    /// the picker and session surfaces display the active [`SpeedMode`].
    /// Antigravity has no equivalent control, so neither the command nor the
    /// speed display is offered for it.
    ///
    /// [`SpeedMode`]: ag_contracts::SpeedMode
    pub fn supports_speed_mode(self) -> bool {
        matches!(self, Self::Claude | Self::Codex)
    }
}

impl AgentSelectionMetadata for AgentKind {
    fn name(&self) -> &'static str {
        match self {
            Self::Antigravity => "antigravity",
            Self::Claude => "claude",
            Self::Codex => "codex",
            Self::Harness => "harness",
        }
    }

    fn description(&self) -> &'static str {
        match self {
            Self::Antigravity => "Google Antigravity CLI agent.",
            Self::Claude => "Anthropic Claude Code agent.",
            Self::Codex => "OpenAI Codex CLI agent.",
            Self::Harness => "Native Agentty harness agent.",
        }
    }
}

impl AgentSelectionMetadata for ReasoningLevel {
    fn name(&self) -> &'static str {
        (*self).as_str()
    }

    fn description(&self) -> &'static str {
        (*self).description()
    }
}

impl fmt::Display for AgentKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

/// Parses a provider name.
///
/// The retired `gemini` provider name parses as [`AgentKind::Antigravity`],
/// which serves the same models, so saved settings and graph snapshots from
/// the removed Gemini CLI backend keep loading.
impl FromStr for AgentKind {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "antigravity" | "agy" | "gemini" => Ok(Self::Antigravity),
            "claude" => Ok(Self::Claude),
            "codex" => Ok(Self::Codex),
            "harness" => Ok(Self::Harness),
            other => Err(format!("unknown agent kind: {other}")),
        }
    }
}

#[cfg(test)]
#[path = "agent_test.rs"]
mod tests;