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