repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

ai(SMH-PLAN-AIAG0001): ship the reviewed offline catalog with deterministic resolution

212c561fb5e9fff91776d25ac881f13604ea194d

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Model capabilities gate requests before dispatch: unadvertised
tools, thinking, and output limits are rejected with the offending
field path. Alias chains and groups resolve offline into ordered
failover plans; cycles and dangling references fail at load with
sorted, deterministic diagnostics.

Changed files (5)

+442 / −0 text lines

Diff layout

Cargo.lock

Modified

+1 / −0 text lines

513513name = "smith-ai"
514514version = "0.1.0"
515515dependencies = [
516 "serde",
516517 "serde_json",
517518 "smith",

smith-ai/Cargo.toml

Modified

+1 / −0 text lines

1010[dependencies]
1111smith = { path = "../smith" }
12serde = { workspace = true }
1213serde_json = { workspace = true }

smith-ai/src/catalog.json

Added
new file mode 100644

+63 / −0 text lines

1{
2 "models": {
3 "mock-smith": {
4 "id": "mock-smith",
5 "provider": "OpenAiCompatible",
6 "capabilities": {
7 "context_window": 8192,
8 "max_output_tokens": 1024,
9 "input_images": false,
10 "tool_use": true,
11 "thinking": false,
12 "strict_tool_input": false,
13 "cache_control": false
14 }
15 },
16 "claude-sonnet-4-5": {
17 "id": "claude-sonnet-4-5",
18 "provider": "Anthropic",
19 "capabilities": {
20 "context_window": 200000,
21 "max_output_tokens": 16384,
22 "input_images": true,
23 "tool_use": true,
24 "thinking": true,
25 "strict_tool_input": true,
26 "cache_control": true
27 }
28 },
29 "gpt-5.1": {
30 "id": "gpt-5.1",
31 "provider": "OpenAiCompatible",
32 "capabilities": {
33 "context_window": 400000,
34 "max_output_tokens": 128000,
35 "input_images": true,
36 "tool_use": true,
37 "thinking": true,
38 "strict_tool_input": true,
39 "cache_control": false
40 }
41 },
42 "gemini-3-pro": {
43 "id": "gemini-3-pro",
44 "provider": "Google",
45 "capabilities": {
46 "context_window": 1000000,
47 "max_output_tokens": 65536,
48 "input_images": true,
49 "tool_use": true,
50 "thinking": true,
51 "strict_tool_input": false,
52 "cache_control": false
53 }
54 }
55 },
56 "aliases": {
57 "sonnet": "claude-sonnet-4-5",
58 "smart": "claude-sonnet-4-5"
59 },
60 "groups": {
61 "default": ["claude-sonnet-4-5", "gpt-5.1", "gemini-3-pro"]
62 }
63}

smith-ai/src/lib.rs

Modified

+3 / −0 text lines

1313pub mod conformance;
1414/// Google Gemini adapter.
1515pub mod gemini;
16/// Offline model catalog, capabilities, and resolution.
17pub mod models;
1618/// OpenAI-compatible chat-completions adapter.
1719pub mod openai;
1921pub use anthropic::AnthropicDecoder;
2022pub use conformance::{Expected, Fixture, StreamDecoder};
2123pub use gemini::GeminiDecoder;
24pub use models::{Catalog, ModelCapabilities, ModelEntry, ProviderKind};
2225pub use openai::OpenAiDecoder;

smith-ai/src/models.rs

Added
new file mode 100644

+374 / −0 text lines

1//! Offline model catalog, capabilities, and deterministic resolution.
2//!
3//! The reviewed catalog ships as checked-in JSON. Resolution is pure data
4//! navigation with no network: aliases recurse, groups expand to ordered
5//! failover plans, and cycles or dangling references fail at load with the
6//! field path that caused them.
7
8use serde::{Deserialize, Serialize};
9use smith::error::{ProviderFault, Result, SmithError};
10use smith::provider::{ProviderParams, ProviderRequest};
11use std::collections::HashMap;
13/// Which adapter family serves a model.
14#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
15pub enum ProviderKind {
16 /// OpenAI-compatible chat completions.
17 OpenAiCompatible,
18 /// Anthropic Messages.
19 Anthropic,
20 /// Google Gemini.
21 Google,
22 /// Plugin-provided.
23 Plugin,
24}
26/// What a model explicitly supports, used to validate requests.
27#[expect(
28 clippy::struct_excessive_bools,
29 reason = "capabilities are independent advertised switches"
30)]
31#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
32pub struct ModelCapabilities {
33 /// Context window in tokens.
34 pub context_window: u64,
35 /// Output limit in tokens.
36 pub max_output_tokens: u64,
37 /// Accepts image inputs.
38 pub input_images: bool,
39 /// Accepts tool definitions.
40 pub tool_use: bool,
41 /// Supports thinking output.
42 pub thinking: bool,
43 /// Supports strict or grammar-constrained tool input.
44 pub strict_tool_input: bool,
45 /// Supports provider-side prompt caching.
46 pub cache_control: bool,
47}
49/// One catalog model entry.
50#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
51pub struct ModelEntry {
52 /// Model identifier used in requests.
53 pub id: String,
54 /// Adapter family.
55 pub provider: ProviderKind,
56 /// Advertised capabilities.
57 pub capabilities: ModelCapabilities,
58}
60/// A reviewed offline catalog plus its resolution tables.
61#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
62pub struct Catalog {
63 /// Model entries by id.
64 pub models: HashMap<String, ModelEntry>,
65 /// Alias to model id or group name.
66 pub aliases: HashMap<String, String>,
67 /// Group name to ordered member model ids.
68 pub groups: HashMap<String, Vec<String>>,
69}
71/// The reviewed offline catalog, checked in as data.
72const BUILTIN: &str = include_str!("catalog.json");
74impl Catalog {
75 /// Load the built-in reviewed catalog, validating all references.
76 ///
77 /// # Errors
78 ///
79 /// Returns a [`SmithError::Config`] naming the offending field path when
80 /// the data references a missing model, alias, or group, or contains a
81 /// direct alias cycle.
82 pub fn builtin() -> Result<Self> {
83 Self::from_json(BUILTIN)
84 }
86 /// Parse and validate catalog JSON.
87 ///
88 /// # Errors
89 ///
90 /// Same failures as [`Catalog::builtin`].
91 pub fn from_json(json: &str) -> Result<Self> {
92 let catalog: Self =
93 serde_json::from_str(json).map_err(|e| invalid("catalog", &e.to_string()))?;
94 // Deterministic diagnostics: validation walks aliases in sorted order.
95 let mut alias_names: Vec<&String> = catalog.aliases.keys().collect();
96 alias_names.sort();
97 for alias in alias_names {
98 let target = &catalog.aliases[alias];
99 if !catalog.models.contains_key(target)
100 && !catalog.groups.contains_key(target)
101 && !catalog.aliases.contains_key(target)
102 {
103 return Err(invalid(
104 &format!("catalog.aliases.{alias}"),
105 &format!("target '{target}' is neither a model nor a group"),
106 ));
107 }
108 }
109 for (group, members) in &catalog.groups {
110 for (position, member) in members.iter().enumerate() {
111 if !catalog.models.contains_key(member) {
112 return Err(invalid(
113 &format!("catalog.groups.{group}[{position}]"),
114 &format!("member '{member}' is not a model"),
115 ));
116 }
117 }
118 }
119 for alias in &alias_names {
120 catalog.resolve_alias(alias)?;
121 }
122 Ok(catalog)
123 }
125 fn resolve_alias(&self, alias: &str) -> Result<String> {
126 let mut chain = vec![alias.to_string()];
127 let mut current = alias;
128 while let Some(next) = self.aliases.get(current) {
129 if chain.iter().any(|step| step == next) {
130 chain.push(next.clone());
131 return Err(invalid(
132 &format!("catalog.aliases.{alias}"),
133 &format!("alias cycle: {}", chain.join(" -> ")),
134 ));
135 }
136 chain.push(next.clone());
137 current = next;
138 }
139 Ok(current.to_string())
140 }
142 /// Resolve a request target into an ordered failover plan.
143 ///
144 /// A model id resolves to itself; an alias resolves to its referent; a
145 /// group resolves to its members in declared order. Resolution performs
146 /// no network access.
147 ///
148 /// # Errors
149 ///
150 /// Returns a [`SmithError::Config`] naming the target when it is unknown
151 /// or cyclic.
152 pub fn resolve_plan(&self, requested: &str) -> Result<Vec<&ModelEntry>> {
153 let resolved = self.resolve_alias(requested)?;
154 let ids: Vec<&String> = self
155 .groups
156 .get(&resolved)
157 .map_or_else(|| vec![&resolved], |members| members.iter().collect());
158 ids.into_iter()
159 .map(|id| {
160 self.models.get(id).ok_or_else(|| {
161 invalid(
162 &format!("catalog.resolve.{requested}"),
163 &format!("'{id}' is not a model"),
164 )
165 })
166 })
167 .collect()
168 }
170 /// Validate that a request uses only capabilities the model advertises.
171 ///
172 /// # Errors
173 ///
174 /// Returns a [`SmithError::Provider`] with fault
175 /// [`ProviderFault::Invalid`] naming the offending request field when the
176 /// model does not advertise what the request asks for.
177 pub fn validate_request(&self, model: &str, request: &ProviderRequest) -> Result<()> {
178 let entry =
179 self.resolve_plan(model)?.first().copied().ok_or_else(|| {
180 invalid(&format!("catalog.resolve.{model}"), "empty resolution plan")
181 })?;
182 let caps = &entry.capabilities;
183 if !request.tools.is_empty() && !caps.tool_use {
184 return Err(invalid_request(
185 "tools",
186 &format!("{} does not advertise tool use", entry.id),
187 ));
188 }
189 let ProviderParams {
190 max_output_tokens,
191 temperature,
192 thinking,
193 } = request.params;
194 if let Some(requested) = max_output_tokens
195 && requested > caps.max_output_tokens
196 {
197 return Err(invalid_request(
198 "params.max_output_tokens",
199 &format!(
200 "{requested} exceeds the advertised limit of {}",
201 caps.max_output_tokens
202 ),
203 ));
204 }
205 if let Some(requested) = temperature
206 && requested > 2
207 {
208 return Err(invalid_request(
209 "params.temperature",
210 "temperature above 2 is not a valid sampling value",
211 ));
212 }
213 if thinking && !caps.thinking {
214 return Err(invalid_request(
215 "params.thinking",
216 &format!("{} does not advertise thinking", entry.id),
217 ));
218 }
219 Ok(())
220 }
221}
223fn invalid(field: &str, message: &str) -> SmithError {
224 SmithError::Config {
225 field: field.to_string(),
226 message: message.to_string(),
227 }
228}
230fn invalid_request(field: &str, message: &str) -> SmithError {
231 SmithError::Provider {
232 fault: ProviderFault::Invalid {
233 field: Some(field.to_string()),
234 message: message.to_string(),
235 },
236 }
237}
239#[cfg(test)]
240#[expect(clippy::unwrap_used, reason = "catalog tests assert on checked data")]
241mod tests {
242 use super::*;
243 use smith::message::{Message, Role};
244 use smith::provider::ProviderParams;
245 use smith::tool::ToolMetadata;
247 const TEST_CATALOG: &str = r#"{
248 "models": {
249 "mock-smith": {
250 "id": "mock-smith",
251 "provider": "OpenAiCompatible",
252 "capabilities": {
253 "context_window": 8192,
254 "max_output_tokens": 1024,
255 "input_images": false,
256 "tool_use": true,
257 "thinking": false,
258 "strict_tool_input": false,
259 "cache_control": false
260 }
261 },
262 "thinker": {
263 "id": "thinker",
264 "provider": "Anthropic",
265 "capabilities": {
266 "context_window": 200000,
267 "max_output_tokens": 8192,
268 "input_images": true,
269 "tool_use": true,
270 "thinking": true,
271 "strict_tool_input": false,
272 "cache_control": true
273 }
274 }
275 },
276 "aliases": { "smart": "thinker" },
277 "groups": { "default": ["thinker", "mock-smith"] }
278 }"#;
280 #[expect(
281 clippy::unwrap_used,
282 reason = "catalog fixtures are valid by construction"
283 )]
284 fn catalog() -> Catalog {
285 Catalog::from_json(TEST_CATALOG).unwrap()
286 }
288 #[test]
289 fn builtin_catalog_loads_and_resolves() {
290 let catalog = Catalog::builtin().unwrap();
291 let _plan = catalog.resolve_plan("default");
292 // Every builtin id resolves to itself.
293 for id in catalog.models.keys() {
294 assert!(catalog.resolve_plan(id).is_ok(), "id {id}");
295 }
296 }
298 #[test]
299 fn alias_resolves_to_model_and_group_expands_in_order() {
300 let catalog = catalog();
301 let plan = catalog.resolve_plan("smart").unwrap();
302 assert_eq!(plan.len(), 1);
303 assert_eq!(plan[0].id, "thinker");
304 let plan = catalog.resolve_plan("default").unwrap();
305 assert_eq!(
306 plan.iter()
307 .map(|entry| entry.id.as_str())
308 .collect::<Vec<_>>(),
309 vec!["thinker", "mock-smith"]
310 );
311 }
313 #[test]
314 fn unknown_targets_and_cycles_fail_with_field_paths() {
315 let catalog = catalog();
316 let err = catalog.resolve_plan("nope").unwrap_err();
317 assert_eq!(err.code(), "CONFIG");
318 let cyclic = r#"{
319 "models": {},
320 "aliases": { "a": "b", "b": "a" },
321 "groups": {}
322 }"#;
323 let err = Catalog::from_json(cyclic).unwrap_err();
324 assert_eq!(
325 err.to_string(),
326 "config [catalog.aliases.a]: alias cycle: a -> b -> a"
327 );
328 let dangling = r#"{
329 "models": {},
330 "aliases": { "smart": "ghost" },
331 "groups": {}
332 }"#;
333 let err = Catalog::from_json(dangling).unwrap_err();
334 assert!(err.to_string().contains("catalog.aliases.smart"));
335 }
337 #[test]
338 fn requests_cannot_use_unadvertised_capabilities() {
339 let catalog = catalog();
340 let tools = vec![ToolMetadata::new("read", "Read a file")];
341 let mut request =
342 ProviderRequest::new("mock-smith", vec![Message::with_text(Role::User, "hi")])
343 .with_tools(tools);
344 // mock-smith advertises tools: allowed.
345 assert!(catalog.validate_request("mock-smith", &request).is_ok());
346 let tools = vec![ToolMetadata::new("read", "Read a file")];
347 let _ = tools;
348 // Thinking not advertised: rejected with the field path.
349 request.params = ProviderParams {
350 thinking: true,
351 ..ProviderParams::default()
352 };
353 let err = catalog
354 .validate_request("mock-smith", &request)
355 .unwrap_err();
356 assert_eq!(err.code(), "PROVIDER_INVALID");
357 assert!(err.to_string().contains("params.thinking"));
358 // Output limit exceeded: rejected.
359 request.params = ProviderParams {
360 max_output_tokens: Some(999_999),
361 thinking: false,
362 ..ProviderParams::default()
363 };
364 assert!(catalog.validate_request("mock-smith", &request).is_err());
365 // thinker advertises thinking but not an unlimited budget: also rejected.
366 assert!(catalog.validate_request("thinker", &request).is_err());
367 request.params = ProviderParams {
368 max_output_tokens: Some(4096),
369 thinking: true,
370 ..ProviderParams::default()
371 };
372 assert!(catalog.validate_request("thinker", &request).is_ok());
373 }
374}