Skip to main content

ag_session/
agent.rs

1use std::fmt;
2use std::str::FromStr;
3
4use ag_contracts::{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-6.1-sol`.
29    Gpt61Sol,
30    /// Codex Luna model backed by `gpt-6-luna`.
31    Gpt6Luna,
32    /// Codex Terra model backed by `gpt-5.6-terra`.
33    Gpt56Terra,
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-5`.
43    ClaudeOpus55,
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::ClaudeOpus55)
93                | (
94                    AgentKind::Codex,
95                    AgentModel::Gpt6Astra
96                        | AgentModel::Gpt61Sol
97                        | AgentModel::Gpt6Luna
98                        | AgentModel::Gpt56Terra
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::ClaudeOpus55),
116            AgentKind::Codex if self.model == AgentModel::Gpt53CodexSpark => {
117                Self::new(AgentKind::Codex, AgentModel::Gpt61Sol)
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::Gpt61Sol => "gpt-6.1-sol",
140            Self::Gpt6Luna => "gpt-6-luna",
141            Self::Gpt56Terra => "gpt-5.6-terra",
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::ClaudeOpus55 => "claude-opus-5-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-5", AgentModel::ClaudeOpus55),
204            ("gpt-6-sol", AgentModel::Gpt61Sol),
205            ("gpt-5.6-sol", AgentModel::Gpt61Sol),
206            ("gpt-5.6-luna", AgentModel::Gpt6Luna),
207            ("claude-opus-4-8", AgentModel::ClaudeOpus55),
208            ("claude-opus-4-6", AgentModel::ClaudeOpus55),
209            ("claude-opus-4-7", AgentModel::ClaudeOpus55),
210            ("claude-sonnet-4-6", AgentModel::ClaudeSonnet5),
211            ("gpt-5.5", AgentModel::Gpt61Sol),
212            ("gpt-5.4-mini", AgentModel::Gpt6Luna),
213            ("gpt-5.4", AgentModel::Gpt61Sol),
214            ("gpt-5.3-codex", AgentModel::Gpt61Sol),
215            ("gpt-5.2-codex", AgentModel::Gpt53CodexSpark),
216        ];
217
218        RETIRED_MODEL_REPLACEMENTS
219            .iter()
220            .find(|(retired_id, _)| *retired_id == value)
221            .map(|(_, replacement)| *replacement)
222    }
223}
224
225/// Parses one persisted session agent/model pair without deriving the agent
226/// from the model when the saved agent kind is available.
227///
228/// Existing databases did not persist `agent`, so rows with a missing or
229/// invalid agent value fall back to a compatibility provider inferred from
230/// the persisted model string. Ambiguous raw `gemini-*` rows default to
231/// Antigravity because direct Gemini support had been removed before the new
232/// `agent` column was introduced.
233pub fn parse_persisted_session_agent_model(
234    agent_value: Option<&str>,
235    model_value: &str,
236) -> AgentSelection {
237    let parsed_agent = agent_value
238        .filter(|value| !value.trim().is_empty())
239        .and_then(|value| value.parse::<AgentKind>().ok());
240
241    if let Some(agent_kind) = parsed_agent {
242        return parse_model_for_persisted_agent(agent_kind, model_value);
243    }
244
245    let model = AgentModel::parse_persisted(model_value)
246        .unwrap_or_else(|_| AgentKind::Antigravity.default_model());
247    let agent_kind = legacy_agent_kind_for_model_value(model_value, model);
248
249    AgentSelection::new(agent_kind, model)
250}
251
252/// Parses a persisted model using the already persisted agent kind as the
253/// source of truth for provider ownership.
254fn parse_model_for_persisted_agent(agent_kind: AgentKind, model_value: &str) -> AgentSelection {
255    if let Some(model) = agent_kind.parse_model(model_value) {
256        return AgentSelection::new(agent_kind, model);
257    }
258
259    if let Ok(model) = AgentModel::parse_persisted(model_value)
260        && agent_kind.supports_model(model)
261    {
262        return AgentSelection::new(agent_kind, model);
263    }
264
265    AgentSelection::new(agent_kind, agent_kind.default_model())
266}
267
268/// Returns the provider used for legacy rows that predate explicit session
269/// agent persistence.
270fn legacy_agent_kind_for_model_value(model_value: &str, model: AgentModel) -> AgentKind {
271    if model_value.starts_with("claude-") {
272        return AgentKind::Claude;
273    }
274
275    if model_value.starts_with("gpt-") {
276        return AgentKind::Codex;
277    }
278
279    if model_value.starts_with("gemini-") {
280        return AgentKind::Antigravity;
281    }
282
283    AgentKind::ALL
284        .iter()
285        .copied()
286        .find(|agent_kind| agent_kind.supports_model(model))
287        .unwrap_or(AgentKind::Antigravity)
288}
289
290/// Returns all selectable models owned by the provided agent kinds in stable
291/// settings and slash-menu order.
292#[must_use]
293pub fn selectable_models_for_agent_kinds(agent_kinds: &[AgentKind]) -> Vec<AgentModel> {
294    let mut models = Vec::new();
295    for model in agent_kinds
296        .iter()
297        .flat_map(|agent_kind| agent_kind.models())
298        .copied()
299    {
300        if !models.contains(&model) {
301            models.push(model);
302        }
303    }
304
305    models
306}
307
308/// Resolves one model against the currently available agent kinds.
309///
310/// When `model` is unsupported by every available provider, this prefers
311/// `fallback_model` when any available provider supports it and otherwise falls
312/// back to the first available provider default in `agent_kinds`. When no
313/// providers are available, it returns `fallback_model` unchanged.
314#[must_use]
315pub fn resolve_model_for_available_agent_kinds(
316    model: AgentModel,
317    agent_kinds: &[AgentKind],
318    fallback_model: AgentModel,
319) -> AgentModel {
320    if agent_kinds
321        .iter()
322        .any(|agent_kind| agent_kind.supports_model(model))
323    {
324        return model;
325    }
326
327    if agent_kinds
328        .iter()
329        .any(|agent_kind| agent_kind.supports_model(fallback_model))
330    {
331        return fallback_model;
332    }
333
334    agent_kinds
335        .first()
336        .copied()
337        .map_or(fallback_model, AgentKind::default_model)
338}
339
340/// Resolves a provider kind that can run `model` from the available provider
341/// list.
342///
343/// Shared Gemini model ids can be run by both Gemini and Antigravity. This
344/// helper uses the order of `agent_kinds` as the tie-breaker and returns
345/// `fallback_agent_kind` when no available provider supports `model`.
346#[must_use]
347pub fn resolve_agent_kind_for_model(
348    model: AgentModel,
349    agent_kinds: &[AgentKind],
350    fallback_agent_kind: AgentKind,
351) -> AgentKind {
352    agent_kinds
353        .iter()
354        .copied()
355        .find(|agent_kind| agent_kind.supports_model(model))
356        .unwrap_or(fallback_agent_kind)
357}
358
359/// Resolves an [`AgentSelection`] for a model-only setting.
360///
361/// `preferred_agent_kind` is kept when it can run `model`, which preserves the
362/// current session provider for shared Gemini model ids. Otherwise the
363/// available provider order decides the owning provider, falling back to
364/// `preferred_agent_kind` when no available provider supports the model.
365#[must_use]
366pub fn resolve_agent_selection_for_model(
367    model: AgentModel,
368    preferred_agent_kind: AgentKind,
369    agent_kinds: &[AgentKind],
370) -> AgentSelection {
371    let agent_kind = if preferred_agent_kind.supports_model(model) {
372        preferred_agent_kind
373    } else {
374        resolve_agent_kind_for_model(model, agent_kinds, preferred_agent_kind)
375    };
376
377    AgentSelection::new(agent_kind, model)
378}
379
380/// Resolves the agent kind used for prompt-side `/model` selection.
381///
382/// This preserves `session_agent_kind` when that backend is still available
383/// and otherwise falls back to the first available backend. When no backends
384/// are available, it returns `None`.
385#[must_use]
386pub fn resolve_prompt_model_agent_kind(
387    session_agent_kind: AgentKind,
388    agent_kinds: &[AgentKind],
389) -> Option<AgentKind> {
390    if agent_kinds.contains(&session_agent_kind) {
391        return Some(session_agent_kind);
392    }
393
394    agent_kinds.first().copied()
395}
396
397impl FromStr for AgentModel {
398    type Err = String;
399
400    fn from_str(value: &str) -> Result<Self, Self::Err> {
401        match value {
402            "gemini-3.8-flash" => Ok(Self::Gemini38Flash),
403            "gemini-3.5-flash-lite" => Ok(Self::Gemini35FlashLite),
404            "gemini-3.1-pro-preview" => Ok(Self::Gemini31Pro),
405            "gpt-6-astra" => Ok(Self::Gpt6Astra),
406            "gpt-6.1-sol" => Ok(Self::Gpt61Sol),
407            "gpt-6-luna" => Ok(Self::Gpt6Luna),
408            "gpt-5.6-terra" => Ok(Self::Gpt56Terra),
409            "gpt-5.3-codex-spark" => Ok(Self::Gpt53CodexSpark),
410            "claude-opus-5-5" => Ok(Self::ClaudeOpus55),
411            "claude-sonnet-5" => Ok(Self::ClaudeSonnet5),
412            "claude-fable-5" => Ok(Self::ClaudeFable5),
413            "claude-haiku-4-5-20251001" => Ok(Self::ClaudeHaiku4520251001),
414            other => Err(format!("unknown model: {other}")),
415        }
416    }
417}
418
419impl AgentSelectionMetadata for AgentModel {
420    fn name(&self) -> &'static str {
421        (*self).provider_model_str()
422    }
423
424    fn description(&self) -> &'static str {
425        match self {
426            Self::Gemini31Pro => "Higher-quality Gemini model for deeper reasoning.",
427            Self::Gemini38Flash => "Fast Gemini model for agentic and multimodal tasks.",
428            Self::Gemini35FlashLite => {
429                "Lightweight Gemini model for fast, cost-conscious workloads."
430            }
431            Self::Gpt6Astra => "Most capable Codex model for the hardest end-to-end work.",
432            Self::Gpt61Sol => "Near-Astra Codex model for complex work at a lower cost.",
433            Self::Gpt6Luna => "Efficient Codex model for focused, high-volume tasks.",
434            Self::Gpt56Terra => "Current Codex model for balanced coding performance.",
435            Self::Gpt53CodexSpark => "Codex spark model for quick coding iterations.",
436            Self::ClaudeOpus55 => "Latest Claude Opus model for complex agentic tasks.",
437            Self::ClaudeSonnet5 => "Balanced Claude model for quality and latency.",
438            Self::ClaudeFable5 => "Claude Fable model for creative, narrative-heavy tasks.",
439            Self::ClaudeHaiku4520251001 => "Fast Claude model for lighter tasks.",
440        }
441    }
442}
443
444impl AgentKind {
445    /// All available agent kinds, in display order.
446    pub const ALL: &[AgentKind] = &[
447        AgentKind::Gemini,
448        AgentKind::Antigravity,
449        AgentKind::Claude,
450        AgentKind::Codex,
451    ];
452
453    /// Returns the provider CLI executable name.
454    pub fn executable_name(self) -> &'static str {
455        match self {
456            Self::Antigravity => "agy",
457            Self::Gemini => "gemini",
458            Self::Claude => "claude",
459            Self::Codex => "codex",
460        }
461    }
462
463    /// Returns the default model for this agent kind.
464    pub fn default_model(self) -> AgentModel {
465        match self {
466            Self::Antigravity | Self::Gemini => AgentModel::Gemini31Pro,
467            Self::Claude => AgentModel::ClaudeFable5,
468            Self::Codex => AgentModel::Gpt61Sol,
469        }
470    }
471
472    /// Returns the model string when it belongs to this agent kind.
473    pub fn model_str(self, model: AgentModel) -> Option<&'static str> {
474        if !self.supports_model(model) {
475            return None;
476        }
477
478        Some(model.as_str())
479    }
480
481    /// Returns the curated model list for this agent kind.
482    pub fn models(self) -> &'static [AgentModel] {
483        const ANTIGRAVITY_MODELS: &[AgentModel] = &[
484            AgentModel::Gemini31Pro,
485            AgentModel::Gemini38Flash,
486            AgentModel::Gemini35FlashLite,
487        ];
488        const GEMINI_MODELS: &[AgentModel] = &[
489            AgentModel::Gemini31Pro,
490            AgentModel::Gemini38Flash,
491            AgentModel::Gemini35FlashLite,
492        ];
493        const CLAUDE_MODELS: &[AgentModel] = &[
494            AgentModel::ClaudeFable5,
495            AgentModel::ClaudeOpus55,
496            AgentModel::ClaudeSonnet5,
497            AgentModel::ClaudeHaiku4520251001,
498        ];
499        const CODEX_MODELS: &[AgentModel] = &[
500            AgentModel::Gpt6Astra,
501            AgentModel::Gpt61Sol,
502            AgentModel::Gpt6Luna,
503            AgentModel::Gpt56Terra,
504            AgentModel::Gpt53CodexSpark,
505        ];
506
507        match self {
508            Self::Antigravity => ANTIGRAVITY_MODELS,
509            Self::Gemini => GEMINI_MODELS,
510            Self::Claude => CLAUDE_MODELS,
511            Self::Codex => CODEX_MODELS,
512        }
513    }
514
515    /// Parses a provider-specific model string for this agent kind.
516    pub fn parse_model(self, value: &str) -> Option<AgentModel> {
517        let model = value.parse::<AgentModel>().ok()?;
518        if !self.supports_model(model) {
519            return None;
520        }
521
522        Some(model)
523    }
524
525    /// Returns whether this provider can run the given model.
526    pub fn supports_model(self, model: AgentModel) -> bool {
527        self.models().contains(&model)
528    }
529
530    /// Returns whether this provider exposes a response-speed control.
531    ///
532    /// Claude and Codex accept a per-turn speed selection, so `/speed` offers
533    /// the picker and session surfaces display the active [`SpeedMode`].
534    /// Gemini and Antigravity have no equivalent control, so neither the
535    /// command nor the speed display is offered for them.
536    ///
537    /// [`SpeedMode`]: ag_contracts::SpeedMode
538    pub fn supports_speed_mode(self) -> bool {
539        matches!(self, Self::Claude | Self::Codex)
540    }
541}
542
543impl AgentSelectionMetadata for AgentKind {
544    fn name(&self) -> &'static str {
545        match self {
546            Self::Antigravity => "antigravity",
547            Self::Gemini => "gemini",
548            Self::Claude => "claude",
549            Self::Codex => "codex",
550        }
551    }
552
553    fn description(&self) -> &'static str {
554        match self {
555            Self::Antigravity => "Google Antigravity CLI agent.",
556            Self::Gemini => "Google Gemini CLI agent.",
557            Self::Claude => "Anthropic Claude Code agent.",
558            Self::Codex => "OpenAI Codex CLI agent.",
559        }
560    }
561}
562
563impl AgentSelectionMetadata for ReasoningLevel {
564    fn name(&self) -> &'static str {
565        (*self).as_str()
566    }
567
568    fn description(&self) -> &'static str {
569        (*self).description()
570    }
571}
572
573impl fmt::Display for AgentKind {
574    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
575        write!(f, "{}", self.name())
576    }
577}
578
579impl FromStr for AgentKind {
580    type Err = String;
581
582    fn from_str(s: &str) -> Result<Self, Self::Err> {
583        match s.to_lowercase().as_str() {
584            "antigravity" | "agy" => Ok(Self::Antigravity),
585            "gemini" => Ok(Self::Gemini),
586            "claude" => Ok(Self::Claude),
587            "codex" => Ok(Self::Codex),
588            other => Err(format!("unknown agent kind: {other}")),
589        }
590    }
591}
592
593#[cfg(test)]
594#[path = "agent_test.rs"]
595mod tests;