Skip to main content

ag_session/
agent.rs

1use std::fmt;
2use std::str::FromStr;
3
4use ag_runtime::{ReasoningLevel, SpeedMode};
5
6/// Supported agent provider families.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum AgentKind {
9    /// Google Antigravity CLI/backend.
10    Antigravity,
11    /// Google Gemini CLI/backend.
12    Gemini,
13    /// Anthropic Claude Code CLI/backend.
14    Claude,
15    /// `OpenAI` Codex CLI/backend.
16    Codex,
17}
18
19/// Supported agent model names across all providers.
20///
21/// Gemini model ids are shared by the direct Gemini and Antigravity providers,
22/// so provider ownership lives on [`AgentSelection`] rather than on these
23/// variants.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum AgentModel {
26    /// Codex Astra model backed by `gpt-6-astra`.
27    Gpt6Astra,
28    /// Codex Sol model backed by `gpt-5.6-sol`.
29    Gpt56Sol,
30    /// Codex Terra model backed by `gpt-5.6-terra`.
31    Gpt56Terra,
32    /// Codex Luna model backed by `gpt-5.6-luna`.
33    Gpt56Luna,
34    /// Fast Gemini model backed by `gemini-3.8-flash`.
35    Gemini38Flash,
36    /// Lightweight Gemini model backed by `gemini-3.5-flash-lite`.
37    Gemini35FlashLite,
38    /// Higher-quality Gemini preview model backed by `gemini-3.1-pro-preview`.
39    Gemini31Pro,
40    /// Codex spark model backed by `gpt-5.3-codex-spark`.
41    Gpt53CodexSpark,
42    /// Claude Opus model backed by `claude-opus-5`.
43    ClaudeOpus5,
44    /// Claude Sonnet model backed by `claude-sonnet-5`.
45    ClaudeSonnet5,
46    /// Claude Fable model backed by `claude-fable-5`.
47    ClaudeFable5,
48    /// Claude Haiku model backed by `claude-haiku-4-5-20251001`.
49    ClaudeHaiku4520251001,
50}
51
52/// Session-level agent selection that keeps provider kind and model together.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct AgentSelection {
55    kind: AgentKind,
56    model: AgentModel,
57}
58
59impl AgentSelection {
60    /// Creates a coherent session agent selection.
61    ///
62    /// If `model` is not supported by `kind`, the provider's default model is
63    /// used so the selection never carries unrelated provider/model values.
64    #[must_use]
65    pub fn new(kind: AgentKind, model: AgentModel) -> Self {
66        let model = if kind.supports_model(model) {
67            model
68        } else {
69            kind.default_model()
70        };
71
72        Self { kind, model }
73    }
74
75    /// Returns the selected agent provider kind.
76    #[must_use]
77    pub fn kind(self) -> AgentKind {
78        self.kind
79    }
80
81    /// Returns the selected agent model.
82    #[must_use]
83    pub fn model(self) -> AgentModel {
84        self.model
85    }
86
87    /// Returns whether this exact provider/model pair supports Fast mode.
88    #[must_use]
89    pub fn supports_fast_mode(self) -> bool {
90        matches!(
91            (self.kind, self.model),
92            (AgentKind::Claude, AgentModel::ClaudeOpus5)
93                | (
94                    AgentKind::Codex,
95                    AgentModel::Gpt6Astra
96                        | AgentModel::Gpt56Sol
97                        | AgentModel::Gpt56Terra
98                        | AgentModel::Gpt56Luna
99                )
100        )
101    }
102
103    /// Returns the compatible provider/model pair for one speed preference.
104    ///
105    /// Fast Claude requests require Opus, while Codex Spark requests move to
106    /// the provider's default model. Providers without a speed control and
107    /// already compatible selections remain unchanged.
108    #[must_use]
109    pub fn compatible_with_speed_mode(self, speed_mode: SpeedMode) -> Self {
110        if speed_mode == SpeedMode::Normal || self.supports_fast_mode() {
111            return self;
112        }
113
114        match self.kind {
115            AgentKind::Claude => Self::new(AgentKind::Claude, AgentModel::ClaudeOpus5),
116            AgentKind::Codex if self.model == AgentModel::Gpt53CodexSpark => {
117                Self::new(AgentKind::Codex, AgentModel::Gpt56Sol)
118            }
119            AgentKind::Antigravity | AgentKind::Gemini | AgentKind::Codex => self,
120        }
121    }
122}
123
124/// Human-readable metadata for slash-menu selectable items.
125pub trait AgentSelectionMetadata {
126    /// Returns a stable item name shown in menus.
127    fn name(&self) -> &'static str;
128
129    /// Returns a short descriptive subtitle shown in menus.
130    fn description(&self) -> &'static str;
131}
132
133impl AgentModel {
134    /// Returns the stable wire/model identifier used in persistence and CLI
135    /// invocations.
136    pub fn as_str(self) -> &'static str {
137        match self {
138            Self::Gpt6Astra => "gpt-6-astra",
139            Self::Gpt56Sol => "gpt-5.6-sol",
140            Self::Gpt56Terra => "gpt-5.6-terra",
141            Self::Gpt56Luna => "gpt-5.6-luna",
142            Self::Gemini38Flash => "gemini-3.8-flash",
143            Self::Gemini35FlashLite => "gemini-3.5-flash-lite",
144            Self::Gemini31Pro => "gemini-3.1-pro-preview",
145            Self::Gpt53CodexSpark => "gpt-5.3-codex-spark",
146            Self::ClaudeOpus5 => "claude-opus-5",
147            Self::ClaudeSonnet5 => "claude-sonnet-5",
148            Self::ClaudeFable5 => "claude-fable-5",
149            Self::ClaudeHaiku4520251001 => "claude-haiku-4-5-20251001",
150        }
151    }
152
153    /// Returns the model identifier passed to provider transports.
154    ///
155    /// Antigravity and Gemini use the same raw Gemini CLI model ids; callers
156    /// route those ids through the provider stored on [`AgentSelection`].
157    pub fn provider_model_str(self) -> &'static str {
158        self.as_str()
159    }
160
161    /// Parses one persisted model identifier and upgrades retired ids to
162    /// their replacement models.
163    ///
164    /// Stored retired Gemini, Claude, and Codex ids are migrated forward
165    /// through [`AgentModel::retired_replacement`] so existing projects and
166    /// sessions continue loading after model retirements.
167    /// Raw `gemini-*` ids parse to shared Gemini model variants; persisted
168    /// session agents decide whether Gemini or Antigravity owns the session.
169    ///
170    /// # Errors
171    /// Returns an error when `value` is not a known current or retired model
172    /// identifier.
173    pub fn parse_persisted(value: &str) -> Result<Self, String> {
174        if let Some(replacement) = Self::retired_replacement(value) {
175            return Ok(replacement);
176        }
177
178        value.parse()
179    }
180
181    /// Returns the current replacement model for a retired persisted model
182    /// id, or `None` when `value` is not a retired id.
183    ///
184    /// This registry is the single source of truth for model retirement.
185    /// Retiring a model means removing its selectable [`AgentModel`] variant
186    /// and mapping its persisted id to the replacement model here. Retired
187    /// ids never appear in selectable model lists; they stay in the database
188    /// as history for finished sessions, while sessions that are still active
189    /// are switched to the replacement automatically.
190    #[must_use]
191    pub fn retired_replacement(value: &str) -> Option<Self> {
192        const RETIRED_MODEL_REPLACEMENTS: &[(&str, AgentModel)] = &[
193            ("gemini-3-pro-preview", AgentModel::Gemini31Pro),
194            ("gemini-3.1-pro", AgentModel::Gemini31Pro),
195            ("gemini-3-flash-preview", AgentModel::Gemini38Flash),
196            ("gemini-3.7-flash", AgentModel::Gemini38Flash),
197            ("gemini-3.6-flash", AgentModel::Gemini38Flash),
198            ("gemini-3.5-flash", AgentModel::Gemini35FlashLite),
199            (
200                "gemini-3.1-flash-lite-preview",
201                AgentModel::Gemini35FlashLite,
202            ),
203            ("claude-opus-4-8", AgentModel::ClaudeOpus5),
204            ("claude-opus-4-6", AgentModel::ClaudeOpus5),
205            ("claude-opus-4-7", AgentModel::ClaudeOpus5),
206            ("claude-sonnet-4-6", AgentModel::ClaudeSonnet5),
207            ("gpt-5.5", AgentModel::Gpt56Sol),
208            ("gpt-5.4-mini", AgentModel::Gpt56Luna),
209            ("gpt-5.4", AgentModel::Gpt56Sol),
210            ("gpt-5.3-codex", AgentModel::Gpt56Sol),
211            ("gpt-5.2-codex", AgentModel::Gpt53CodexSpark),
212        ];
213
214        RETIRED_MODEL_REPLACEMENTS
215            .iter()
216            .find(|(retired_id, _)| *retired_id == value)
217            .map(|(_, replacement)| *replacement)
218    }
219}
220
221/// Parses one persisted session agent/model pair without deriving the agent
222/// from the model when the saved agent kind is available.
223///
224/// Existing databases did not persist `agent`, so rows with a missing or
225/// invalid agent value fall back to a compatibility provider inferred from
226/// the persisted model string. Ambiguous raw `gemini-*` rows default to
227/// Antigravity because direct Gemini support had been removed before the new
228/// `agent` column was introduced.
229pub fn parse_persisted_session_agent_model(
230    agent_value: Option<&str>,
231    model_value: &str,
232) -> AgentSelection {
233    let parsed_agent = agent_value
234        .filter(|value| !value.trim().is_empty())
235        .and_then(|value| value.parse::<AgentKind>().ok());
236
237    if let Some(agent_kind) = parsed_agent {
238        return parse_model_for_persisted_agent(agent_kind, model_value);
239    }
240
241    let model = AgentModel::parse_persisted(model_value)
242        .unwrap_or_else(|_| AgentKind::Antigravity.default_model());
243    let agent_kind = legacy_agent_kind_for_model_value(model_value, model);
244
245    AgentSelection::new(agent_kind, model)
246}
247
248/// Parses a persisted model using the already persisted agent kind as the
249/// source of truth for provider ownership.
250fn parse_model_for_persisted_agent(agent_kind: AgentKind, model_value: &str) -> AgentSelection {
251    if let Some(model) = agent_kind.parse_model(model_value) {
252        return AgentSelection::new(agent_kind, model);
253    }
254
255    if let Ok(model) = AgentModel::parse_persisted(model_value)
256        && agent_kind.supports_model(model)
257    {
258        return AgentSelection::new(agent_kind, model);
259    }
260
261    AgentSelection::new(agent_kind, agent_kind.default_model())
262}
263
264/// Returns the provider used for legacy rows that predate explicit session
265/// agent persistence.
266fn legacy_agent_kind_for_model_value(model_value: &str, model: AgentModel) -> AgentKind {
267    if model_value.starts_with("claude-") {
268        return AgentKind::Claude;
269    }
270
271    if model_value.starts_with("gpt-") {
272        return AgentKind::Codex;
273    }
274
275    if model_value.starts_with("gemini-") {
276        return AgentKind::Antigravity;
277    }
278
279    AgentKind::ALL
280        .iter()
281        .copied()
282        .find(|agent_kind| agent_kind.supports_model(model))
283        .unwrap_or(AgentKind::Antigravity)
284}
285
286/// Returns all selectable models owned by the provided agent kinds in stable
287/// settings and slash-menu order.
288#[must_use]
289pub fn selectable_models_for_agent_kinds(agent_kinds: &[AgentKind]) -> Vec<AgentModel> {
290    let mut models = Vec::new();
291    for model in agent_kinds
292        .iter()
293        .flat_map(|agent_kind| agent_kind.models())
294        .copied()
295    {
296        if !models.contains(&model) {
297            models.push(model);
298        }
299    }
300
301    models
302}
303
304/// Resolves one model against the currently available agent kinds.
305///
306/// When `model` is unsupported by every available provider, this prefers
307/// `fallback_model` when any available provider supports it and otherwise falls
308/// back to the first available provider default in `agent_kinds`. When no
309/// providers are available, it returns `fallback_model` unchanged.
310#[must_use]
311pub fn resolve_model_for_available_agent_kinds(
312    model: AgentModel,
313    agent_kinds: &[AgentKind],
314    fallback_model: AgentModel,
315) -> AgentModel {
316    if agent_kinds
317        .iter()
318        .any(|agent_kind| agent_kind.supports_model(model))
319    {
320        return model;
321    }
322
323    if agent_kinds
324        .iter()
325        .any(|agent_kind| agent_kind.supports_model(fallback_model))
326    {
327        return fallback_model;
328    }
329
330    agent_kinds
331        .first()
332        .copied()
333        .map_or(fallback_model, AgentKind::default_model)
334}
335
336/// Resolves a provider kind that can run `model` from the available provider
337/// list.
338///
339/// Shared Gemini model ids can be run by both Gemini and Antigravity. This
340/// helper uses the order of `agent_kinds` as the tie-breaker and returns
341/// `fallback_agent_kind` when no available provider supports `model`.
342#[must_use]
343pub fn resolve_agent_kind_for_model(
344    model: AgentModel,
345    agent_kinds: &[AgentKind],
346    fallback_agent_kind: AgentKind,
347) -> AgentKind {
348    agent_kinds
349        .iter()
350        .copied()
351        .find(|agent_kind| agent_kind.supports_model(model))
352        .unwrap_or(fallback_agent_kind)
353}
354
355/// Resolves an [`AgentSelection`] for a model-only setting.
356///
357/// `preferred_agent_kind` is kept when it can run `model`, which preserves the
358/// current session provider for shared Gemini model ids. Otherwise the
359/// available provider order decides the owning provider, falling back to
360/// `preferred_agent_kind` when no available provider supports the model.
361#[must_use]
362pub fn resolve_agent_selection_for_model(
363    model: AgentModel,
364    preferred_agent_kind: AgentKind,
365    agent_kinds: &[AgentKind],
366) -> AgentSelection {
367    let agent_kind = if preferred_agent_kind.supports_model(model) {
368        preferred_agent_kind
369    } else {
370        resolve_agent_kind_for_model(model, agent_kinds, preferred_agent_kind)
371    };
372
373    AgentSelection::new(agent_kind, model)
374}
375
376/// Resolves the agent kind used for prompt-side `/model` selection.
377///
378/// This preserves `session_agent_kind` when that backend is still available
379/// and otherwise falls back to the first available backend. When no backends
380/// are available, it returns `None`.
381#[must_use]
382pub fn resolve_prompt_model_agent_kind(
383    session_agent_kind: AgentKind,
384    agent_kinds: &[AgentKind],
385) -> Option<AgentKind> {
386    if agent_kinds.contains(&session_agent_kind) {
387        return Some(session_agent_kind);
388    }
389
390    agent_kinds.first().copied()
391}
392
393impl FromStr for AgentModel {
394    type Err = String;
395
396    fn from_str(value: &str) -> Result<Self, Self::Err> {
397        match value {
398            "gemini-3.8-flash" => Ok(Self::Gemini38Flash),
399            "gemini-3.5-flash-lite" => Ok(Self::Gemini35FlashLite),
400            "gemini-3.1-pro-preview" => Ok(Self::Gemini31Pro),
401            "gpt-6-astra" => Ok(Self::Gpt6Astra),
402            "gpt-5.6-sol" => Ok(Self::Gpt56Sol),
403            "gpt-5.6-terra" => Ok(Self::Gpt56Terra),
404            "gpt-5.6-luna" => Ok(Self::Gpt56Luna),
405            "gpt-5.3-codex-spark" => Ok(Self::Gpt53CodexSpark),
406            "claude-opus-5" => Ok(Self::ClaudeOpus5),
407            "claude-sonnet-5" => Ok(Self::ClaudeSonnet5),
408            "claude-fable-5" => Ok(Self::ClaudeFable5),
409            "claude-haiku-4-5-20251001" => Ok(Self::ClaudeHaiku4520251001),
410            other => Err(format!("unknown model: {other}")),
411        }
412    }
413}
414
415impl AgentSelectionMetadata for AgentModel {
416    fn name(&self) -> &'static str {
417        (*self).provider_model_str()
418    }
419
420    fn description(&self) -> &'static str {
421        match self {
422            Self::Gemini31Pro => "Higher-quality Gemini model for deeper reasoning.",
423            Self::Gemini38Flash => "Fast Gemini model for agentic and multimodal tasks.",
424            Self::Gemini35FlashLite => {
425                "Lightweight Gemini model for fast, cost-conscious workloads."
426            }
427            Self::Gpt6Astra => "Most capable Codex model for the hardest end-to-end work.",
428            Self::Gpt56Sol => "Flagship Codex model for complex professional work.",
429            Self::Gpt56Terra => "Current Codex model for balanced coding performance.",
430            Self::Gpt56Luna => "Current Codex model for lighter coding iterations.",
431            Self::Gpt53CodexSpark => "Codex spark model for quick coding iterations.",
432            Self::ClaudeOpus5 => "Latest Claude Opus model for complex tasks.",
433            Self::ClaudeSonnet5 => "Balanced Claude model for quality and latency.",
434            Self::ClaudeFable5 => "Claude Fable model for creative, narrative-heavy tasks.",
435            Self::ClaudeHaiku4520251001 => "Fast Claude model for lighter tasks.",
436        }
437    }
438}
439
440impl AgentKind {
441    /// All available agent kinds, in display order.
442    pub const ALL: &[AgentKind] = &[
443        AgentKind::Gemini,
444        AgentKind::Antigravity,
445        AgentKind::Claude,
446        AgentKind::Codex,
447    ];
448
449    /// Returns the provider CLI executable name.
450    pub fn executable_name(self) -> &'static str {
451        match self {
452            Self::Antigravity => "agy",
453            Self::Gemini => "gemini",
454            Self::Claude => "claude",
455            Self::Codex => "codex",
456        }
457    }
458
459    /// Returns the default model for this agent kind.
460    pub fn default_model(self) -> AgentModel {
461        match self {
462            Self::Antigravity | Self::Gemini => AgentModel::Gemini31Pro,
463            Self::Claude => AgentModel::ClaudeFable5,
464            Self::Codex => AgentModel::Gpt56Sol,
465        }
466    }
467
468    /// Returns the model string when it belongs to this agent kind.
469    pub fn model_str(self, model: AgentModel) -> Option<&'static str> {
470        if !self.supports_model(model) {
471            return None;
472        }
473
474        Some(model.as_str())
475    }
476
477    /// Returns the curated model list for this agent kind.
478    pub fn models(self) -> &'static [AgentModel] {
479        const ANTIGRAVITY_MODELS: &[AgentModel] = &[
480            AgentModel::Gemini31Pro,
481            AgentModel::Gemini38Flash,
482            AgentModel::Gemini35FlashLite,
483        ];
484        const GEMINI_MODELS: &[AgentModel] = &[
485            AgentModel::Gemini31Pro,
486            AgentModel::Gemini38Flash,
487            AgentModel::Gemini35FlashLite,
488        ];
489        const CLAUDE_MODELS: &[AgentModel] = &[
490            AgentModel::ClaudeFable5,
491            AgentModel::ClaudeOpus5,
492            AgentModel::ClaudeSonnet5,
493            AgentModel::ClaudeHaiku4520251001,
494        ];
495        const CODEX_MODELS: &[AgentModel] = &[
496            AgentModel::Gpt6Astra,
497            AgentModel::Gpt56Sol,
498            AgentModel::Gpt56Terra,
499            AgentModel::Gpt56Luna,
500            AgentModel::Gpt53CodexSpark,
501        ];
502
503        match self {
504            Self::Antigravity => ANTIGRAVITY_MODELS,
505            Self::Gemini => GEMINI_MODELS,
506            Self::Claude => CLAUDE_MODELS,
507            Self::Codex => CODEX_MODELS,
508        }
509    }
510
511    /// Parses a provider-specific model string for this agent kind.
512    pub fn parse_model(self, value: &str) -> Option<AgentModel> {
513        let model = value.parse::<AgentModel>().ok()?;
514        if !self.supports_model(model) {
515            return None;
516        }
517
518        Some(model)
519    }
520
521    /// Returns whether this provider can run the given model.
522    pub fn supports_model(self, model: AgentModel) -> bool {
523        self.models().contains(&model)
524    }
525
526    /// Returns whether this provider exposes a response-speed control.
527    ///
528    /// Claude and Codex accept a per-turn speed selection, so `/speed` offers
529    /// the picker and session surfaces display the active [`SpeedMode`].
530    /// Gemini and Antigravity have no equivalent control, so neither the
531    /// command nor the speed display is offered for them.
532    ///
533    /// [`SpeedMode`]: ag_runtime::SpeedMode
534    pub fn supports_speed_mode(self) -> bool {
535        matches!(self, Self::Claude | Self::Codex)
536    }
537}
538
539impl AgentSelectionMetadata for AgentKind {
540    fn name(&self) -> &'static str {
541        match self {
542            Self::Antigravity => "antigravity",
543            Self::Gemini => "gemini",
544            Self::Claude => "claude",
545            Self::Codex => "codex",
546        }
547    }
548
549    fn description(&self) -> &'static str {
550        match self {
551            Self::Antigravity => "Google Antigravity CLI agent.",
552            Self::Gemini => "Google Gemini CLI agent.",
553            Self::Claude => "Anthropic Claude Code agent.",
554            Self::Codex => "OpenAI Codex CLI agent.",
555        }
556    }
557}
558
559impl AgentSelectionMetadata for ReasoningLevel {
560    fn name(&self) -> &'static str {
561        (*self).as_str()
562    }
563
564    fn description(&self) -> &'static str {
565        (*self).description()
566    }
567}
568
569impl fmt::Display for AgentKind {
570    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
571        write!(f, "{}", self.name())
572    }
573}
574
575impl FromStr for AgentKind {
576    type Err = String;
577
578    fn from_str(s: &str) -> Result<Self, Self::Err> {
579        match s.to_lowercase().as_str() {
580            "antigravity" | "agy" => Ok(Self::Antigravity),
581            "gemini" => Ok(Self::Gemini),
582            "claude" => Ok(Self::Claude),
583            "codex" => Ok(Self::Codex),
584            other => Err(format!("unknown agent kind: {other}")),
585        }
586    }
587}
588
589#[cfg(test)]
590#[path = "agent_test.rs"]
591mod tests;