Skip to main content

ag_session/
agent.rs

1//! Agent provider kinds, models, and selections, with persisted-value parsing
2//! and model resolution against available providers.
3
4use std::fmt;
5use std::str::FromStr;
6use std::sync::{Mutex, OnceLock, PoisonError};
7
8use ag_contracts::{ReasoningLevel, SpeedMode};
9use rustc_hash::FxHashMap;
10
11/// Supported agent provider families.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum AgentKind {
14    /// Google Antigravity CLI/backend.
15    Antigravity,
16    /// Anthropic Claude Code CLI/backend.
17    Claude,
18    /// `OpenAI` Codex CLI/backend.
19    Codex,
20    /// Native in-process `ag-harness` backend, which has no CLI executable.
21    Harness,
22}
23
24// Resolve a catalog entry's short display name, defaulting to its id.
25macro_rules! model_short_name {
26    ($id:literal) => {
27        $id
28    };
29    ($id:literal, $short_name:literal) => {
30        $short_name
31    };
32}
33
34// Generate typed identities, exhaustive metadata, and ordered provider lists
35// from the same declaration so adding a model cannot omit one of those
36// surfaces. A model without an explicit `short_name` displays its id.
37macro_rules! define_model_catalog {
38    ($($provider:ident { $(
39        $(#[$attribute:meta])*
40        $model:ident = $discriminant:literal => {
41            id: $id:literal,
42            $(short_name: $short_name:literal,)?
43            description: $description:literal,
44            fast: $fast:literal,
45        },
46    )* })*) => {
47        /// Supported agent model names across all providers.
48        ///
49        /// Provider ownership lives on [`AgentSelection`] because some
50        /// providers share models. Removing a variant is a Rust source API
51        /// change even when [`AgentModel::retired_replacement`] preserves saved ids.
52        #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
53        #[repr(u8)]
54        pub enum AgentModel {
55            $($( $(#[$attribute])* $model = $discriminant, )*)*
56            /// Model a local or self-hosted OpenAI-compatible server, such as
57            /// Ollama, serves to the native harness. Its id is
58            /// `openai-compatible/<served model>`, such as
59            /// `openai-compatible/qwen3:latest`.
60            OpenAiCompatible(ServedModel) = 18,
61        }
62
63        impl AgentModel {
64            /// All fixed catalog models, grouped in catalog provider order.
65            /// Served [`AgentModel::OpenAiCompatible`] models are discovered at
66            /// runtime and never listed here.
67            pub const ALL: &[Self] = &[$($(Self::$model,)*)*];
68
69            /// Returns the provider whose catalog declares this model.
70            ///
71            /// Shared ids, such as the Claude models Antigravity also serves,
72            /// keep this provider as their owner, so provider resolution
73            /// prefers it whenever it is available.
74            #[must_use]
75            pub const fn owner_kind(self) -> AgentKind {
76                match self {
77                    $($(Self::$model => AgentKind::$provider,)*)*
78                    Self::OpenAiCompatible(_) => AgentKind::Harness,
79                }
80            }
81
82            const fn descriptor(self) -> ModelDescriptor {
83                match self {
84                    $($(Self::$model => ModelDescriptor {
85                        description: $description,
86                        id: $id,
87                        short_name: model_short_name!($id $(, $short_name)?),
88                        supports_fast_mode: $fast,
89                    },)*)*
90                    Self::OpenAiCompatible(served) => ModelDescriptor {
91                        description: "Model served by a local or self-hosted \
92                                      OpenAI-compatible server, such as Ollama.",
93                        id: served.id(),
94                        short_name: served.id(),
95                        supports_fast_mode: false,
96                    },
97                }
98            }
99        }
100
101        impl AgentKind {
102            /// Returns the models declared under this provider's catalog
103            /// block, without the models it shares with another provider.
104            const fn declared_models(self) -> &'static [AgentModel] {
105                match self {
106                    $(Self::$provider => &[$(AgentModel::$model,)*],)*
107                }
108            }
109        }
110    };
111}
112
113define_model_catalog! {
114    Antigravity {
115        /// Gemini Neon model backed by `gemini-4-neon`.
116        Gemini4Neon = 33 => {
117            id: "gemini-4-neon",
118            description: "Gemini 4 Neon model with extra-high reasoning effort.",
119            fast: false,
120        },
121        /// Gemini Argon model backed by `gemini-4-argon`.
122        Gemini4Argon = 17 => {
123            id: "gemini-4-argon",
124            description: "Gemini 4 Argon model.",
125            fast: false,
126        },
127        /// Gemini Hydrogen model backed by `gemini-4-hydrogen`.
128        Gemini4Hydrogen = 30 => {
129            id: "gemini-4-hydrogen",
130            description: "Gemini 4 Hydrogen model with extra-high reasoning effort.",
131            fast: false,
132        },
133        /// Antigravity orchestrator backed by `gemini-pro-orchestrator-g1-pro`,
134        /// which Antigravity labels Orchestrator (Argon).
135        GeminiProOrchestrator = 31 => {
136            id: "gemini-pro-orchestrator-g1-pro",
137            description: "Orchestrator (Argon) model that coordinates subagents.",
138            fast: false,
139        },
140        /// Fast Gemini model backed by `gemini-3.8-flash`.
141        Gemini38Flash = 4 => {
142            id: "gemini-3.8-flash",
143            description: "Fast Gemini model for agentic and multimodal tasks.",
144            fast: false,
145        },
146        /// Open-weight `OpenAI` model backed by `gpt-oss-120b`.
147        GptOss120b = 32 => {
148            id: "gpt-oss-120b",
149            description: "Open-weight GPT-OSS 120B model served through Antigravity.",
150            fast: false,
151        },
152    }
153    Claude {
154        /// Claude Fable model backed by `claude-fable-5-2`.
155        ClaudeFable52 = 10 => {
156            id: "claude-fable-5-2",
157            short_name: "fable-5.2",
158            description: "Claude Fable model for creative, narrative-heavy tasks.",
159            fast: false,
160        },
161        /// Claude Opus model backed by `claude-opus-5-5`.
162        ClaudeOpus55 = 8 => {
163            id: "claude-opus-5-5",
164            short_name: "opus-5.5",
165            description: "Latest Claude Opus model for complex agentic tasks.",
166            fast: true,
167        },
168        /// Claude Sonnet model backed by `claude-sonnet-5-5`.
169        ClaudeSonnet55 = 9 => {
170            id: "claude-sonnet-5-5",
171            short_name: "sonnet-5.5",
172            description: "Balanced Claude model for quality and latency.",
173            fast: false,
174        },
175        /// Claude Haiku model backed by `claude-haiku-5-5`.
176        ClaudeHaiku55 = 11 => {
177            id: "claude-haiku-5-5",
178            short_name: "haiku-5.5",
179            description: "Fast Claude model for lighter tasks.",
180            fast: false,
181        },
182    }
183    Codex {
184        /// Codex Astra model backed by `gpt-6-astra`.
185        Gpt6Astra = 0 => {
186            id: "gpt-6-astra",
187            description: "Most capable Codex model for the hardest end-to-end work.",
188            fast: true,
189        },
190        /// Codex Sol model backed by `gpt-6.1-sol`.
191        Gpt61Sol = 1 => {
192            id: "gpt-6.1-sol",
193            description: "Near-Astra Codex model for complex work at a lower cost.",
194            fast: true,
195        },
196        /// Codex Luna model backed by `gpt-6-luna`.
197        Gpt6Luna = 2 => {
198            id: "gpt-6-luna",
199            description: "Efficient Codex model for focused, high-volume tasks.",
200            fast: true,
201        },
202        /// Codex Terra model backed by `gpt-5.6-terra`.
203        Gpt56Terra = 3 => {
204            id: "gpt-5.6-terra",
205            description: "Current Codex model for balanced coding performance.",
206            fast: true,
207        },
208        /// Codex spark model backed by `gpt-5.3-codex-spark`.
209        Gpt53CodexSpark = 7 => {
210            id: "gpt-5.3-codex-spark",
211            description: "Codex spark model for quick coding iterations.",
212            fast: false,
213        },
214    }
215    Harness {
216        /// Muse model backed by `muse-spark-1.3`.
217        MuseSpark13 = 12 => {
218            id: "muse-spark-1.3",
219            description: "Muse Spark model served through the native harness.",
220            fast: false,
221        },
222        /// Discounted Muse model backed by `muse-spark-1.3-contributor`,
223        /// whose prompts and completions Meta may use for training.
224        MuseSpark13Contributor = 19 => {
225            id: "muse-spark-1.3-contributor",
226            description: "Cheap Muse Spark tier; Meta may train on its prompts and completions.",
227            fast: false,
228        },
229        /// Kimi model backed by `kimi-k3`.
230        KimiK3 = 13 => {
231            id: "kimi-k3",
232            description: "Latest Kimi model served through the native harness.",
233            fast: false,
234        },
235        /// Kimi model backed by `kimi-k2.6`.
236        KimiK26 = 14 => {
237            id: "kimi-k2.6",
238            description: "Previous Kimi model served through the native harness.",
239            fast: false,
240        },
241        /// Qwen model backed by `qwen3.8-max`.
242        Qwen38Max = 15 => {
243            id: "qwen3.8-max",
244            description: "Most capable Qwen model served through the native harness.",
245            fast: false,
246        },
247        /// Qwen model backed by `qwen-plus`.
248        QwenPlus = 16 => {
249            id: "qwen-plus",
250            description: "Balanced Qwen model served through the native harness.",
251            fast: false,
252        },
253        /// Cheap Qwen model backed by `qwen3.8-flash`.
254        Qwen38Flash = 20 => {
255            id: "qwen3.8-flash",
256            description: "Cheap Qwen model for simple tasks such as titles and commit messages.",
257            fast: false,
258        },
259        /// Cheapest Qwen model backed by `qwen3.7-flash`.
260        Qwen37Flash = 21 => {
261            id: "qwen3.7-flash",
262            description: "Cheapest Qwen model for short, simple tasks.",
263            fast: false,
264        },
265        /// `gpt-6.1-sol` billed to the user's `ChatGPT` plan.
266        ChatGptGpt61Sol = 22 => {
267            id: "chatgpt/gpt-6.1-sol",
268            description: "GPT-6.1 Sol billed to your ChatGPT plan instead of API credits.",
269            fast: false,
270        },
271        /// `gpt-6.1-terra` billed to the user's `ChatGPT` plan.
272        ChatGptGpt61Terra = 23 => {
273            id: "chatgpt/gpt-6.1-terra",
274            description: "GPT-6.1 Terra billed to your ChatGPT plan instead of API credits.",
275            fast: false,
276        },
277        /// `gpt-6-astra` billed to the user's `ChatGPT` plan.
278        ChatGptGpt6Astra = 24 => {
279            id: "chatgpt/gpt-6-astra",
280            description: "GPT-6 Astra billed to your ChatGPT plan instead of API credits.",
281            fast: false,
282        },
283        /// `gpt-6-sol` billed to the user's `ChatGPT` plan.
284        ChatGptGpt6Sol = 25 => {
285            id: "chatgpt/gpt-6-sol",
286            description: "GPT-6 Sol billed to your ChatGPT plan instead of API credits.",
287            fast: false,
288        },
289        /// `gpt-6-luna` billed to the user's `ChatGPT` plan.
290        ChatGptGpt6Luna = 26 => {
291            id: "chatgpt/gpt-6-luna",
292            description: "GPT-6 Luna billed to your ChatGPT plan instead of API credits.",
293            fast: false,
294        },
295        /// `gpt-5.6-sol` billed to the user's `ChatGPT` plan.
296        ChatGptGpt56Sol = 27 => {
297            id: "chatgpt/gpt-5.6-sol",
298            description: "GPT-5.6 Sol billed to your ChatGPT plan instead of API credits.",
299            fast: false,
300        },
301        /// `gpt-5.6-terra` billed to the user's `ChatGPT` plan.
302        ChatGptGpt56Terra = 28 => {
303            id: "chatgpt/gpt-5.6-terra",
304            description: "GPT-5.6 Terra billed to your ChatGPT plan instead of API credits.",
305            fast: false,
306        },
307        /// `gpt-5.6-luna` billed to the user's `ChatGPT` plan.
308        ChatGptGpt56Luna = 29 => {
309            id: "chatgpt/gpt-5.6-luna",
310            description: "GPT-5.6 Luna billed to your ChatGPT plan instead of API credits.",
311            fast: false,
312        },
313    }
314}
315
316/// Models the Antigravity CLI serves, in its `agy models` display order: its
317/// own catalog models with the Claude models it shares with
318/// [`AgentKind::Claude`] placed before GPT-OSS.
319const ANTIGRAVITY_MODELS: &[AgentModel] = &[
320    AgentModel::Gemini4Neon,
321    AgentModel::Gemini4Argon,
322    AgentModel::Gemini4Hydrogen,
323    AgentModel::GeminiProOrchestrator,
324    AgentModel::Gemini38Flash,
325    AgentModel::ClaudeOpus55,
326    AgentModel::ClaudeSonnet55,
327    AgentModel::GptOss120b,
328];
329
330/// Hosted models the native harness serves, in display order: its own
331/// catalog models, then the Codex models `OpenAI`'s Responses API also
332/// serves, which the harness shares with [`AgentKind::Codex`], then the
333/// Claude models the Anthropic Messages API serves, which it shares with
334/// [`AgentKind::Claude`]. Served [`AgentModel::OpenAiCompatible`] models are
335/// discovered at runtime and listed before these.
336///
337/// ChatGPT-plan models carry a `chatgpt/` id prefix, distinct from the bare
338/// ids of the same models on the API-billed `OpenAI` provider, so choosing
339/// one never bills API credits. They precede the `OpenAI` and Claude models,
340/// which come last because `OPENAI_API_KEY` and `ANTHROPIC_API_KEY` are often
341/// set for other tools, so their mere presence must not move sessions from a
342/// deliberately configured harness provider to paid API usage. The
343/// harness library also catalogs the deprecated `gpt-5.3-codex`, which
344/// Agentty retires to [`AgentModel::Gpt61Sol`] instead of offering it. Cheap
345/// tiers follow their provider's other models, so adding one never changes
346/// which configured model a new session starts on.
347const HARNESS_MODELS: &[AgentModel] = &[
348    AgentModel::MuseSpark13,
349    AgentModel::MuseSpark13Contributor,
350    AgentModel::KimiK3,
351    AgentModel::KimiK26,
352    AgentModel::Qwen38Max,
353    AgentModel::QwenPlus,
354    AgentModel::Qwen38Flash,
355    AgentModel::Qwen37Flash,
356    AgentModel::ChatGptGpt61Sol,
357    AgentModel::ChatGptGpt61Terra,
358    AgentModel::ChatGptGpt6Astra,
359    AgentModel::ChatGptGpt6Sol,
360    AgentModel::ChatGptGpt6Luna,
361    AgentModel::ChatGptGpt56Sol,
362    AgentModel::ChatGptGpt56Terra,
363    AgentModel::ChatGptGpt56Luna,
364    AgentModel::Gpt61Sol,
365    AgentModel::Gpt6Astra,
366    AgentModel::Gpt6Luna,
367    AgentModel::Gpt56Terra,
368    AgentModel::ClaudeFable52,
369    AgentModel::ClaudeOpus55,
370    AgentModel::ClaudeSonnet55,
371    AgentModel::ClaudeHaiku55,
372];
373
374/// Id prefix of every [`AgentModel::OpenAiCompatible`] model.
375const OPENAI_COMPATIBLE_ID: &str = "openai-compatible";
376
377struct ModelDescriptor {
378    description: &'static str,
379    id: &'static str,
380    short_name: &'static str,
381    supports_fast_mode: bool,
382}
383
384/// Model an OpenAI-compatible server serves, identified as
385/// `openai-compatible/<served model>`.
386///
387/// Servers name their models at runtime, so each distinct id is interned once
388/// and kept for the process lifetime, which keeps [`AgentModel`] `Copy` and
389/// one pointer wide. A process interns only the names its servers report and
390/// its sessions store.
391#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
392pub struct ServedModel(&'static &'static str);
393
394impl ServedModel {
395    /// Model named by the host's `OPENAI_COMPATIBLE_MODEL`, stored under the
396    /// bare `openai-compatible` id.
397    pub const CONFIGURED: Self = Self(&OPENAI_COMPATIBLE_ID);
398
399    /// Returns the served model `name`, such as `qwen3:latest`, or `None`
400    /// for a blank name.
401    #[must_use]
402    pub fn new(name: &str) -> Option<Self> {
403        let name = name.trim();
404        if name.is_empty() {
405            return None;
406        }
407
408        Some(Self(intern(format!("{OPENAI_COMPATIBLE_ID}/{name}"))))
409    }
410
411    /// Returns the stable model id, such as `openai-compatible/qwen3:latest`.
412    #[must_use]
413    pub const fn id(self) -> &'static str {
414        self.0
415    }
416
417    /// Returns the name the server serves, or `None` for
418    /// [`Self::CONFIGURED`], whose name the host environment supplies.
419    #[must_use]
420    pub fn name(self) -> Option<&'static str> {
421        self.id()
422            .strip_prefix(OPENAI_COMPATIBLE_ID)?
423            .strip_prefix('/')
424    }
425
426    /// Parses an `openai-compatible` or `openai-compatible/<name>` id.
427    fn parse(id: &str) -> Option<Self> {
428        if id == OPENAI_COMPATIBLE_ID {
429            return Some(Self::CONFIGURED);
430        }
431
432        Self::new(id.strip_prefix(OPENAI_COMPATIBLE_ID)?.strip_prefix('/')?)
433    }
434}
435
436/// Returns the process-lifetime copy of `id`, leaking it on first use.
437fn intern(id: String) -> &'static &'static str {
438    static INTERNED: OnceLock<Mutex<FxHashMap<&str, &&str>>> = OnceLock::new();
439    let mut interned = INTERNED
440        .get_or_init(Mutex::default)
441        .lock()
442        .unwrap_or_else(PoisonError::into_inner);
443    if let Some(existing) = interned.get(id.as_str()) {
444        return existing;
445    }
446    let leaked: &'static &'static str = Box::leak(Box::new(&*Box::leak(id.into_boxed_str())));
447    interned.insert(leaked, leaked);
448
449    leaked
450}
451
452/// Session-level agent selection that keeps provider kind and model together.
453#[derive(Debug, Clone, Copy, PartialEq, Eq)]
454pub struct AgentSelection {
455    kind: AgentKind,
456    model: AgentModel,
457}
458
459impl AgentSelection {
460    /// Creates a coherent session agent selection.
461    ///
462    /// If `model` is not supported by `kind`, the provider's default model is
463    /// used so the selection never carries unrelated provider/model values.
464    #[must_use]
465    pub fn new(kind: AgentKind, model: AgentModel) -> Self {
466        let model = if kind.supports_model(model) {
467            model
468        } else {
469            kind.default_model()
470        };
471
472        Self { kind, model }
473    }
474
475    /// Returns the selected agent provider kind.
476    #[must_use]
477    pub fn kind(self) -> AgentKind {
478        self.kind
479    }
480
481    /// Returns the selected agent model.
482    #[must_use]
483    pub fn model(self) -> AgentModel {
484        self.model
485    }
486
487    /// Returns whether this exact provider/model pair supports Fast mode,
488    /// which needs a provider with a speed control; the harness serves Codex
489    /// models without one.
490    #[must_use]
491    pub fn supports_fast_mode(self) -> bool {
492        self.kind.supports_speed_mode() && self.model.descriptor().supports_fast_mode
493    }
494
495    /// Returns the compatible provider/model pair for one speed preference.
496    ///
497    /// Fast Claude requests require Opus, while incompatible Codex models move
498    /// to the provider's default model. Providers without a speed control and
499    /// already compatible selections remain unchanged.
500    #[must_use]
501    pub fn compatible_with_speed_mode(self, speed_mode: SpeedMode) -> Self {
502        if speed_mode == SpeedMode::Normal || self.supports_fast_mode() {
503            return self;
504        }
505
506        match self.kind {
507            AgentKind::Claude => Self::new(AgentKind::Claude, AgentModel::ClaudeOpus55),
508            AgentKind::Codex => Self::new(AgentKind::Codex, AgentKind::Codex.default_model()),
509            AgentKind::Antigravity | AgentKind::Harness => self,
510        }
511    }
512}
513
514/// Human-readable metadata for slash-menu selectable items.
515pub trait AgentSelectionMetadata {
516    /// Returns a stable item name shown in menus.
517    fn name(&self) -> &'static str;
518
519    /// Returns a short descriptive subtitle shown in menus.
520    fn description(&self) -> &'static str;
521}
522
523impl AgentModel {
524    /// Returns the stable wire/model identifier used in persistence and CLI
525    /// invocations.
526    pub const fn as_str(self) -> &'static str {
527        self.descriptor().id
528    }
529
530    /// Returns the compact name shown in dense views such as the session
531    /// list, such as `opus-5.5` for `claude-opus-5-5`.
532    ///
533    /// Models without a shorter catalog name, including
534    /// [`AgentModel::OpenAiCompatible`] models, display their menu name.
535    #[must_use]
536    pub fn short_name(self) -> &'static str {
537        match self {
538            Self::OpenAiCompatible(_) => self.name(),
539            _ => self.descriptor().short_name,
540        }
541    }
542
543    /// Returns the model identifier passed to provider transports.
544    ///
545    /// Callers route ids shared by several providers through the provider
546    /// stored on [`AgentSelection`].
547    pub fn provider_model_str(self) -> &'static str {
548        self.as_str()
549    }
550
551    /// Parses one persisted model identifier and upgrades retired ids to
552    /// their replacement models.
553    ///
554    /// Stored retired Gemini, Claude, and Codex ids are migrated forward
555    /// through [`AgentModel::retired_replacement`] so existing projects and
556    /// sessions continue loading after model retirements.
557    ///
558    /// # Errors
559    /// Returns an error when `value` is not a known current or retired model
560    /// identifier.
561    pub fn parse_persisted(value: &str) -> Result<Self, String> {
562        if let Some(replacement) = Self::retired_replacement(value) {
563            return Ok(replacement);
564        }
565
566        value.parse()
567    }
568
569    /// Returns the current replacement model for a retired persisted model
570    /// id, or `None` when `value` is not a retired id.
571    ///
572    /// This registry is the single source of truth for model retirement.
573    /// Retiring a model means removing its selectable [`AgentModel`] variant
574    /// and mapping its persisted id to the replacement model here. Retired
575    /// ids never appear in selectable model lists. Persisted selections resolve
576    /// to the replacement, and sessions that are still active are switched to
577    /// it automatically. Database migrations may also normalize saved ids.
578    #[must_use]
579    pub fn retired_replacement(value: &str) -> Option<Self> {
580        const RETIRED_MODEL_REPLACEMENTS: &[(&str, AgentModel)] = &[
581            ("gemini-3-pro-preview", AgentModel::Gemini4Argon),
582            ("gemini-3.1-pro", AgentModel::Gemini4Argon),
583            ("gemini-3.1-pro-preview", AgentModel::Gemini4Argon),
584            ("gemini-3-flash-preview", AgentModel::Gemini38Flash),
585            ("gemini-3.7-flash", AgentModel::Gemini38Flash),
586            ("gemini-3.6-flash", AgentModel::Gemini38Flash),
587            ("gemini-3.5-flash", AgentModel::Gemini38Flash),
588            ("gemini-3.5-flash-lite", AgentModel::Gemini38Flash),
589            ("gemini-3.1-flash-lite-preview", AgentModel::Gemini38Flash),
590            ("claude-fable-5", AgentModel::ClaudeFable52),
591            ("claude-fable-5-1", AgentModel::ClaudeFable52),
592            ("claude-opus-5", AgentModel::ClaudeOpus55),
593            ("claude-haiku-4-5-20251001", AgentModel::ClaudeHaiku55),
594            ("gpt-6-sol", AgentModel::Gpt61Sol),
595            ("gpt-5.6-sol", AgentModel::Gpt61Sol),
596            ("gpt-5.6-luna", AgentModel::Gpt6Luna),
597            ("claude-opus-4-8", AgentModel::ClaudeOpus55),
598            ("claude-opus-4-6", AgentModel::ClaudeOpus55),
599            ("claude-opus-4-7", AgentModel::ClaudeOpus55),
600            ("claude-sonnet-4-6", AgentModel::ClaudeSonnet55),
601            ("claude-sonnet-5", AgentModel::ClaudeSonnet55),
602            ("gpt-5.5", AgentModel::Gpt61Sol),
603            ("gpt-5.4-mini", AgentModel::Gpt6Luna),
604            ("gpt-5.4", AgentModel::Gpt61Sol),
605            ("gpt-5.3-codex", AgentModel::Gpt61Sol),
606            ("gpt-5.2-codex", AgentModel::Gpt53CodexSpark),
607        ];
608
609        RETIRED_MODEL_REPLACEMENTS
610            .iter()
611            .find(|(retired_id, _)| *retired_id == value)
612            .map(|(_, replacement)| *replacement)
613    }
614}
615
616/// Parses one persisted session agent/model pair without deriving the agent
617/// from the model when the saved agent kind is available.
618///
619/// Existing databases did not persist `agent`, so rows with a missing or
620/// invalid agent value fall back to a compatibility provider inferred from
621/// the persisted model string. Raw `gemini-*` rows belong to Antigravity,
622/// the only provider serving those models.
623pub fn parse_persisted_session_agent_model(
624    agent_value: Option<&str>,
625    model_value: &str,
626) -> AgentSelection {
627    let parsed_agent = agent_value
628        .filter(|value| !value.trim().is_empty())
629        .and_then(|value| value.parse::<AgentKind>().ok());
630
631    if let Some(agent_kind) = parsed_agent {
632        return parse_model_for_persisted_agent(agent_kind, model_value);
633    }
634
635    let model = AgentModel::parse_persisted(model_value)
636        .unwrap_or_else(|_| AgentKind::Antigravity.default_model());
637    let agent_kind = legacy_agent_kind_for_model_value(model_value, model);
638
639    AgentSelection::new(agent_kind, model)
640}
641
642/// Parses a persisted model using the already persisted agent kind as the
643/// source of truth for provider ownership.
644fn parse_model_for_persisted_agent(agent_kind: AgentKind, model_value: &str) -> AgentSelection {
645    if let Some(model) = agent_kind.parse_model(model_value) {
646        return AgentSelection::new(agent_kind, model);
647    }
648
649    if let Ok(model) = AgentModel::parse_persisted(model_value)
650        && agent_kind.supports_model(model)
651    {
652        return AgentSelection::new(agent_kind, model);
653    }
654
655    AgentSelection::new(agent_kind, agent_kind.default_model())
656}
657
658/// Returns the provider used for legacy rows that predate explicit session
659/// agent persistence.
660///
661/// Current ids belong to their owning provider; retired and unknown ids fall
662/// back to the provider their id prefix names.
663fn legacy_agent_kind_for_model_value(model_value: &str, model: AgentModel) -> AgentKind {
664    if model.as_str() == model_value {
665        return model.owner_kind();
666    }
667
668    if model_value.starts_with("claude-") {
669        return AgentKind::Claude;
670    }
671
672    if model_value.starts_with("gpt-") {
673        return AgentKind::Codex;
674    }
675
676    if model_value.starts_with("gemini-") {
677        return AgentKind::Antigravity;
678    }
679
680    model.owner_kind()
681}
682
683/// Resolves one model against the currently available agent kinds.
684///
685/// When `model` is unsupported by every available provider, this prefers
686/// `fallback_model` when any available provider supports it and otherwise falls
687/// back to the first available provider default in `agent_kinds`. When no
688/// providers are available, it returns `fallback_model` unchanged.
689#[must_use]
690pub fn resolve_model_for_available_agent_kinds(
691    model: AgentModel,
692    agent_kinds: &[AgentKind],
693    fallback_model: AgentModel,
694) -> AgentModel {
695    if agent_kinds
696        .iter()
697        .any(|agent_kind| agent_kind.supports_model(model))
698    {
699        return model;
700    }
701
702    if agent_kinds
703        .iter()
704        .any(|agent_kind| agent_kind.supports_model(fallback_model))
705    {
706        return fallback_model;
707    }
708
709    agent_kinds
710        .first()
711        .copied()
712        .map_or(fallback_model, AgentKind::default_model)
713}
714
715/// Resolves a provider kind that can run `model` from the available provider
716/// list.
717///
718/// Shared model ids, such as the Codex models the harness also serves, can be
719/// run by several providers. This helper prefers the model's
720/// [`AgentModel::owner_kind`] when it is available, then uses the order of
721/// `agent_kinds` as the tie-breaker, and returns `fallback_agent_kind` when no
722/// available provider supports `model`.
723#[must_use]
724pub fn resolve_agent_kind_for_model(
725    model: AgentModel,
726    agent_kinds: &[AgentKind],
727    fallback_agent_kind: AgentKind,
728) -> AgentKind {
729    let owner_kind = model.owner_kind();
730    if agent_kinds.contains(&owner_kind) {
731        return owner_kind;
732    }
733
734    agent_kinds
735        .iter()
736        .copied()
737        .find(|agent_kind| agent_kind.supports_model(model))
738        .unwrap_or(fallback_agent_kind)
739}
740
741/// Resolves an [`AgentSelection`] for a model-only setting.
742///
743/// `preferred_agent_kind` is kept when it can run `model`, which preserves the
744/// current session provider for shared model ids. Otherwise the
745/// available provider order decides the owning provider, falling back to
746/// `preferred_agent_kind` when no available provider supports the model.
747#[must_use]
748pub fn resolve_agent_selection_for_model(
749    model: AgentModel,
750    preferred_agent_kind: AgentKind,
751    agent_kinds: &[AgentKind],
752) -> AgentSelection {
753    let agent_kind = if preferred_agent_kind.supports_model(model) {
754        preferred_agent_kind
755    } else {
756        resolve_agent_kind_for_model(model, agent_kinds, preferred_agent_kind)
757    };
758
759    AgentSelection::new(agent_kind, model)
760}
761
762/// Resolves the agent kind used for prompt-side `/model` selection.
763///
764/// This preserves `session_agent_kind` when that backend is still available
765/// and otherwise falls back to the first available backend. When no backends
766/// are available, it returns `None`.
767#[must_use]
768pub fn resolve_prompt_model_agent_kind(
769    session_agent_kind: AgentKind,
770    agent_kinds: &[AgentKind],
771) -> Option<AgentKind> {
772    if agent_kinds.contains(&session_agent_kind) {
773        return Some(session_agent_kind);
774    }
775
776    agent_kinds.first().copied()
777}
778
779impl FromStr for AgentModel {
780    type Err = String;
781
782    fn from_str(value: &str) -> Result<Self, Self::Err> {
783        Self::ALL
784            .iter()
785            .copied()
786            .find(|model| model.as_str() == value)
787            .or_else(|| ServedModel::parse(value).map(Self::OpenAiCompatible))
788            .ok_or_else(|| format!("unknown model: {value}"))
789    }
790}
791
792impl AgentSelectionMetadata for AgentModel {
793    /// Returns the model id, or the bare served name of an
794    /// [`AgentModel::OpenAiCompatible`] model, such as `qwen3:latest`.
795    fn name(&self) -> &'static str {
796        match self {
797            Self::OpenAiCompatible(served) => served.name().unwrap_or(served.id()),
798            _ => (*self).provider_model_str(),
799        }
800    }
801
802    fn description(&self) -> &'static str {
803        self.descriptor().description
804    }
805}
806
807impl AgentKind {
808    /// All CLI-backed agent kinds, in display order.
809    ///
810    /// [`AgentKind::Harness`] runs in process, so it is never discovered from
811    /// `PATH` and stays out of this list.
812    pub const ALL: &[AgentKind] = &[AgentKind::Antigravity, AgentKind::Claude, AgentKind::Codex];
813
814    /// Returns the provider CLI executable name, or `None` for the in-process
815    /// harness.
816    pub fn executable_name(self) -> Option<&'static str> {
817        match self {
818            Self::Antigravity => Some("agy"),
819            Self::Claude => Some("claude"),
820            Self::Codex => Some("codex"),
821            Self::Harness => None,
822        }
823    }
824
825    /// Returns this provider's models in their catalog display order.
826    ///
827    /// Antigravity also serves Claude Opus and Sonnet, and the harness serves
828    /// the Codex models available through `OpenAI`'s Responses API and the
829    /// Claude models available through the Anthropic Messages API, beside
830    /// their own.
831    pub fn models(self) -> &'static [AgentModel] {
832        match self {
833            Self::Antigravity => ANTIGRAVITY_MODELS,
834            Self::Harness => HARNESS_MODELS,
835            Self::Claude | Self::Codex => self.declared_models(),
836        }
837    }
838
839    /// Returns the default model for this agent kind.
840    pub fn default_model(self) -> AgentModel {
841        match self {
842            Self::Antigravity => AgentModel::Gemini4Neon,
843            Self::Claude => AgentModel::ClaudeFable52,
844            Self::Codex => AgentModel::Gpt61Sol,
845            Self::Harness => AgentModel::MuseSpark13,
846        }
847    }
848
849    /// Parses a provider-specific model string for this agent kind.
850    pub fn parse_model(self, value: &str) -> Option<AgentModel> {
851        let model = value.parse::<AgentModel>().ok()?;
852        if !self.supports_model(model) {
853            return None;
854        }
855
856        Some(model)
857    }
858
859    /// Returns whether this provider can run the given model. Only
860    /// [`AgentKind::Harness`] runs served [`AgentModel::OpenAiCompatible`]
861    /// models.
862    pub fn supports_model(self, model: AgentModel) -> bool {
863        match model {
864            AgentModel::OpenAiCompatible(_) => self == Self::Harness,
865            _ => self.models().contains(&model),
866        }
867    }
868
869    /// Returns whether this provider exposes a response-speed control.
870    ///
871    /// Claude and Codex accept a per-turn speed selection, so `/speed` offers
872    /// the picker and session surfaces display the active [`SpeedMode`].
873    /// Antigravity has no equivalent control, so neither the command nor the
874    /// speed display is offered for it.
875    ///
876    /// [`SpeedMode`]: ag_contracts::SpeedMode
877    pub fn supports_speed_mode(self) -> bool {
878        matches!(self, Self::Claude | Self::Codex)
879    }
880}
881
882impl AgentSelectionMetadata for AgentKind {
883    fn name(&self) -> &'static str {
884        match self {
885            Self::Antigravity => "antigravity",
886            Self::Claude => "claude",
887            Self::Codex => "codex",
888            Self::Harness => "harness",
889        }
890    }
891
892    fn description(&self) -> &'static str {
893        match self {
894            Self::Antigravity => "Google Antigravity CLI agent.",
895            Self::Claude => "Anthropic Claude Code agent.",
896            Self::Codex => "OpenAI Codex CLI agent.",
897            Self::Harness => "Native Agentty harness agent.",
898        }
899    }
900}
901
902impl AgentSelectionMetadata for ReasoningLevel {
903    fn name(&self) -> &'static str {
904        (*self).as_str()
905    }
906
907    fn description(&self) -> &'static str {
908        (*self).description()
909    }
910}
911
912impl fmt::Display for AgentKind {
913    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
914        write!(f, "{}", self.name())
915    }
916}
917
918/// Parses a provider name.
919///
920/// The retired `gemini` provider name parses as [`AgentKind::Antigravity`],
921/// which serves the same models, so saved settings and graph snapshots from
922/// the removed Gemini CLI backend keep loading.
923impl FromStr for AgentKind {
924    type Err = String;
925
926    fn from_str(s: &str) -> Result<Self, Self::Err> {
927        match s.to_lowercase().as_str() {
928            "antigravity" | "agy" | "gemini" => Ok(Self::Antigravity),
929            "claude" => Ok(Self::Claude),
930            "codex" => Ok(Self::Codex),
931            "harness" => Ok(Self::Harness),
932            other => Err(format!("unknown agent kind: {other}")),
933        }
934    }
935}
936
937#[cfg(test)]
938#[path = "agent_test.rs"]
939mod tests;