Skip to main content

jev/
model.rs

1//! Model identifiers and surface-aware wire-ID normalization.
2
3use std::{borrow::Cow, fmt, str::FromStr};
4
5use crate::{config::Surface, error::Error};
6
7/// Bare (unnamespaced) System One ID for the pinned default model.
8const JEV_1_13_BARE: &str = "jev-1.13";
9/// Decisions-surface (namespaced) ID for the pinned default model.
10const JEV_1_13_NAMESPACED: &str = "typesafe/jev-1.13";
11/// Bare (unnamespaced) System One ID for the rolling-latest alias.
12const JEV_LATEST_BARE: &str = "jev-latest";
13/// Decisions-surface (namespaced) ID for the rolling-latest alias.
14const JEV_LATEST_NAMESPACED: &str = "~typesafe/jev-latest";
15
16/// The context window, in tokens, shared by every known Jev model as of this release.
17const KNOWN_MODEL_CONTEXT_TOKENS: usize = 32_000;
18
19/// A Jev / System One model identifier.
20///
21/// `Model` normalizes the documented ID mapping between the two API surfaces: the
22/// Decisions surface expects an author-namespaced ID (`typesafe/jev-1.13`), while the
23/// System One surface accepts and returns bare IDs (`jev-1.13`). Use
24/// [`Model::wire_id`] to get the ID to send for a given [`Surface`].
25/// [`crate::Client`] additionally maps the pinned default to `jev-1.13.0` for
26/// [`crate::Provider::TypeSafe`], following the direct API's version convention.
27///
28/// # Examples
29///
30/// ```
31/// use jev::{Model, Surface};
32///
33/// let model = Model::Jev113;
34/// assert_eq!(model.wire_id(Surface::Decisions), "typesafe/jev-1.13");
35/// assert_eq!(model.wire_id(Surface::SystemOne), "jev-1.13");
36/// ```
37#[derive(Debug, Clone, PartialEq, Eq)]
38#[non_exhaustive]
39pub enum Model {
40    /// `typesafe/jev-1.13` on the Decisions surface, `jev-1.13` on System One.
41    ///
42    /// This is [`DEFAULT_MODEL`]: pinned, not auto-updating. Thresholds are tuned
43    /// against one model's calibration, so silently following `jev-latest` would
44    /// silently re-tune every gate in production.
45    Jev113,
46    /// `~typesafe/jev-latest` on the Decisions surface, `jev-latest` on System One.
47    ///
48    /// Tracks the newest release. Intended for exploratory work, not for a service
49    /// with tuned thresholds.
50    Latest,
51    /// Any other System One model ID, passed through unchanged on every surface.
52    Custom(String),
53}
54
55/// The pinned default model. A bump is one reviewable line, deliberately never
56/// [`Model::Latest`]. See [`Model::Jev113`] for the rationale.
57pub const DEFAULT_MODEL: Model = Model::Jev113;
58
59impl Model {
60    /// The identifier to send on the wire for the given [`Surface`].
61    ///
62    /// [`Model::Custom`] is never rewritten: the caller owns the exact string they
63    /// provided, on every surface.
64    ///
65    /// # Examples
66    ///
67    /// ```
68    /// use jev::{Model, Surface};
69    ///
70    /// let custom = Model::Custom("acme/experimental".to_string());
71    /// assert_eq!(custom.wire_id(Surface::Decisions), "acme/experimental");
72    /// assert_eq!(custom.wire_id(Surface::SystemOne), "acme/experimental");
73    /// ```
74    #[must_use]
75    pub fn wire_id(&self, surface: Surface) -> Cow<'_, str> {
76        match (self, surface) {
77            (Model::Jev113, Surface::Decisions) => Cow::Borrowed(JEV_1_13_NAMESPACED),
78            (Model::Jev113, Surface::SystemOne) => Cow::Borrowed(JEV_1_13_BARE),
79            (Model::Latest, Surface::Decisions) => Cow::Borrowed(JEV_LATEST_NAMESPACED),
80            (Model::Latest, Surface::SystemOne) => Cow::Borrowed(JEV_LATEST_BARE),
81            (Model::Custom(id), _) => Cow::Borrowed(id.as_str()),
82        }
83    }
84
85    /// The model's context window, in tokens, used for a cheap pre-flight size check.
86    ///
87    /// Returns `None` for [`Model::Custom`], since the SDK has no data for it; the
88    /// context-size guard is skipped in that case and the server remains authoritative.
89    #[must_use]
90    pub fn context_tokens(&self) -> Option<usize> {
91        match self {
92            Model::Jev113 | Model::Latest => Some(KNOWN_MODEL_CONTEXT_TOKENS),
93            Model::Custom(_) => None,
94        }
95    }
96}
97
98impl fmt::Display for Model {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        match self {
101            Model::Jev113 => f.write_str(JEV_1_13_NAMESPACED),
102            Model::Latest => f.write_str(JEV_LATEST_NAMESPACED),
103            Model::Custom(id) => f.write_str(id),
104        }
105    }
106}
107
108impl FromStr for Model {
109    type Err = Error;
110
111    /// Parses a model ID in either its bare or namespaced form.
112    ///
113    /// # Examples
114    ///
115    /// ```
116    /// use jev::Model;
117    ///
118    /// assert_eq!("jev-1.13".parse::<Model>().unwrap(), Model::Jev113);
119    /// assert_eq!("typesafe/jev-1.13".parse::<Model>().unwrap(), Model::Jev113);
120    /// assert_eq!("~typesafe/jev-latest".parse::<Model>().unwrap(), Model::Latest);
121    /// ```
122    ///
123    /// # Errors
124    ///
125    /// Returns [`Error::Invalid`] when `s` is empty.
126    fn from_str(s: &str) -> Result<Self, Self::Err> {
127        if s.is_empty() {
128            return Err(Error::Invalid {
129                field: "model".to_string(),
130                reason: "model id must not be empty".to_string(),
131            });
132        }
133        Ok(match s {
134            JEV_1_13_BARE | JEV_1_13_NAMESPACED => Model::Jev113,
135            JEV_LATEST_BARE | JEV_LATEST_NAMESPACED => Model::Latest,
136            other => Model::Custom(other.to_string()),
137        })
138    }
139}
140
141impl fmt::Display for Surface {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        match self {
144            Surface::Decisions => f.write_str("decisions"),
145            Surface::SystemOne => f.write_str("systemOne"),
146        }
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use proptest::prelude::*;
153
154    use super::*;
155
156    #[test]
157    fn test_should_map_jev113_wire_id_per_surface() {
158        assert_eq!(
159            Model::Jev113.wire_id(Surface::Decisions),
160            "typesafe/jev-1.13"
161        );
162        assert_eq!(Model::Jev113.wire_id(Surface::SystemOne), "jev-1.13");
163    }
164
165    #[test]
166    fn test_should_map_latest_wire_id_per_surface() {
167        assert_eq!(
168            Model::Latest.wire_id(Surface::Decisions),
169            "~typesafe/jev-latest"
170        );
171        assert_eq!(Model::Latest.wire_id(Surface::SystemOne), "jev-latest");
172    }
173
174    #[test]
175    fn test_should_never_rewrite_custom_model() {
176        let custom = Model::Custom("acme/model-x".to_string());
177        assert_eq!(custom.wire_id(Surface::Decisions), "acme/model-x");
178        assert_eq!(custom.wire_id(Surface::SystemOne), "acme/model-x");
179    }
180
181    #[test]
182    fn test_should_default_to_pinned_jev113_not_latest() {
183        assert_eq!(DEFAULT_MODEL, Model::Jev113);
184    }
185
186    #[test]
187    fn test_should_parse_bare_and_namespaced_ids() {
188        assert_eq!("jev-1.13".parse::<Model>().unwrap(), Model::Jev113);
189        assert_eq!("typesafe/jev-1.13".parse::<Model>().unwrap(), Model::Jev113);
190        assert_eq!("jev-latest".parse::<Model>().unwrap(), Model::Latest);
191        assert_eq!(
192            "~typesafe/jev-latest".parse::<Model>().unwrap(),
193            Model::Latest
194        );
195    }
196
197    #[test]
198    fn test_should_parse_unknown_id_as_custom() {
199        assert_eq!(
200            "acme/model-x".parse::<Model>().unwrap(),
201            Model::Custom("acme/model-x".to_string())
202        );
203    }
204
205    #[test]
206    fn test_should_reject_empty_model_string() {
207        assert!("".parse::<Model>().is_err());
208    }
209
210    #[test]
211    fn test_should_report_context_tokens_for_known_models_only() {
212        assert_eq!(Model::Jev113.context_tokens(), Some(32_000));
213        assert_eq!(Model::Latest.context_tokens(), Some(32_000));
214        assert_eq!(Model::Custom("x".into()).context_tokens(), None);
215    }
216
217    proptest! {
218        #[test]
219        fn test_should_round_trip_display_and_from_str_for_custom(id in "[a-z][a-z0-9_/.~-]{1,40}") {
220            // Avoid colliding with the two reserved canonical forms, which is not a
221            // round-trip failure but a deliberate, documented normalization.
222            prop_assume!(!matches!(id.as_str(), "jev-1.13" | "typesafe/jev-1.13" | "jev-latest" | "~typesafe/jev-latest"));
223            let model = Model::Custom(id.clone());
224            let displayed = model.to_string();
225            let parsed: Model = displayed.parse().unwrap();
226            prop_assert_eq!(parsed, Model::Custom(id));
227        }
228
229        #[test]
230        fn test_should_round_trip_display_and_from_str_for_canonical_models(pick in 0usize..2) {
231            let model = if pick == 0 { Model::Jev113 } else { Model::Latest };
232            let displayed = model.to_string();
233            let parsed: Model = displayed.parse().unwrap();
234            prop_assert_eq!(parsed, model);
235        }
236    }
237}