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. The standard-priced
347/// `claude-sonnet-5-5` leads the Claude models, so an Anthropic key that
348/// leaves it the first ready model starts sessions on it rather than on a
349/// premium one. A shared model keeps the provider its selection stores, so
350/// a Claude or Codex CLI selection never moves to the harness, nor the
351/// reverse.
352const HARNESS_MODELS: &[AgentModel] = &[
353    AgentModel::MuseSpark13,
354    AgentModel::MuseSpark13Contributor,
355    AgentModel::KimiK3,
356    AgentModel::KimiK26,
357    AgentModel::Qwen38Max,
358    AgentModel::QwenPlus,
359    AgentModel::Qwen38Flash,
360    AgentModel::Qwen37Flash,
361    AgentModel::ChatGptGpt61Sol,
362    AgentModel::ChatGptGpt61Terra,
363    AgentModel::ChatGptGpt6Astra,
364    AgentModel::ChatGptGpt6Sol,
365    AgentModel::ChatGptGpt6Luna,
366    AgentModel::ChatGptGpt56Sol,
367    AgentModel::ChatGptGpt56Terra,
368    AgentModel::ChatGptGpt56Luna,
369    AgentModel::Gpt61Sol,
370    AgentModel::Gpt6Astra,
371    AgentModel::Gpt6Luna,
372    AgentModel::Gpt56Terra,
373    AgentModel::ClaudeSonnet55,
374    AgentModel::ClaudeOpus55,
375    AgentModel::ClaudeFable52,
376    AgentModel::ClaudeHaiku55,
377];
378
379/// Id prefix of every [`AgentModel::OpenAiCompatible`] model.
380const OPENAI_COMPATIBLE_ID: &str = "openai-compatible";
381
382struct ModelDescriptor {
383    description: &'static str,
384    id: &'static str,
385    short_name: &'static str,
386    supports_fast_mode: bool,
387}
388
389/// Model an OpenAI-compatible server serves, identified as
390/// `openai-compatible/<served model>`.
391///
392/// Servers name their models at runtime, so each distinct id is interned once
393/// and kept for the process lifetime, which keeps [`AgentModel`] `Copy` and
394/// one pointer wide. A process interns only the names its servers report and
395/// its sessions store.
396#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
397pub struct ServedModel(&'static &'static str);
398
399impl ServedModel {
400    /// Model named by the host's `OPENAI_COMPATIBLE_MODEL`, stored under the
401    /// bare `openai-compatible` id.
402    pub const CONFIGURED: Self = Self(&OPENAI_COMPATIBLE_ID);
403
404    /// Returns the served model `name`, such as `qwen3:latest`, or `None`
405    /// for a blank name.
406    #[must_use]
407    pub fn new(name: &str) -> Option<Self> {
408        let name = name.trim();
409        if name.is_empty() {
410            return None;
411        }
412
413        Some(Self(intern(format!("{OPENAI_COMPATIBLE_ID}/{name}"))))
414    }
415
416    /// Returns the stable model id, such as `openai-compatible/qwen3:latest`.
417    #[must_use]
418    pub const fn id(self) -> &'static str {
419        self.0
420    }
421
422    /// Returns the name the server serves, or `None` for
423    /// [`Self::CONFIGURED`], whose name the host environment supplies.
424    #[must_use]
425    pub fn name(self) -> Option<&'static str> {
426        self.id()
427            .strip_prefix(OPENAI_COMPATIBLE_ID)?
428            .strip_prefix('/')
429    }
430
431    /// Parses an `openai-compatible` or `openai-compatible/<name>` id.
432    fn parse(id: &str) -> Option<Self> {
433        if id == OPENAI_COMPATIBLE_ID {
434            return Some(Self::CONFIGURED);
435        }
436
437        Self::new(id.strip_prefix(OPENAI_COMPATIBLE_ID)?.strip_prefix('/')?)
438    }
439}
440
441/// Returns the process-lifetime copy of `id`, leaking it on first use.
442fn intern(id: String) -> &'static &'static str {
443    static INTERNED: OnceLock<Mutex<FxHashMap<&str, &&str>>> = OnceLock::new();
444    let mut interned = INTERNED
445        .get_or_init(Mutex::default)
446        .lock()
447        .unwrap_or_else(PoisonError::into_inner);
448    if let Some(existing) = interned.get(id.as_str()) {
449        return existing;
450    }
451    let leaked: &'static &'static str = Box::leak(Box::new(&*Box::leak(id.into_boxed_str())));
452    interned.insert(leaked, leaked);
453
454    leaked
455}
456
457/// Session-level agent selection that keeps provider kind and model together.
458#[derive(Debug, Clone, Copy, PartialEq, Eq)]
459pub struct AgentSelection {
460    kind: AgentKind,
461    model: AgentModel,
462}
463
464impl AgentSelection {
465    /// Creates a coherent session agent selection.
466    ///
467    /// If `model` is not supported by `kind`, the provider's default model is
468    /// used so the selection never carries unrelated provider/model values.
469    #[must_use]
470    pub fn new(kind: AgentKind, model: AgentModel) -> Self {
471        let model = if kind.supports_model(model) {
472            model
473        } else {
474            kind.default_model()
475        };
476
477        Self { kind, model }
478    }
479
480    /// Returns the selected agent provider kind.
481    #[must_use]
482    pub fn kind(self) -> AgentKind {
483        self.kind
484    }
485
486    /// Returns the selected agent model.
487    #[must_use]
488    pub fn model(self) -> AgentModel {
489        self.model
490    }
491
492    /// Returns whether this exact provider/model pair supports Fast mode,
493    /// which needs a provider with a speed control; the harness serves Codex
494    /// models without one.
495    #[must_use]
496    pub fn supports_fast_mode(self) -> bool {
497        self.kind.supports_speed_mode() && self.model.descriptor().supports_fast_mode
498    }
499
500    /// Returns the compatible provider/model pair for one speed preference.
501    ///
502    /// Fast Claude requests require Opus, while incompatible Codex models move
503    /// to the provider's default model. Providers without a speed control and
504    /// already compatible selections remain unchanged.
505    #[must_use]
506    pub fn compatible_with_speed_mode(self, speed_mode: SpeedMode) -> Self {
507        if speed_mode == SpeedMode::Normal || self.supports_fast_mode() {
508            return self;
509        }
510
511        match self.kind {
512            AgentKind::Claude => Self::new(AgentKind::Claude, AgentModel::ClaudeOpus55),
513            AgentKind::Codex => Self::new(AgentKind::Codex, AgentKind::Codex.default_model()),
514            AgentKind::Antigravity | AgentKind::Harness => self,
515        }
516    }
517}
518
519/// Human-readable metadata for slash-menu selectable items.
520pub trait AgentSelectionMetadata {
521    /// Returns a stable item name shown in menus.
522    fn name(&self) -> &'static str;
523
524    /// Returns a short descriptive subtitle shown in menus.
525    fn description(&self) -> &'static str;
526}
527
528impl AgentModel {
529    /// Returns the stable wire/model identifier used in persistence and CLI
530    /// invocations.
531    pub const fn as_str(self) -> &'static str {
532        self.descriptor().id
533    }
534
535    /// Returns the compact name shown in dense views such as the session
536    /// list, such as `opus-5.5` for `claude-opus-5-5`.
537    ///
538    /// Models without a shorter catalog name, including
539    /// [`AgentModel::OpenAiCompatible`] models, display their menu name.
540    #[must_use]
541    pub fn short_name(self) -> &'static str {
542        match self {
543            Self::OpenAiCompatible(_) => self.name(),
544            _ => self.descriptor().short_name,
545        }
546    }
547
548    /// Returns the model identifier passed to provider transports.
549    ///
550    /// Callers route ids shared by several providers through the provider
551    /// stored on [`AgentSelection`].
552    pub fn provider_model_str(self) -> &'static str {
553        self.as_str()
554    }
555
556    /// Parses one persisted model identifier and upgrades retired ids to
557    /// their replacement models.
558    ///
559    /// Stored retired Gemini, Claude, and Codex ids are migrated forward
560    /// through [`AgentModel::retired_replacement`] so existing projects and
561    /// sessions continue loading after model retirements.
562    ///
563    /// # Errors
564    /// Returns an error when `value` is not a known current or retired model
565    /// identifier.
566    pub fn parse_persisted(value: &str) -> Result<Self, String> {
567        if let Some(replacement) = Self::retired_replacement(value) {
568            return Ok(replacement);
569        }
570
571        value.parse()
572    }
573
574    /// Returns the current replacement model for a retired persisted model
575    /// id, or `None` when `value` is not a retired id.
576    ///
577    /// This registry is the single source of truth for model retirement.
578    /// Retiring a model means removing its selectable [`AgentModel`] variant
579    /// and mapping its persisted id to the replacement model here. Retired
580    /// ids never appear in selectable model lists. Persisted selections resolve
581    /// to the replacement, and sessions that are still active are switched to
582    /// it automatically. Database migrations may also normalize saved ids.
583    #[must_use]
584    pub fn retired_replacement(value: &str) -> Option<Self> {
585        const RETIRED_MODEL_REPLACEMENTS: &[(&str, AgentModel)] = &[
586            ("gemini-3-pro-preview", AgentModel::Gemini4Argon),
587            ("gemini-3.1-pro", AgentModel::Gemini4Argon),
588            ("gemini-3.1-pro-preview", AgentModel::Gemini4Argon),
589            ("gemini-3-flash-preview", AgentModel::Gemini38Flash),
590            ("gemini-3.7-flash", AgentModel::Gemini38Flash),
591            ("gemini-3.6-flash", AgentModel::Gemini38Flash),
592            ("gemini-3.5-flash", AgentModel::Gemini38Flash),
593            ("gemini-3.5-flash-lite", AgentModel::Gemini38Flash),
594            ("gemini-3.1-flash-lite-preview", AgentModel::Gemini38Flash),
595            ("claude-fable-5", AgentModel::ClaudeFable52),
596            ("claude-fable-5-1", AgentModel::ClaudeFable52),
597            ("claude-opus-5", AgentModel::ClaudeOpus55),
598            ("claude-haiku-4-5-20251001", AgentModel::ClaudeHaiku55),
599            ("gpt-6-sol", AgentModel::Gpt61Sol),
600            ("gpt-5.6-sol", AgentModel::Gpt61Sol),
601            ("gpt-5.6-luna", AgentModel::Gpt6Luna),
602            ("claude-opus-4-8", AgentModel::ClaudeOpus55),
603            ("claude-opus-4-6", AgentModel::ClaudeOpus55),
604            ("claude-opus-4-7", AgentModel::ClaudeOpus55),
605            ("claude-sonnet-4-6", AgentModel::ClaudeSonnet55),
606            ("claude-sonnet-5", AgentModel::ClaudeSonnet55),
607            ("gpt-5.5", AgentModel::Gpt61Sol),
608            ("gpt-5.4-mini", AgentModel::Gpt6Luna),
609            ("gpt-5.4", AgentModel::Gpt61Sol),
610            ("gpt-5.3-codex", AgentModel::Gpt61Sol),
611            ("gpt-5.2-codex", AgentModel::Gpt53CodexSpark),
612        ];
613
614        RETIRED_MODEL_REPLACEMENTS
615            .iter()
616            .find(|(retired_id, _)| *retired_id == value)
617            .map(|(_, replacement)| *replacement)
618    }
619}
620
621/// Parses one persisted session agent/model pair without deriving the agent
622/// from the model when the saved agent kind is available.
623///
624/// Existing databases did not persist `agent`, so rows with a missing or
625/// invalid agent value fall back to a compatibility provider inferred from
626/// the persisted model string. Raw `gemini-*` rows belong to Antigravity,
627/// the only provider serving those models.
628pub fn parse_persisted_session_agent_model(
629    agent_value: Option<&str>,
630    model_value: &str,
631) -> AgentSelection {
632    let parsed_agent = agent_value
633        .filter(|value| !value.trim().is_empty())
634        .and_then(|value| value.parse::<AgentKind>().ok());
635
636    if let Some(agent_kind) = parsed_agent {
637        return parse_model_for_persisted_agent(agent_kind, model_value);
638    }
639
640    let model = AgentModel::parse_persisted(model_value)
641        .unwrap_or_else(|_| AgentKind::Antigravity.default_model());
642    let agent_kind = legacy_agent_kind_for_model_value(model_value, model);
643
644    AgentSelection::new(agent_kind, model)
645}
646
647/// Parses a persisted model using the already persisted agent kind as the
648/// source of truth for provider ownership.
649fn parse_model_for_persisted_agent(agent_kind: AgentKind, model_value: &str) -> AgentSelection {
650    if let Some(model) = agent_kind.parse_model(model_value) {
651        return AgentSelection::new(agent_kind, model);
652    }
653
654    if let Ok(model) = AgentModel::parse_persisted(model_value)
655        && agent_kind.supports_model(model)
656    {
657        return AgentSelection::new(agent_kind, model);
658    }
659
660    AgentSelection::new(agent_kind, agent_kind.default_model())
661}
662
663/// Returns the provider used for legacy rows that predate explicit session
664/// agent persistence.
665///
666/// Current ids belong to their owning provider; retired and unknown ids fall
667/// back to the provider their id prefix names.
668fn legacy_agent_kind_for_model_value(model_value: &str, model: AgentModel) -> AgentKind {
669    if model.as_str() == model_value {
670        return model.owner_kind();
671    }
672
673    if model_value.starts_with("claude-") {
674        return AgentKind::Claude;
675    }
676
677    if model_value.starts_with("gpt-") {
678        return AgentKind::Codex;
679    }
680
681    if model_value.starts_with("gemini-") {
682        return AgentKind::Antigravity;
683    }
684
685    model.owner_kind()
686}
687
688/// Resolves one model against the currently available agent kinds.
689///
690/// When `model` is unsupported by every available provider, this prefers
691/// `fallback_model` when any available provider supports it and otherwise falls
692/// back to the first available provider default in `agent_kinds`. When no
693/// providers are available, it returns `fallback_model` unchanged.
694#[must_use]
695pub fn resolve_model_for_available_agent_kinds(
696    model: AgentModel,
697    agent_kinds: &[AgentKind],
698    fallback_model: AgentModel,
699) -> AgentModel {
700    if agent_kinds
701        .iter()
702        .any(|agent_kind| agent_kind.supports_model(model))
703    {
704        return model;
705    }
706
707    if agent_kinds
708        .iter()
709        .any(|agent_kind| agent_kind.supports_model(fallback_model))
710    {
711        return fallback_model;
712    }
713
714    agent_kinds
715        .first()
716        .copied()
717        .map_or(fallback_model, AgentKind::default_model)
718}
719
720/// Resolves a provider kind that can run `model` from the available provider
721/// list.
722///
723/// Shared model ids, such as the Codex models the harness also serves, can be
724/// run by several providers. This helper prefers the model's
725/// [`AgentModel::owner_kind`] when it is available, then uses the order of
726/// `agent_kinds` as the tie-breaker, and returns `fallback_agent_kind` when no
727/// available provider supports `model`.
728#[must_use]
729pub fn resolve_agent_kind_for_model(
730    model: AgentModel,
731    agent_kinds: &[AgentKind],
732    fallback_agent_kind: AgentKind,
733) -> AgentKind {
734    let owner_kind = model.owner_kind();
735    if agent_kinds.contains(&owner_kind) {
736        return owner_kind;
737    }
738
739    agent_kinds
740        .iter()
741        .copied()
742        .find(|agent_kind| agent_kind.supports_model(model))
743        .unwrap_or(fallback_agent_kind)
744}
745
746/// Resolves an [`AgentSelection`] for a model-only setting.
747///
748/// `preferred_agent_kind` is kept when it can run `model`, which preserves the
749/// current session provider for shared model ids. Otherwise the
750/// available provider order decides the owning provider, falling back to
751/// `preferred_agent_kind` when no available provider supports the model.
752#[must_use]
753pub fn resolve_agent_selection_for_model(
754    model: AgentModel,
755    preferred_agent_kind: AgentKind,
756    agent_kinds: &[AgentKind],
757) -> AgentSelection {
758    let agent_kind = if preferred_agent_kind.supports_model(model) {
759        preferred_agent_kind
760    } else {
761        resolve_agent_kind_for_model(model, agent_kinds, preferred_agent_kind)
762    };
763
764    AgentSelection::new(agent_kind, model)
765}
766
767/// Resolves the agent kind used for prompt-side `/model` selection.
768///
769/// This preserves `session_agent_kind` when that backend is still available
770/// and otherwise falls back to the first available backend. When no backends
771/// are available, it returns `None`.
772#[must_use]
773pub fn resolve_prompt_model_agent_kind(
774    session_agent_kind: AgentKind,
775    agent_kinds: &[AgentKind],
776) -> Option<AgentKind> {
777    if agent_kinds.contains(&session_agent_kind) {
778        return Some(session_agent_kind);
779    }
780
781    agent_kinds.first().copied()
782}
783
784impl FromStr for AgentModel {
785    type Err = String;
786
787    fn from_str(value: &str) -> Result<Self, Self::Err> {
788        Self::ALL
789            .iter()
790            .copied()
791            .find(|model| model.as_str() == value)
792            .or_else(|| ServedModel::parse(value).map(Self::OpenAiCompatible))
793            .ok_or_else(|| format!("unknown model: {value}"))
794    }
795}
796
797impl AgentSelectionMetadata for AgentModel {
798    /// Returns the model id, or the bare served name of an
799    /// [`AgentModel::OpenAiCompatible`] model, such as `qwen3:latest`.
800    fn name(&self) -> &'static str {
801        match self {
802            Self::OpenAiCompatible(served) => served.name().unwrap_or(served.id()),
803            _ => (*self).provider_model_str(),
804        }
805    }
806
807    fn description(&self) -> &'static str {
808        self.descriptor().description
809    }
810}
811
812impl AgentKind {
813    /// All CLI-backed agent kinds, in display order.
814    ///
815    /// [`AgentKind::Harness`] runs in process, so it is never discovered from
816    /// `PATH` and stays out of this list.
817    pub const ALL: &[AgentKind] = &[AgentKind::Antigravity, AgentKind::Claude, AgentKind::Codex];
818
819    /// Returns the provider CLI executable name, or `None` for the in-process
820    /// harness.
821    pub fn executable_name(self) -> Option<&'static str> {
822        match self {
823            Self::Antigravity => Some("agy"),
824            Self::Claude => Some("claude"),
825            Self::Codex => Some("codex"),
826            Self::Harness => None,
827        }
828    }
829
830    /// Returns this provider's models in their catalog display order.
831    ///
832    /// Antigravity also serves Claude Opus and Sonnet, and the harness serves
833    /// the Codex models available through `OpenAI`'s Responses API and the
834    /// Claude models available through the Anthropic Messages API, beside
835    /// their own.
836    pub fn models(self) -> &'static [AgentModel] {
837        match self {
838            Self::Antigravity => ANTIGRAVITY_MODELS,
839            Self::Harness => HARNESS_MODELS,
840            Self::Claude | Self::Codex => self.declared_models(),
841        }
842    }
843
844    /// Returns the default model for this agent kind.
845    pub fn default_model(self) -> AgentModel {
846        match self {
847            Self::Antigravity => AgentModel::Gemini4Neon,
848            Self::Claude => AgentModel::ClaudeFable52,
849            Self::Codex => AgentModel::Gpt61Sol,
850            Self::Harness => AgentModel::MuseSpark13,
851        }
852    }
853
854    /// Parses a provider-specific model string for this agent kind.
855    pub fn parse_model(self, value: &str) -> Option<AgentModel> {
856        let model = value.parse::<AgentModel>().ok()?;
857        if !self.supports_model(model) {
858            return None;
859        }
860
861        Some(model)
862    }
863
864    /// Returns whether this provider can run the given model. Only
865    /// [`AgentKind::Harness`] runs served [`AgentModel::OpenAiCompatible`]
866    /// models.
867    pub fn supports_model(self, model: AgentModel) -> bool {
868        match model {
869            AgentModel::OpenAiCompatible(_) => self == Self::Harness,
870            _ => self.models().contains(&model),
871        }
872    }
873
874    /// Returns whether this provider exposes a response-speed control.
875    ///
876    /// Claude and Codex accept a per-turn speed selection, so `/speed` offers
877    /// the picker and session surfaces display the active [`SpeedMode`].
878    /// Antigravity has no equivalent control, so neither the command nor the
879    /// speed display is offered for it.
880    ///
881    /// [`SpeedMode`]: ag_contracts::SpeedMode
882    pub fn supports_speed_mode(self) -> bool {
883        matches!(self, Self::Claude | Self::Codex)
884    }
885}
886
887impl AgentSelectionMetadata for AgentKind {
888    fn name(&self) -> &'static str {
889        match self {
890            Self::Antigravity => "antigravity",
891            Self::Claude => "claude",
892            Self::Codex => "codex",
893            Self::Harness => "harness",
894        }
895    }
896
897    fn description(&self) -> &'static str {
898        match self {
899            Self::Antigravity => "Google Antigravity CLI agent.",
900            Self::Claude => "Anthropic Claude Code agent.",
901            Self::Codex => "OpenAI Codex CLI agent.",
902            Self::Harness => "Native Agentty harness agent.",
903        }
904    }
905}
906
907impl AgentSelectionMetadata for ReasoningLevel {
908    fn name(&self) -> &'static str {
909        (*self).as_str()
910    }
911
912    fn description(&self) -> &'static str {
913        (*self).description()
914    }
915}
916
917impl fmt::Display for AgentKind {
918    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
919        write!(f, "{}", self.name())
920    }
921}
922
923/// Parses a provider name.
924///
925/// The retired `gemini` provider name parses as [`AgentKind::Antigravity`],
926/// which serves the same models, so saved settings and graph snapshots from
927/// the removed Gemini CLI backend keep loading.
928impl FromStr for AgentKind {
929    type Err = String;
930
931    fn from_str(s: &str) -> Result<Self, Self::Err> {
932        match s.to_lowercase().as_str() {
933            "antigravity" | "agy" | "gemini" => Ok(Self::Antigravity),
934            "claude" => Ok(Self::Claude),
935            "codex" => Ok(Self::Codex),
936            "harness" => Ok(Self::Harness),
937            other => Err(format!("unknown agent kind: {other}")),
938        }
939    }
940}
941
942#[cfg(test)]
943#[path = "agent_test.rs"]
944mod tests;