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