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