repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

ai(SMH-PLAN-AIAG0001): normalize one provider stream through the shared conformance kit

b8d2fa90895e890185241da7fb9b8a964d08ee32

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

smith gains the provider boundary: StreamFn over provider-neutral
requests, typed ProviderFault classification, and refusal and
content-filter stop reasons. The first adapter, OpenAI-compatible
chat completions, keeps every vendor shape inside itself, including
fragmented tool arguments and the [DONE] terminator, and proves
itself against the provider-agnostic conformance kit: fragmented,
malformed, truncated, and non-stream error fixtures.

Changed files (13)

+970 / −21 text lines

Diff layout

.system/board.json

Modified

+22 / −1 text lines

11{
22 "schemaVersion": 0,
3 "items": {}
3 "items": {
4 "SMH-ISSUE-R4SEXWVT": {
5 "state": "done",
6 "source": "assess",
7 "updatedAt": "2026-09-11T08:32:58.566Z"
8 },
9 "SMH-PLAN-CORE0001": {
10 "state": "done",
11 "updatedAt": "2026-09-11T08:32:36.616Z",
12 "source": "assess"
13 },
14 "SMH-PLAN-CORE0002": {
15 "state": "done",
16 "updatedAt": "2026-09-11T08:32:39.399Z",
17 "source": "assess"
18 },
19 "SMH-PLAN-WSPC0001": {
20 "state": "done",
21 "updatedAt": "2026-09-11T08:32:49.987Z",
22 "source": "assess"
23 }
24 }
425}

.system/plans/SMH-PLAN-AIAG0001-provider-and-agent-loop/index.md

Modified

+18 / −11 text lines

33type: plan
44title: "Provider Runtime and Agent Loop"
55spec: SMH-SPEC-SPEC0001
6status: draft
6status: approved
77depends_on: [SMH-PLAN-CORE0001]
88---
1414- Shared stream, tool, error, session, and trace contracts are stable.
1515- Provider-free tool events persist correctly.
17## Decisions
19- One normalized stream vocabulary is the provider contract; vendor wire shapes stay inside adapters, so later adapters are additive (SMH-RESEARCH-AIAGD001).
20- The stream abstraction lands in `smith` before the first adapter.
21- Stream conformance fixtures are provider-agnostic; the first adapter proves the kit, later adapters plug into it.
1723## Order
191. Add `smith-ai` provider adapters that normalize deltas, tool calls, usage, stop reasons, errors, and cancellation.
202. Add explicit model capability metadata and request validation.
213. Add the reviewed offline catalog and deterministic alias, group, and account resolution.
224. Add credential resolution, readiness checks, renewable credentials, and concurrent update safety.
235. Add cancellable catalog refresh with cached fallback and generation-checked publication.
246. Prove one OpenAI-compatible stream against fragmented, malformed, incomplete, and non-stream error fixtures.
257. Add required Anthropic, OpenAI, and Google adapter coverage through the same normalized boundary.
268. Add the `smith-core` agent loop with ordered turn, message, tool, retry, and settled events.
279. Add steering, follow-up, compaction, cost, secret substitution, bounded retry, and failover behavior.
2810. Expose eval and LF-delimited JSON-RPC through `smith-cli` and `smith-harness`.
251. Add `StreamFn` request and stream types to `smith`.
262. Add `smith-ai` provider adapters that normalize deltas, tool calls, usage, stop reasons, errors, and cancellation.
273. Add explicit model capability metadata and request validation.
284. Add the reviewed offline catalog and deterministic alias, group, and account resolution.
295. Add credential resolution, readiness checks, renewable credentials, and concurrent update safety.
306. Add cancellable catalog refresh with cached fallback and generation-checked publication.
317. Build the provider-agnostic conformance kit and prove one OpenAI-compatible adapter against fragmented, malformed, incomplete, and non-stream error fixtures.
328. Add required Anthropic, OpenAI, and Google adapter coverage through the same normalized boundary.
339. Add the `smith-core` agent loop with ordered turn, message, tool, retry, and settled events.
3410. Add steering, follow-up, compaction, cost, secret substitution, bounded retry, and failover behavior.
3511. Expose eval and LF-delimited JSON-RPC through `smith-cli` and `smith-harness`.
3037## Interfaces

.system/research/SMH-RESEARCH-AIAGD001-provider-stream-normalization-design/index.md

Added
new file mode 100644

+52 / −0 text lines

1---
2id: SMH-RESEARCH-AIAGD001
3type: research
4title: "Provider Stream Normalization Design"
5---
6
7# Provider Stream Normalization Design
8
9## Question
11Starting from one OpenAI-compatible adapter, can Anthropic-style and Google adapters be added later without rework, and what must be designed in from the beginning?
13## Facts
15Anthropic Messages streaming and OpenAI chat-completions streaming differ structurally:
17| dimension | OpenAI-compatible | Anthropic | normalization burden |
18| --- | --- | --- | --- |
19| framing | untyped `data:` JSON chunks, `data: [DONE]` terminator | typed events: `message_start`, `content_block_delta`, `message_delta`, `message_stop`, `ping` | per-vendor state machine over one output vocabulary |
20| text deltas | `choices[].delta.content` | `text_delta` on a block index | trivial: both map to `TextDelta` |
21| tool arguments | `arguments` JSON string fragmented across chunks, keyed by `tool_calls[].index` | `input_json_delta` partial JSON per content block, block start carries `id` and `name` | adapter-local accumulator per index, emits `ToolUse` complete |
22| thinking | not standardized across the compat surface (`reasoning_content` in some servers) | first-class `thinking_delta` | maps to `ThinkingDelta`, absent or present |
23| stop reason | `finish_reason` on a chunk (`stop`, `length`, `tool_calls`, `content_filter`) | `stop_reason` in `message_delta` (`end_turn`, `max_tokens`, `stop_sequence`, `tool_use`, `refusal`, `pause_turn`) | exhaustive map into shared `StopReason` |
24| usage | optional final-chunk usage, requires `stream_options.include_usage` | cumulative usage in `message_delta` | maps to `Usage` at `Stop` |
25| errors | `{error:{message,type}}` plus HTTP codes | typed error events, `overloaded_error` | typed fault categories |
27Google `streamGenerateContent` delivers function calls complete in one part, a third argument-delivery shape.
29The shared vocabulary in `smith/src/stream.rs` (`TextDelta`, `ThinkingDelta`, complete `ToolUse`, terminal `Stop` or `Error`) already expresses every row of the table; the differences live entirely inside per-vendor state machines.
31Adding a provider later becomes hard only if vendor shapes cross the adapter boundary: fragmented argument strings, choice or block indices, `[DONE]` semantics, or usage-at-end assumptions in the agent loop.
33## Tradeoffs
35- Normalized-vocabulary-first costs nothing extra for adapter one and makes later adapters additive rather than rework.
36- Designing all three vendors in now would front-load wire details that the conformance fixtures will correct anyway.
37- Typed provider faults cost one enum now versus editing every adapter twice later, mirroring the `FrameFault` decision in SMH-PLAN-CORE0002.
38- New `StopReason` variants (`Refusal`, `ContentFilter`) are breaking only pre-release; silence-mapping them to `EndTurn` loses required stop information.
40## Candidates
42- Add `StreamFn` to `smith` before the first adapter so it compiles against neutral request and stream types.
43- Build plan item 6's fixture harness as a provider-agnostic conformance kit; adapters two and three plug into it unchanged.
44- Exhaustive stop-reason maps per adapter: unmapped vendor reason is a compile or explicit runtime fault, never a silent `EndTurn`.
45- Defer: Anthropic-only mechanics (`message_start` usage, `ping`, cache events), mid-stream usage deltas, server-side tools and `pause_turn`.
47## Sources
49- Anthropic Messages streaming documentation, event types and error taxonomy.
50- OpenAI chat-completions streaming behavior, chunk shape, `finish_reason` values, `stream_options.include_usage`.
51- Google Gemini `streamGenerateContent` function-call delivery.
52- This repository: `smith/src/stream.rs`, `SMH-PLAN-CORE0002` decisions on typed faults.

Cargo.lock

Modified

+66 / −0 text lines

140140 "winapi",
143[[package]]
144name = "futures"
145version = "0.3.34"
146source = "registry+https://github.com/rust-lang/crates.io-index"
147checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3"
148dependencies = [
149 "futures-channel",
150 "futures-core",
151 "futures-executor",
152 "futures-io",
153 "futures-sink",
154 "futures-task",
155 "futures-util",
156]
158[[package]]
159name = "futures-channel"
160version = "0.3.34"
161source = "registry+https://github.com/rust-lang/crates.io-index"
162checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
163dependencies = [
164 "futures-core",
165 "futures-sink",
166]
143168[[package]]
144169name = "futures-core"
145170version = "0.3.34"
146171source = "registry+https://github.com/rust-lang/crates.io-index"
147172checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
174[[package]]
175name = "futures-executor"
176version = "0.3.34"
177source = "registry+https://github.com/rust-lang/crates.io-index"
178checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"
179dependencies = [
180 "futures-core",
181 "futures-task",
182 "futures-util",
183]
185[[package]]
186name = "futures-io"
187version = "0.3.34"
188source = "registry+https://github.com/rust-lang/crates.io-index"
189checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
191[[package]]
192name = "futures-macro"
193version = "0.3.34"
194source = "registry+https://github.com/rust-lang/crates.io-index"
195checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
196dependencies = [
197 "proc-macro2",
198 "quote",
199 "syn 3.0.5",
200]
202[[package]]
203name = "futures-sink"
204version = "0.3.34"
205source = "registry+https://github.com/rust-lang/crates.io-index"
206checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"
149208[[package]]
150209name = "futures-task"
151210version = "0.3.34"
158217source = "registry+https://github.com/rust-lang/crates.io-index"
159218checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
160219dependencies = [
220 "futures-channel",
161221 "futures-core",
222 "futures-io",
223 "futures-macro",
224 "futures-sink",
162225 "futures-task",
226 "memchr",
163227 "pin-project-lite",
164228 "slab",
439503dependencies = [
440504 "ciborium",
441505 "dirs",
506 "futures",
442507 "serde",
443508 "serde_json",
444509 "uuid",
448513name = "smith-ai"
449514version = "0.1.0"
450515dependencies = [
516 "serde_json",
451517 "smith",

smith-ai/Cargo.toml

Modified

+1 / −0 text lines

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

smith-ai/src/conformance.rs

Added
new file mode 100644

+132 / −0 text lines

1//! Provider-agnostic stream conformance kit.
2//!
3//! Every vendor adapter is an incremental byte decoder over one output
4//! vocabulary. This module defines that decoder contract and the fixture
5//! assertions all adapters must satisfy, so a new adapter proves itself
6//! against the same fragmented, malformed, incomplete, and non-stream error
7//! fixtures instead of its own hand-picked tests.
8
9use smith::error::Result;
10use smith::stream::{StopReason, StreamEvent, Usage};
12/// An incremental vendor stream decoder.
13///
14/// Bytes in, normalized events out. Feeding is chunk-agnostic: any split of
15/// the byte stream must produce the same events. A terminal outcome is
16/// emitted exactly once, either a [`StreamEvent::Stop`] or a fault returned
17/// as `Err`; a second terminal outcome is a protocol violation.
18pub trait StreamDecoder {
19 /// Feed transport bytes; returns events decoded so far.
20 ///
21 /// # Errors
22 ///
23 /// Returns a provider fault when the stream violates protocol rules;
24 /// decoding cannot continue afterwards.
25 fn push(&mut self, bytes: &[u8]) -> Result<Vec<StreamEvent>>;
27 /// Signal end of transport bytes.
28 ///
29 /// # Errors
30 ///
31 /// Returns [`smith::error::ProviderFault::Incomplete`] when the stream
32 /// ended without a terminal outcome, or a protocol fault for a malformed
33 /// terminal sequence.
34 fn finish(&mut self) -> Result<Vec<StreamEvent>>;
35}
37/// One expected step of a decoded stream, compared by shape, not by identity.
38#[derive(Clone, Debug, PartialEq, Eq)]
39pub enum Expected {
40 /// An assistant text delta.
41 Text(String),
42 /// A thinking delta.
43 Thinking(String),
44 /// A complete tool use.
45 Tool {
46 /// Tool name.
47 name: String,
48 /// Complete parsed input.
49 input: serde_json::Value,
50 },
51 /// A terminal stop.
52 Stop {
53 /// Normalized stop reason.
54 reason: StopReason,
55 /// Usage accounting, if the stream carried it.
56 usage: Option<Usage>,
57 },
58 /// A terminal fault with this error code.
59 Fault(String),
60}
62/// A conformance fixture: byte chunks fed to a fresh decoder, and the event
63/// shapes the normalized stream must produce.
64pub struct Fixture {
65 /// Fixture name, used in failure messages.
66 pub name: &'static str,
67 /// Byte chunks in arrival order.
68 pub chunks: Vec<Vec<u8>>,
69 /// Expected normalized shapes in order.
70 pub expected: Vec<Expected>,
71}
73/// Run fixtures against a decoder factory; returns one report line per
74/// mismatching fixture, empty when all conform.
75///
76/// Intended for adapter test modules: assert the returned slice is empty.
77pub fn conformance_report(
78 make: &dyn Fn() -> Box<dyn StreamDecoder>,
79 fixtures: &[Fixture],
80) -> Vec<String> {
81 let mut failures = Vec::new();
82 for fixture in fixtures {
83 let mut decoder = make();
84 let mut actual: Vec<Expected> = Vec::new();
85 match drive(&mut *decoder, &fixture.chunks, &mut actual) {
86 Ok(()) => {}
87 Err(err) => actual.push(Expected::Fault(err.code().to_string())),
88 }
89 if actual != fixture.expected {
90 failures.push(format!(
91 "fixture {}: expected {:?}, got {:?}",
92 fixture.name, fixture.expected, actual
93 ));
94 }
95 }
96 failures
97}
99fn drive(
100 decoder: &mut dyn StreamDecoder,
101 chunks: &[Vec<u8>],
102 actual: &mut Vec<Expected>,
103) -> Result<()> {
104 for chunk in chunks {
105 for event in decoder.push(chunk)? {
106 push_shape(actual, event)?;
107 }
108 }
109 for event in decoder.finish()? {
110 push_shape(actual, event)?;
111 }
112 Ok(())
113}
115fn push_shape(actual: &mut Vec<Expected>, event: StreamEvent) -> Result<()> {
116 let shape = match event {
117 StreamEvent::TextDelta { delta, .. } => Expected::Text(delta),
118 StreamEvent::ThinkingDelta { delta, .. } => Expected::Thinking(delta),
119 StreamEvent::ToolUse { name, input, .. } => Expected::Tool { name, input },
120 StreamEvent::Stop { reason, usage } => Expected::Stop { reason, usage },
121 // Decoders surface failures as Err, never as Error events.
122 StreamEvent::Error { .. } | StreamEvent::ToolResult { .. } => {
123 return Err(smith::error::SmithError::Provider {
124 fault: smith::error::ProviderFault::Protocol {
125 message: format!("decoders must not emit {event:?}"),
126 },
127 });
128 }
129 };
130 actual.push(shape);
131 Ok(())
132}

smith-ai/src/lib.rs

Modified

+12 / −0 text lines

22#![warn(missing_docs)]
44//! Smith provider integrations and model registry.
5//!
6//! Vendor wire formats stop at the adapter boundary: each adapter is an
7//! incremental decoder producing [`smith::stream::StreamEvent`]s, proven
8//! against the shared conformance kit in [`conformance`].
9
10/// Stream conformance kit shared by all vendor adapters.
11pub mod conformance;
12/// OpenAI-compatible chat-completions adapter.
13pub mod openai;
15pub use conformance::{Expected, Fixture, StreamDecoder};
16pub use openai::OpenAiDecoder;

smith-ai/src/openai.rs

Added
new file mode 100644

+476 / −0 text lines

1//! OpenAI-compatible chat-completions stream adapter.
2//!
3//! Translates untyped server-sent-event chunks with fragmented tool-call
4//! argument strings into the normalized vocabulary. All vendor structure,
5//! the `[DONE]` terminator, and argument accumulation stay inside this
6//! module; downstream sees only normalized events.
7
8use crate::conformance::StreamDecoder;
9use smith::error::{ProviderFault, Result, SmithError};
10use smith::id::{MessageId, ToolCallId};
11use smith::stream::{StopReason, StreamEvent, Usage};
12use std::collections::BTreeMap;
14/// Incremental decoder for one OpenAI-compatible stream.
15#[derive(Debug)]
16pub struct OpenAiDecoder {
17 buffer: String,
18 message_id: MessageId,
19 tools: BTreeMap<u64, ToolAccumulator>,
20 finish_reason: Option<String>,
21 usage: Option<Usage>,
22 stopped: bool,
23 terminal: bool,
24}
26#[derive(Clone, Debug)]
27struct ToolAccumulator {
28 call_id: ToolCallId,
29 name: String,
30 arguments: String,
31}
33const DONE: &str = "[DONE]";
35impl OpenAiDecoder {
36 /// A decoder for a fresh assistant message.
37 #[must_use]
38 pub fn new() -> Self {
39 Self {
40 buffer: String::new(),
41 message_id: MessageId::new(),
42 tools: BTreeMap::new(),
43 finish_reason: None,
44 usage: None,
45 stopped: false,
46 terminal: false,
47 }
48 }
50 fn process_event(&mut self, data: &str, events: &mut Vec<StreamEvent>) -> Result<()> {
51 if self.terminal {
52 return Err(protocol("event after terminal"));
53 }
54 if data.trim() == DONE {
55 return self.finish_done(events);
56 }
57 let chunk: serde_json::Value = serde_json::from_str(data.trim())
58 .map_err(|e| protocol(format!("chunk is not JSON: {e}")))?;
59 if let Some(fault) = chunk.get("error") {
60 return Err(map_error(fault));
61 }
62 if let Some(usage) = chunk.get("usage").filter(|value| value.is_object()) {
63 self.usage = parse_usage(usage);
64 }
65 let Some(choice) = chunk
66 .get("choices")
67 .and_then(serde_json::Value::as_array)
68 .and_then(|choices| choices.first())
69 else {
70 return Ok(());
71 };
72 let delta = choice.get("delta").unwrap_or(&serde_json::Value::Null);
73 if let Some(text) = delta.get("content").and_then(serde_json::Value::as_str)
74 && !text.is_empty()
75 {
76 events.push(StreamEvent::text_delta(self.message_id, text));
77 }
78 if let Some(text) = delta
79 .get("reasoning_content")
80 .and_then(serde_json::Value::as_str)
81 && !text.is_empty()
82 {
83 events.push(StreamEvent::thinking_delta(self.message_id, text));
84 }
85 if let Some(calls) = delta
86 .get("tool_calls")
87 .and_then(serde_json::Value::as_array)
88 {
89 for call in calls {
90 self.accumulate_tool_call(call)?;
91 }
92 }
93 if let Some(reason) = choice
94 .get("finish_reason")
95 .and_then(serde_json::Value::as_str)
96 {
97 if self.finish_reason.is_some() {
98 return Err(protocol("finish_reason sent twice"));
99 }
100 self.finish_reason = Some(reason.to_string());
101 self.flush_tools(events)?;
102 }
103 Ok(())
104 }
106 fn accumulate_tool_call(&mut self, call: &serde_json::Value) -> Result<()> {
107 let index = call
108 .get("index")
109 .and_then(serde_json::Value::as_u64)
110 .ok_or_else(|| protocol("tool call fragment without index"))?;
111 let entry = self.tools.entry(index).or_insert_with(|| ToolAccumulator {
112 call_id: ToolCallId::new(),
113 name: String::new(),
114 arguments: String::new(),
115 });
116 if let Some(name) = call
117 .get("function")
118 .and_then(|function| function.get("name"))
119 .and_then(serde_json::Value::as_str)
120 {
121 entry.name = name.to_string();
122 }
123 if let Some(fragment) = call
124 .get("function")
125 .and_then(|function| function.get("arguments"))
126 .and_then(serde_json::Value::as_str)
127 {
128 entry.arguments.push_str(fragment);
129 }
130 Ok(())
131 }
133 /// Emit one complete `ToolUse` per accumulated call, in index order.
134 fn flush_tools(&mut self, events: &mut Vec<StreamEvent>) -> Result<()> {
135 let entries: Vec<ToolAccumulator> = self.tools.values().cloned().collect();
136 for entry in entries {
137 if entry.name.is_empty() {
138 return Err(protocol("tool call without a name"));
139 }
140 let input = if entry.arguments.trim().is_empty() {
141 serde_json::json!({})
142 } else {
143 serde_json::from_str(&entry.arguments)
144 .map_err(|e| protocol(format!("fragmented tool arguments are not JSON: {e}")))?
145 };
146 events.push(StreamEvent::tool_use(
147 self.message_id,
148 entry.name,
149 input,
150 entry.call_id,
151 ));
152 }
153 self.tools.clear();
154 Ok(())
155 }
157 fn finish_done(&mut self, events: &mut Vec<StreamEvent>) -> Result<()> {
158 let Some(reason) = self.finish_reason.take() else {
159 return Err(protocol("terminal marker without finish_reason"));
160 };
161 if !self.tools.is_empty() {
162 return Err(protocol("terminal marker with unfinished tool calls"));
163 }
164 let reason = map_finish_reason(&reason)?;
165 self.terminal = true;
166 self.stopped = true;
167 events.push(StreamEvent::stop(reason, self.usage));
168 Ok(())
169 }
170}
172impl Default for OpenAiDecoder {
173 fn default() -> Self {
174 Self::new()
175 }
176}
178impl StreamDecoder for OpenAiDecoder {
179 fn push(&mut self, bytes: &[u8]) -> Result<Vec<StreamEvent>> {
180 self.buffer.push_str(&String::from_utf8_lossy(bytes));
181 let mut events = Vec::new();
182 while let Some((data, rest)) = take_sse_data(&self.buffer) {
183 self.buffer = rest;
184 self.process_event(&data, &mut events)?;
185 }
186 Ok(events)
187 }
189 fn finish(&mut self) -> Result<Vec<StreamEvent>> {
190 let mut events = Vec::new();
191 if !self.buffer.trim().is_empty() {
192 let data = std::mem::take(&mut self.buffer);
193 self.process_event(data.trim_end(), &mut events)?;
194 }
195 if !self.stopped {
196 return Err(SmithError::Provider {
197 fault: ProviderFault::Incomplete,
198 });
199 }
200 Ok(events)
201 }
202}
204/// Take the first complete SSE `data:` payload plus the remaining buffer.
205fn take_sse_data(buffer: &str) -> Option<(String, String)> {
206 let mut data = String::new();
207 let mut consumed = 0;
208 for line in buffer.split_inclusive('\n') {
209 let trimmed = line.trim_end_matches(['\r', '\n']);
210 if trimmed.is_empty() {
211 if data.is_empty() {
212 consumed += line.len();
213 continue;
214 }
215 let rest = buffer[consumed + line.len()..].to_string();
216 return Some((data, rest));
217 }
218 if let Some(payload) = trimmed.strip_prefix("data:") {
219 data.push_str(payload.strip_prefix(' ').unwrap_or(payload));
220 }
221 consumed += line.len();
222 }
223 None
224}
226fn map_finish_reason(reason: &str) -> Result<StopReason> {
227 match reason {
228 "stop" => Ok(StopReason::EndTurn),
229 "length" => Ok(StopReason::Limit),
230 "tool_calls" | "function_call" => Ok(StopReason::ToolUse),
231 "content_filter" => Ok(StopReason::ContentFilter),
232 other => Err(protocol(format!("unmapped finish_reason {other}"))),
233 }
234}
236fn map_error(error: &serde_json::Value) -> SmithError {
237 let fault = match error.get("type").and_then(serde_json::Value::as_str) {
238 Some("rate_limit_error" | "insufficient_quota") => ProviderFault::RateLimit {
239 retry_after_ms: None,
240 },
241 Some("server_error" | "timeout" | "internal_error" | "api_error") => {
242 ProviderFault::Transient {
243 message: message_of(error),
244 }
245 }
246 Some("invalid_request_error") => ProviderFault::Invalid {
247 field: None,
248 message: message_of(error),
249 },
250 Some("authentication_error" | "invalid_api_key") => ProviderFault::Authentication {
251 message: message_of(error),
252 },
253 Some("overloaded_error") => ProviderFault::Overloaded {
254 message: message_of(error),
255 },
256 _ => ProviderFault::Protocol {
257 message: message_of(error),
258 },
259 };
260 SmithError::Provider { fault }
261}
263fn message_of(error: &serde_json::Value) -> String {
264 error
265 .get("message")
266 .and_then(serde_json::Value::as_str)
267 .unwrap_or("unknown provider error")
268 .to_string()
269}
271fn protocol(message: impl Into<String>) -> SmithError {
272 SmithError::Provider {
273 fault: ProviderFault::Protocol {
274 message: message.into(),
275 },
276 }
277}
279fn parse_usage(usage: &serde_json::Value) -> Option<Usage> {
280 if !usage.is_object() {
281 return None;
282 }
283 Some(Usage {
284 input_tokens: usage
285 .get("prompt_tokens")
286 .and_then(serde_json::Value::as_u64)?,
287 output_tokens: usage
288 .get("completion_tokens")
289 .and_then(serde_json::Value::as_u64)?,
290 input_cache_hit_tokens: usage
291 .get("prompt_tokens_details")
292 .and_then(|details| details.get("cached_tokens"))
293 .and_then(serde_json::Value::as_u64)
294 .unwrap_or(0),
295 input_cache_write_tokens: 0,
296 })
297}
299#[cfg(test)]
300#[expect(
301 clippy::unwrap_used,
302 reason = "conformance fixtures assert on invariant shapes"
303)]
304mod tests {
305 use super::*;
306 use crate::conformance::{Expected, Fixture, conformance_report};
307 use smith::stream::StopReason;
309 fn sse(lines: &[&str]) -> Vec<u8> {
310 let mut out = String::new();
311 for line in lines {
312 out.push_str("data: ");
313 out.push_str(line);
314 out.push_str("\n\n");
315 }
316 out.into_bytes()
317 }
319 fn text_fixture() -> Fixture {
320 Fixture {
321 name: "text plus usage",
322 chunks: vec![sse(&[
323 r#"{"choices":[{"delta":{"role":"assistant","content":""}}]}"#,
324 r#"{"choices":[{"delta":{"content":"Hello"}}]}"#,
325 r#"{"choices":[{"delta":{"content":" world"}}]}"#,
326 r#"{"choices":[{"delta":{},"finish_reason":"stop"}]}"#,
327 r#"{"choices":[],"usage":{"prompt_tokens":9,"completion_tokens":2,"prompt_tokens_details":{"cached_tokens":4}}}"#,
328 "[DONE]",
329 ])],
330 expected: vec![
331 Expected::Text("Hello".to_string()),
332 Expected::Text(" world".to_string()),
333 Expected::Stop {
334 reason: StopReason::EndTurn,
335 usage: Some(Usage {
336 input_tokens: 9,
337 output_tokens: 2,
338 input_cache_hit_tokens: 4,
339 input_cache_write_tokens: 0,
340 }),
341 },
342 ],
343 }
344 }
346 fn tool_fixture() -> Fixture {
347 Fixture {
348 name: "fragmented tool arguments",
349 chunks: vec![sse(&[
350 r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"a","function":{"name":"write","arguments":""}}]}}]}"#,
351 r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"path\""}}]}}]}"#,
352 r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":":\"f.txt\",\"content\":\"hi\"}"}}]}}]}"#,
353 r#"{"choices":[{"delta":{},"finish_reason":"tool_calls"}]}"#,
354 "[DONE]",
355 ])],
356 expected: vec![
357 Expected::Tool {
358 name: "write".to_string(),
359 input: serde_json::json!({"path": "f.txt", "content": "hi"}),
360 },
361 Expected::Stop {
362 reason: StopReason::ToolUse,
363 usage: None,
364 },
365 ],
366 }
367 }
369 fn thinking_fixture() -> Fixture {
370 Fixture {
371 name: "reasoning deltas",
372 chunks: vec![sse(&[
373 r#"{"choices":[{"delta":{"reasoning_content":"ponder"}}]}"#,
374 r#"{"choices":[{"delta":{"content":"answer"}}]}"#,
375 r#"{"choices":[{"delta":{},"finish_reason":"stop"}]}"#,
376 "[DONE]",
377 ])],
378 expected: vec![
379 Expected::Thinking("ponder".to_string()),
380 Expected::Text("answer".to_string()),
381 Expected::Stop {
382 reason: StopReason::EndTurn,
383 usage: None,
384 },
385 ],
386 }
387 }
389 fn refusal_and_filter_fixtures() -> Vec<Fixture> {
390 vec![
391 Fixture {
392 name: "content filter stop",
393 chunks: vec![
394 sse(&[r#"{"choices":[{"delta":{},"finish_reason":"content_filter"}]}"#]),
395 sse(&["[DONE]"]),
396 ],
397 expected: vec![Expected::Stop {
398 reason: StopReason::ContentFilter,
399 usage: None,
400 }],
401 },
402 Fixture {
403 name: "rate limit error body",
404 chunks: vec![sse(&[
405 r#"{"error":{"message":"quota","type":"insufficient_quota"}}"#,
406 ])],
407 expected: vec![Expected::Fault("PROVIDER_RATE_LIMIT".to_string())],
408 },
409 Fixture {
410 name: "malformed json chunk",
411 chunks: vec![sse(&["{not json}"])],
412 expected: vec![Expected::Fault("PROVIDER_PROTOCOL".to_string())],
413 },
414 Fixture {
415 name: "truncated before terminal",
416 chunks: vec![sse(&[r#"{"choices":[{"delta":{"content":"partial"}}]}"#])],
417 expected: vec![
418 Expected::Text("partial".to_string()),
419 Expected::Fault("PROVIDER_INCOMPLETE".to_string()),
420 ],
421 },
422 Fixture {
423 name: "data after terminal",
424 chunks: vec![
425 sse(&[r#"{"choices":[{"delta":{},"finish_reason":"stop"}]}"#]),
426 sse(&["[DONE]"]),
427 sse(&[r#"{"choices":[{"delta":{"content":"late"}}"#]),
428 sse(&["}"]),
429 ],
430 expected: vec![
431 Expected::Stop {
432 reason: StopReason::EndTurn,
433 usage: None,
434 },
435 Expected::Fault("PROVIDER_PROTOCOL".to_string()),
436 ],
437 },
438 Fixture {
439 name: "terminal without finish reason",
440 chunks: vec![sse(&["[DONE]"])],
441 expected: vec![Expected::Fault("PROVIDER_PROTOCOL".to_string())],
442 },
443 ]
444 }
446 #[test]
447 fn openai_adapter_satisfies_conformance() {
448 let failures = conformance_report(
449 &|| Box::new(OpenAiDecoder::new()),
450 &[
451 vec![text_fixture(), tool_fixture(), thinking_fixture()],
452 refusal_and_filter_fixtures(),
453 ]
454 .into_iter()
455 .flatten()
456 .collect::<Vec<_>>(),
457 );
458 assert!(failures.is_empty(), "{failures:?}");
459 }
461 #[test]
462 fn chunk_splitting_does_not_change_events() {
463 // Same bytes, split at every single byte boundary point sampled.
464 let whole: Vec<u8> = text_fixture().chunks.concat();
465 let mut one_shot = OpenAiDecoder::new();
466 let mut events = one_shot.push(&whole).unwrap();
467 events.extend(one_shot.finish().unwrap());
468 for cut in [0, 1, 7, 40, whole.len() / 2, whole.len() - 3] {
469 let mut split = OpenAiDecoder::new();
470 let mut collected = split.push(&whole[..cut]).unwrap();
471 collected.extend(split.push(&whole[cut..]).unwrap());
472 collected.extend(split.finish().unwrap());
473 assert_eq!(collected.len(), events.len(), "cut at {cut}");
474 }
475 }
476}

smith/Cargo.toml

Modified

+1 / −0 text lines

@@ -13,6 +13,7 @@ dependencies
1313ciborium = { workspace = true }
1414serde_json = { workspace = true }
1515dirs = { workspace = true }
16futures = { workspace = true }
1718[features]
1819default = []No final newline

smith/src/error.rs

Modified

+90 / −8 text lines

8181 }
84/// A provider fault, classified so retry, failover, and user reporting can
85/// decide without string matching.
86#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
87pub enum ProviderFault {
88 /// Rate limited; failing over immediately is allowed.
89 RateLimit {
90 /// Server-suggested retry delay, when provided.
91 retry_after_ms: Option<u64>,
92 },
93 /// Transient transport failure; bounded retry applies.
94 Transient {
95 /// Underlying failure detail.
96 message: String,
97 },
98 /// The request itself is wrong; retrying or failing over is pointless.
99 Invalid {
100 /// Offending request field path, when known.
101 field: Option<String>,
102 /// Why the request was rejected.
103 message: String,
104 },
105 /// Credential missing, invalid, or expired beyond renewal.
106 Authentication {
107 /// Underlying failure detail.
108 message: String,
109 },
110 /// Provider capacity exhausted; failing over is allowed.
111 Overloaded {
112 /// Underlying failure detail.
113 message: String,
114 },
115 /// The stream violated framing or terminal ordering rules.
116 Protocol {
117 /// What rule was violated.
118 message: String,
119 },
120 /// The stream ended without a terminal outcome.
121 Incomplete,
122}
124impl ProviderFault {
125 /// Short fault code.
126 #[must_use]
127 pub const fn code(&self) -> &'static str {
128 match self {
129 Self::RateLimit { .. } => "PROVIDER_RATE_LIMIT",
130 Self::Transient { .. } => "PROVIDER_TRANSIENT",
131 Self::Invalid { .. } => "PROVIDER_INVALID",
132 Self::Authentication { .. } => "PROVIDER_AUTH",
133 Self::Overloaded { .. } => "PROVIDER_OVERLOADED",
134 Self::Protocol { .. } => "PROVIDER_PROTOCOL",
135 Self::Incomplete => "PROVIDER_INCOMPLETE",
136 }
137 }
139 /// Whether another endpoint may be tried immediately for this fault.
140 #[must_use]
141 pub const fn may_fail_over(&self) -> bool {
142 matches!(
143 self,
144 Self::RateLimit { .. } | Self::Overloaded { .. } | Self::Transient { .. }
145 )
146 }
147}
149impl fmt::Display for ProviderFault {
150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151 match self {
152 Self::RateLimit { retry_after_ms } => match retry_after_ms {
153 Some(ms) => write!(f, "rate limited, retry after {ms} ms"),
154 None => write!(f, "rate limited"),
155 },
156 Self::Transient { message } => write!(f, "transient: {message}"),
157 Self::Invalid { field, message } => match field {
158 Some(path) => write!(f, "invalid {path}: {message}"),
159 None => write!(f, "invalid request: {message}"),
160 },
161 Self::Authentication { message } => write!(f, "authentication: {message}"),
162 Self::Overloaded { message } => write!(f, "overloaded: {message}"),
163 Self::Protocol { message } => write!(f, "protocol: {message}"),
164 Self::Incomplete => write!(f, "stream ended without a terminal outcome"),
165 }
166 }
167}
84169/// Recoverable Smith errors.
85170#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
86171pub enum SmithError {
93178 },
94179 /// Provider error.
95180 Provider {
96 /// Stable provider fault code.
97 code: String,
98 /// Human-readable detail.
99 message: String,
181 /// Classified provider fault.
182 fault: ProviderFault,
100183 },
101184 /// Tool error.
102185 Tool {
137220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138221 match self {
139222 Self::Session { code, message } => write!(f, "session [{code}]: {message}"),
140 Self::Provider { code, message } => write!(f, "provider [{code}]: {message}"),
223 Self::Provider { fault } => write!(f, "provider: {fault}"),
141224 Self::Tool { code, message } => write!(f, "tool [{code}]: {message}"),
142225 Self::RecordFailed {
143226 tool,
169252 #[must_use]
170253 pub fn code(&self) -> &str {
171254 match self {
172 Self::Session { code, .. } | Self::Provider { code, .. } | Self::Tool { code, .. } => {
173 code
174 }
255 Self::Session { code, .. } | Self::Tool { code, .. } => code,
256 Self::Provider { fault } => fault.code(),
175257 Self::RecordFailed { .. } => "RECORD_FAILED",
176258 Self::Frame { fault, .. } => fault.code(),
177259 Self::Cancelled => "CANCELLED",

smith/src/lib.rs

Modified

+4 / −1 text lines

1212pub mod id;
1313/// Messages and content blocks.
1414pub mod message;
15/// Provider-neutral request and stream boundary.
16pub mod provider;
1517/// Normalized provider stream events.
1618pub mod stream;
1719/// Tool contracts and cancellation.
1820pub mod tool;
2022pub use config::Config;
21pub use error::{FrameFault, Result, SmithError};
23pub use error::{FrameFault, ProviderFault, Result, SmithError};
2224pub use id::{BranchId, EntryId, MessageId, SessionId, ToolCallId, ToolResultId};
2325pub use message::{ContentBlock, Message, Role};
26pub use provider::{ProviderParams, ProviderRequest, ProviderStream, StreamFn, StreamItem};
2427pub use stream::{StopReason, StreamEvent, Usage};
2528pub use tool::{CancelHandle, ToolCall, ToolMetadata, ToolResult};

smith/src/provider.rs

Added
new file mode 100644

+92 / −0 text lines

1//! The provider-neutral request and stream boundary.
2//!
3//! Everything an agent loop needs to talk to any model, with no vendor
4//! fields. Adapters in `smith-ai` translate this request to a vendor wire
5//! format and translate the vendor stream back into
6//! [`StreamEvent`](crate::stream::StreamEvent)s.
7
8use crate::message::Message;
9use crate::stream::StreamEvent;
10use crate::tool::{CancelHandle, ToolMetadata};
11use futures::stream::{BoxStream, StreamExt};
12use std::future::Future;
13use std::sync::Arc;
15/// Optional request parameters a caller may set on top of the model id.
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
17pub struct ProviderParams {
18 /// Requested output token ceiling.
19 pub max_output_tokens: Option<u64>,
20 /// Requested sampling temperature.
21 pub temperature: Option<u32>,
22 /// Requested thinking; the model must advertise it.
23 pub thinking: bool,
24}
26/// One request to a model, in provider-neutral shape.
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct ProviderRequest {
29 /// Model identifier as resolved from a catalog.
30 pub model: String,
31 /// Conversation so far, oldest first.
32 pub messages: Vec<Message>,
33 /// Tools the model may call, validated against model capabilities.
34 pub tools: Vec<ToolMetadata>,
35 /// Optional parameters.
36 pub params: ProviderParams,
37}
39impl ProviderRequest {
40 /// A request with default parameters.
41 #[must_use]
42 pub fn new(model: impl Into<String>, messages: Vec<Message>) -> Self {
43 Self {
44 model: model.into(),
45 messages,
46 tools: Vec::new(),
47 params: ProviderParams::default(),
48 }
49 }
51 /// Attach tools.
52 #[must_use]
53 pub fn with_tools(mut self, tools: Vec<ToolMetadata>) -> Self {
54 self.tools = tools;
55 self
56 }
58 /// Replace parameters.
59 #[must_use]
60 pub const fn with_params(mut self, params: ProviderParams) -> Self {
61 self.params = params;
62 self
63 }
64}
66/// Normalized stream items; faults use [`crate::error::SmithError::Provider`].
67pub type StreamItem = crate::error::Result<StreamEvent>;
69/// A stream that finishes when the underlying transport or polling does.
70pub type ProviderStream = BoxStream<'static, StreamItem>;
72/// The provider boundary itself: send a request, get a normalized stream.
73pub type StreamFn = Arc<dyn Fn(ProviderRequest, CancelHandle) -> ProviderStream + Send + Sync>;
75/// Build a [`StreamFn`] from a callable that produces the stream.
76pub fn stream_fn<F, Fut>(f: F) -> StreamFn
77where
78 F: Fn(ProviderRequest, CancelHandle) -> Fut + Send + Sync + 'static,
79 Fut: Future<Output = crate::error::Result<ProviderStream>> + Send + 'static,
80{
81 Arc::new(move |request, cancel| {
82 let fut = f(request, cancel);
83 futures::stream::once(async move {
84 match fut.await {
85 Ok(stream) => stream,
86 Err(err) => Box::pin(futures::stream::iter(std::iter::once(Err(err)))),
87 }
88 })
89 .flatten()
90 .boxed()
91 })
92}

smith/src/stream.rs

Modified

+4 / −0 text lines

6969 Abort,
7070 /// Provider-specific stop sequence.
7171 StopSequence,
72 /// The model declined to answer.
73 Refusal,
74 /// A content filter ended generation.
75 ContentFilter,
7478/// Token and cache usage accounting.