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