1use serde::{Deserialize, Serialize};
10
11use crate::agent::EffortRequest;
12use crate::models::{CachedModel, auto_resolve_all, infer_provider_from_model_id};
13
14#[derive(Debug, Clone, PartialEq, Serialize)]
15pub struct ModelAlias {
16 #[serde(skip_serializing_if = "Option::is_none")]
17 pub harness: Option<String>,
18 #[serde(skip_serializing_if = "Option::is_none")]
19 pub description: Option<String>,
20 #[serde(skip_serializing_if = "Option::is_none")]
21 pub prompting: Option<String>,
22 #[serde(skip_serializing_if = "Option::is_none")]
23 pub default_effort: Option<EffortRequest>,
24 #[serde(skip_serializing_if = "Option::is_none")]
25 pub autocompact: Option<u32>,
26 #[serde(skip_serializing_if = "Option::is_none")]
27 pub autocompact_pct: Option<u8>,
28 #[serde(flatten)]
29 pub spec: ModelSpec,
30}
31
32impl ModelAlias {
33 pub fn pinned_model_id(&self) -> Option<&str> {
34 match &self.spec {
35 ModelSpec::Pinned { model, .. } | ModelSpec::PinnedWithMatch { model, .. } => {
36 Some(model.as_str())
37 }
38 ModelSpec::AutoResolve { .. } => None,
39 }
40 }
41}
42
43#[derive(Debug, Clone, PartialEq)]
44pub enum ModelSpec {
45 Pinned {
46 model: String,
47 provider: Option<String>,
48 },
49 PinnedWithMatch {
50 model: String,
51 provider: Option<String>,
52 match_patterns: Vec<String>,
53 exclude_patterns: Vec<String>,
54 },
55 AutoResolve {
56 provider: Option<String>,
57 match_patterns: Vec<String>,
58 exclude_patterns: Vec<String>,
59 },
60}
61
62impl Serialize for ModelSpec {
63 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
64 use serde::ser::SerializeMap;
65 match self {
66 ModelSpec::Pinned { model, provider } => {
67 let mut count = 1;
68 if provider.is_some() {
69 count += 1;
70 }
71 let mut map = serializer.serialize_map(Some(count))?;
72 map.serialize_entry("model", model)?;
73 if let Some(provider) = provider {
74 map.serialize_entry("provider", provider)?;
75 }
76 map.end()
77 }
78 ModelSpec::PinnedWithMatch {
79 model,
80 provider,
81 match_patterns,
82 exclude_patterns,
83 } => {
84 let mut count = 2; if provider.is_some() {
86 count += 1;
87 }
88 if !exclude_patterns.is_empty() {
89 count += 1;
90 }
91 let mut map = serializer.serialize_map(Some(count))?;
92 map.serialize_entry("model", model)?;
93 map.serialize_entry("match", match_patterns)?;
94 if let Some(provider) = provider {
95 map.serialize_entry("provider", provider)?;
96 }
97 if !exclude_patterns.is_empty() {
98 map.serialize_entry("exclude", exclude_patterns)?;
99 }
100 map.end()
101 }
102 ModelSpec::AutoResolve {
103 provider,
104 match_patterns,
105 exclude_patterns,
106 } => {
107 let mut count = 1; if provider.is_some() {
109 count += 1;
110 }
111 if !exclude_patterns.is_empty() {
112 count += 1;
113 }
114 let mut map = serializer.serialize_map(Some(count))?;
115 if let Some(provider) = provider {
116 map.serialize_entry("provider", provider)?;
117 }
118 map.serialize_entry("match", match_patterns)?;
119 if !exclude_patterns.is_empty() {
120 map.serialize_entry("exclude", exclude_patterns)?;
121 }
122 map.end()
123 }
124 }
125 }
126}
127
128#[derive(Debug, Deserialize)]
129struct RawModelAlias {
130 harness: Option<String>,
131 #[serde(default)]
132 description: Option<String>,
133 #[serde(default)]
134 prompting: Option<String>,
135 #[serde(default)]
136 native: Option<toml::Value>,
137 #[serde(default)]
138 default_effort: Option<String>,
139 #[serde(default)]
140 autocompact: Option<toml::Value>,
141 #[serde(default)]
142 autocompact_pct: Option<toml::Value>,
143 #[serde(default)]
144 model: Option<String>,
145 #[serde(default)]
146 provider: Option<String>,
147 #[serde(default, rename = "match")]
148 match_patterns: Option<Vec<String>>,
149 #[serde(default)]
150 exclude: Option<Vec<String>>,
151}
152
153impl<'de> Deserialize<'de> for ModelAlias {
154 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
155 let raw = RawModelAlias::deserialize(deserializer)?;
156 let normalized_harness = if let Some(ref harness_name) = raw.harness {
157 Some(crate::harness::normalize_name(harness_name).ok_or_else(|| {
158 serde::de::Error::custom(format!(
159 "invalid harness '{harness_name}'; valid harnesses: {}",
160 crate::harness::names()
161 ))
162 })?)
163 } else {
164 None
165 };
166 if raw.native.is_some() {
167 return Err(serde::de::Error::custom(
168 "[models.<alias>.native] is no longer supported; Cursor model adaptation is internal",
169 ));
170 }
171 let default_effort = raw
172 .default_effort
173 .filter(|value| !value.trim().is_empty())
174 .map(|effort| {
175 EffortRequest::parse(&effort).ok_or_else(|| {
176 serde::de::Error::custom(format!(
177 "invalid default_effort '{effort}'; accepted values: {}",
178 EffortRequest::ALLOWED
179 ))
180 })
181 })
182 .transpose()?;
183 let autocompact: Option<u32> = match raw.autocompact {
184 Some(toml::Value::Integer(value)) => match u32::try_from(value) {
185 Ok(v) => Some(v),
186 Err(_) => {
187 return Err(serde::de::Error::custom(format!(
188 "autocompact {value} is out of u32 range (0–4294967295)"
189 )));
190 }
191 },
192 Some(other) => {
193 return Err(serde::de::Error::custom(format!(
194 "autocompact must be an integer (token count), got {other:?}"
195 )));
196 }
197 None => None,
198 };
199 let autocompact_pct: Option<u8> = match raw.autocompact_pct {
200 Some(toml::Value::Integer(value)) if (1..=100).contains(&value) => Some(value as u8),
201 Some(toml::Value::Integer(value)) => {
202 return Err(serde::de::Error::custom(format!(
203 "autocompact_pct {value} is out of range 1-100"
204 )));
205 }
206 Some(other) => {
207 return Err(serde::de::Error::custom(format!(
208 "autocompact_pct must be an integer 1-100, got {other:?}"
209 )));
210 }
211 None => None,
212 };
213
214 let has_match = raw.match_patterns.is_some();
215
216 let spec = if let Some(model) = raw.model {
217 if !has_match && raw.exclude.is_some() {
218 return Err(serde::de::Error::custom(
219 "model alias with 'exclude' must also include 'match'",
220 ));
221 }
222 if let Some(match_patterns) = raw.match_patterns {
223 ModelSpec::PinnedWithMatch {
224 model,
225 provider: raw.provider,
226 match_patterns,
227 exclude_patterns: raw.exclude.unwrap_or_default(),
228 }
229 } else {
230 ModelSpec::Pinned {
231 model,
232 provider: raw.provider,
233 }
234 }
235 } else if let Some(match_patterns) = raw.match_patterns {
236 ModelSpec::AutoResolve {
237 provider: raw.provider,
238 match_patterns,
239 exclude_patterns: raw.exclude.unwrap_or_default(),
240 }
241 } else {
242 return Err(serde::de::Error::custom(
243 "model alias must have either 'model' (pinned) or 'match' (auto-resolve)",
244 ));
245 };
246
247 Ok(ModelAlias {
248 harness: normalized_harness,
249 description: raw.description,
250 prompting: raw.prompting,
251 default_effort,
252 autocompact,
253 autocompact_pct,
254 spec,
255 })
256 }
257}
258
259impl ModelAlias {
260 pub fn resolve(&self, rows: &[CachedModel]) -> Option<String> {
263 self.pinned_model_id()
264 .map(str::to_owned)
265 .or_else(|| self.selected(rows).first().map(|row| row.id.clone()))
266 }
267
268 pub fn candidates(&self, rows: &[CachedModel]) -> Vec<String> {
272 let mut ids: Vec<String> = self
273 .pinned_model_id()
274 .map(str::to_owned)
275 .into_iter()
276 .collect();
277 for row in self.selected(rows) {
278 if !ids.contains(&row.id) {
279 ids.push(row.id.clone());
280 }
281 }
282 ids
283 }
284
285 pub fn selected<'a>(&self, rows: &'a [CachedModel]) -> Vec<&'a CachedModel> {
288 match &self.spec {
289 ModelSpec::Pinned { .. } => Vec::new(),
290 ModelSpec::PinnedWithMatch {
291 model,
292 provider,
293 match_patterns,
294 exclude_patterns,
295 } => auto_resolve_all(
296 provider
297 .as_deref()
298 .or_else(|| infer_provider_from_model_id(model)),
299 match_patterns,
300 exclude_patterns,
301 rows,
302 ),
303 ModelSpec::AutoResolve {
304 provider,
305 match_patterns,
306 exclude_patterns,
307 } => auto_resolve_all(provider.as_deref(), match_patterns, exclude_patterns, rows),
308 }
309 }
310}