Skip to main content

ag_session/
agent.rs

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