README Source History Refs Reviews Compare Notes Search Review guide ai(SMH-PLAN-AIAG0001): normalize one provider stream through the shared conformance kit b8d2fa90895e890185241da7fb9b8a964d08ee32
Oliver Jan Krylow <oliver@bugabinga.net > · 11 Sep 2026
unsigned
Browse files Compare 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) Diff layout Auto Unified Split
.system/board.json Modified +22 / −1 text lines
2 2 "schemaVersion" : 0 , "schemaVersion" : 0 ,4 + "SMH-ISSUE-R4SEXWVT" : {7 + "updatedAt" : "2026-09-11T08:32:58.566Z" 9 + "SMH-PLAN-CORE0001" : {11 + "updatedAt" : "2026-09-11T08:32:36.616Z" ,14 + "SMH-PLAN-CORE0002" : {16 + "updatedAt" : "2026-09-11T08:32:39.399Z" ,19 + "SMH-PLAN-WSPC0001" : {21 + "updatedAt" : "2026-09-11T08:32:49.987Z" ,.system/plans/SMH-PLAN-AIAG0001-provider-and-agent-loop/index.md Modified +18 / −11 text lines
4 4 title: "Provider Runtime and Agent Loop"title: "Provider Runtime and Agent Loop"5 5 spec: SMH-SPEC-SPEC0001spec: SMH-SPEC-SPEC00017 7 depends_on: [SMH-PLAN-CORE0001]depends_on: [SMH-PLAN-CORE0001]14 14 - Shared stream, tool, error, session, and trace contracts are stable.- Shared stream, tool, error, session, and trace contracts are stable.15 15 - Provider-free tool events persist correctly.- Provider-free tool events persist correctly.
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.19 - 1. Add `smith-ai` provider adapters that normalize deltas, tool calls, usage, stop reasons, errors, and cancellation.20 - 2. Add explicit model capability metadata and request validation.21 - 3. Add the reviewed offline catalog and deterministic alias, group, and account resolution.22 - 4. Add credential resolution, readiness checks, renewable credentials, and concurrent update safety.23 - 5. Add cancellable catalog refresh with cached fallback and generation-checked publication.24 - 6. Prove one OpenAI-compatible stream against fragmented, malformed, incomplete, and non-stream error fixtures.25 - 7. Add required Anthropic, OpenAI, and Google adapter coverage through the same normalized boundary.26 - 8. Add the `smith-core` agent loop with ordered turn, message, tool, retry, and settled events.27 - 9. Add steering, follow-up, compaction, cost, secret substitution, bounded retry, and failover behavior.28 - 10. Expose eval and LF-delimited JSON-RPC through `smith-cli` and `smith-harness`.25 + 1. Add `StreamFn` request and stream types to `smith`.26 + 2. Add `smith-ai` provider adapters that normalize deltas, tool calls, usage, stop reasons, errors, and cancellation.27 + 3. Add explicit model capability metadata and request validation.28 + 4. Add the reviewed offline catalog and deterministic alias, group, and account resolution.29 + 5. Add credential resolution, readiness checks, renewable credentials, and concurrent update safety.30 + 6. Add cancellable catalog refresh with cached fallback and generation-checked publication.31 + 7. Build the provider-agnostic conformance kit and prove one OpenAI-compatible adapter against fragmented, malformed, incomplete, and non-stream error fixtures.32 + 8. Add required Anthropic, OpenAI, and Google adapter coverage through the same normalized boundary.33 + 9. Add the `smith-core` agent loop with ordered turn, message, tool, retry, and settled events.34 + 10. Add steering, follow-up, compaction, cost, secret substitution, bounded retry, and failover behavior.35 + 11. Expose eval and LF-delimited JSON-RPC through `smith-cli` and `smith-harness`.30 37 ## Interfaces ## Interfaces .system/research/SMH-RESEARCH-AIAGD001-provider-stream-normalization-design/index.md Added new file mode 100644+52 / −0 text lines
2 + id: SMH-RESEARCH-AIAGD0014 + title: "Provider Stream Normalization Design"7 + # Provider Stream Normalization Design 11 + Starting 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?15 + Anthropic 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 |27 + Google `streamGenerateContent` delivers function calls complete in one part, a third argument-delivery shape.29 + The 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.31 + Adding 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.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.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`.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.+66 / −0 text lines
140 140 "winapi" , "winapi" ,
146 + source = "registry+https://github.com/rust-lang/crates.io-index" 147 + checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" 159 + name = "futures-channel" 161 + source = "registry+https://github.com/rust-lang/crates.io-index" 162 + checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" 143 168 [[package ]][[package ]]144 169 name = "futures-core" name = "futures-core" 145 170 version = "0.3.34" version = "0.3.34" 146 171 source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index" 147 172 checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
175 + name = "futures-executor" 177 + source = "registry+https://github.com/rust-lang/crates.io-index" 178 + checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" 188 + source = "registry+https://github.com/rust-lang/crates.io-index" 189 + checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" 192 + name = "futures-macro" 194 + source = "registry+https://github.com/rust-lang/crates.io-index" 195 + checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" 203 + name = "futures-sink" 205 + source = "registry+https://github.com/rust-lang/crates.io-index" 206 + checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" 149 208 [[package ]][[package ]]150 209 name = "futures-task" name = "futures-task" 151 210 version = "0.3.34" version = "0.3.34" 158 217 source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index" 159 218 checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" 160 219 dependencies = [dependencies = [161 221 "futures-core" , "futures-core" ,162 225 "futures-task" , "futures-task" ,163 227 "pin-project-lite" , "pin-project-lite" ,439 503 dependencies = [dependencies = [440 504 "ciborium" , "ciborium" ,443 508 "serde_json" , "serde_json" ,448 513 name = "smith-ai" name = "smith-ai" 449 514 version = "0.1.0" version = "0.1.0" 450 515 dependencies = [dependencies = [smith-ai/Cargo.toml Modified +1 / −0 text lines
10 10 [dependencies ][dependencies ]11 11 smith = { path = "../smith" }smith = { path = "../smith" }
12 + serde_json = { workspace = true }smith-ai/src/conformance.rs Added new file mode 100644+132 / −0 text lines
9 + use smith::error::Result;10 + use smith::stream::{StopReason, StreamEvent, Usage};18 + pub trait StreamDecoder {25 + fn push (&mut self, bytes: & [u8 ]) -> Result <Vec <StreamEvent>>;34 + fn finish (&mut self) -> Result <Vec <StreamEvent>>;38 + #[derive(Clone, Debug, PartialEq, Eq)]49 + input: serde_json::Value,56 + usage: Option <Usage>,66 + pub name: &'static str ,68 + pub chunks: Vec <Vec <u8 >>,70 + pub expected: Vec <Expected>,77 + pub fn conformance_report (78 + make: & dyn Fn() -> Box <dyn StreamDecoder>,79 + fixtures: & [Fixture],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) {87 + Err (err) => actual.push (Expected::Fault(err.code ().to_string ())),89 + if actual != fixture.expected {90 + failures.push (format! (91 + "fixture {}: expected {:?}, got {:?}" ,92 + fixture.name, fixture.expected, actual100 + decoder: &mut dyn StreamDecoder,102 + actual: &mut Vec <Expected>,104 + for chunk in chunks {105 + for event in decoder.push (chunk)? {106 + push_shape (actual, event)? ;109 + for event in decoder.finish ()? {110 + push_shape (actual, event)? ;115 + fn 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 },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:?}" ),smith-ai/src/lib.rs Modified +12 / −0 text lines
2 2 #![warn(missing_docs)]#![warn(missing_docs)]
15 + pub use conformance::{Expected, Fixture, StreamDecoder};16 + pub use openai::OpenAiDecoder;smith-ai/src/openai.rs Added new file mode 100644+476 / −0 text lines
8 + use crate ::conformance::StreamDecoder;9 + use smith::error::{ProviderFault, Result , SmithError};10 + use smith::id::{MessageId, ToolCallId};11 + use smith::stream::{StopReason, StreamEvent, Usage};12 + use std::collections::BTreeMap;16 + pub struct OpenAiDecoder {18 + message_id: MessageId,19 + tools: BTreeMap<u64 , ToolAccumulator>,20 + finish_reason: Option <String >,21 + usage: Option <Usage>,26 + #[derive(Clone, Debug)]27 + struct ToolAccumulator {33 + const DONE : &str = "[DONE]" ;38 + pub fn new () -> Self {40 + buffer: String ::new(),41 + message_id: MessageId::new(),42 + tools: BTreeMap::new(),50 + fn process_event (&mut self, data: &str , events: &mut Vec <StreamEvent>) -> Result <()> {52 + return Err (protocol ("event after terminal" ));54 + if data.trim () == DONE {55 + return self.finish_done (events);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));62 + if let Some (usage) = chunk.get ("usage" ).filter (|value| value.is_object ()) {63 + self.usage = parse_usage (usage);65 + let Some (choice) = chunk67 + .and_then (serde_json::Value::as_array)68 + .and_then (|choices| choices.first ())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)76 + events.push (StreamEvent::text_delta(self.message_id, text));78 + if let Some (text) = delta79 + .get ("reasoning_content" )80 + .and_then (serde_json::Value::as_str)83 + events.push (StreamEvent::thinking_delta(self.message_id, text));85 + if let Some (calls) = delta87 + .and_then (serde_json::Value::as_array)90 + self.accumulate_tool_call (call)? ;93 + if let Some (reason) = choice94 + .get ("finish_reason" )95 + .and_then (serde_json::Value::as_str)97 + if self.finish_reason.is_some () {98 + return Err (protocol ("finish_reason sent twice" ));100 + self.finish_reason = Some (reason.to_string ());101 + self.flush_tools (events)? ;106 + fn accumulate_tool_call (&mut self, call: & serde_json::Value) -> Result <()> {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(),116 + if let Some (name) = call118 + .and_then (|function| function.get ("name" ))119 + .and_then (serde_json::Value::as_str)121 + entry.name = name.to_string ();123 + if let Some (fragment) = call125 + .and_then (|function| function.get ("arguments" ))126 + .and_then (serde_json::Value::as_str)128 + entry.arguments.push_str (fragment);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" ));140 + let input = if entry.arguments.trim ().is_empty () {141 + serde_json::json! ({})143 + serde_json::from_str(& entry.arguments)144 + .map_err (|e| protocol (format! ("fragmented tool arguments are not JSON: {e}" )))? 146 + events.push (StreamEvent::tool_use(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" ));161 + if ! self.tools.is_empty () {162 + return Err (protocol ("terminal marker with unfinished tool calls" ));164 + let reason = map_finish_reason (& reason)? ;165 + self.terminal = true ;166 + self.stopped = true ;167 + events.push (StreamEvent::stop(reason, self.usage));172 + impl Default for OpenAiDecoder {173 + fn default () -> Self {178 + impl 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) {184 + self.process_event (& data, &mut events)? ;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)? ;196 + return Err (SmithError::Provider {197 + fault: ProviderFault::Incomplete,205 + fn 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 ();215 + let rest = buffer[consumed + line.len ().. ].to_string ();216 + return Some ((data, rest));218 + if let Some (payload) = trimmed.strip_prefix ("data:" ) {219 + data.push_str (payload.strip_prefix (' ' ).unwrap_or (payload));221 + consumed += line.len ();226 + fn map_finish_reason (reason: &str ) -> Result <StopReason> {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}" ))),236 + fn 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 ,241 + Some ("server_error" | "timeout" | "internal_error" | "api_error" ) => {242 + ProviderFault::Transient {243 + message: message_of (error),246 + Some ("invalid_request_error" ) => ProviderFault::Invalid {248 + message: message_of (error),250 + Some ("authentication_error" | "invalid_api_key" ) => ProviderFault::Authentication {251 + message: message_of (error),253 + Some ("overloaded_error" ) => ProviderFault::Overloaded {254 + message: message_of (error),256 + _ => ProviderFault::Protocol {257 + message: message_of (error),260 + SmithError::Provider { fault }263 + fn message_of (error: & serde_json::Value) -> String {266 + .and_then (serde_json::Value::as_str)267 + .unwrap_or ("unknown provider error" )271 + fn protocol (message: impl Into <String >) -> SmithError {272 + SmithError::Provider {273 + fault: ProviderFault::Protocol {274 + message: message.into (),279 + fn parse_usage (usage: & serde_json::Value) -> Option <Usage> {280 + if ! usage.is_object () {285 + .get ("prompt_tokens" )286 + .and_then (serde_json::Value::as_u64)? ,287 + output_tokens: usage288 + .get ("completion_tokens" )289 + .and_then (serde_json::Value::as_u64)? ,290 + input_cache_hit_tokens: usage291 + .get ("prompt_tokens_details" )292 + .and_then (|details| details.get ("cached_tokens" ))293 + .and_then (serde_json::Value::as_u64)295 + input_cache_write_tokens: 0 ,301 + clippy::unwrap_used,302 + reason = "conformance fixtures assert on invariant shapes" 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();312 + out.push_str ("data: " );314 + out.push_str ("\n\n" );319 + fn text_fixture () -> Fixture {321 + name: "text plus usage" ,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}}}"# ,331 + Expected::Text("Hello" .to_string ()),332 + Expected::Text(" world" .to_string ()),334 + reason: StopReason::EndTurn,338 + input_cache_hit_tokens: 4 ,339 + input_cache_write_tokens: 0 ,346 + fn tool_fixture () -> Fixture {348 + name: "fragmented tool arguments" ,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"}]}"# ,358 + name: "write" .to_string (),359 + input: serde_json::json! ({"path" : "f.txt" , "content" : "hi" }),362 + reason: StopReason::ToolUse,369 + fn thinking_fixture () -> Fixture {371 + name: "reasoning deltas" ,373 + r #"{"choices":[{"delta":{"reasoning_content":"ponder"}}]}"# ,374 + r #"{"choices":[{"delta":{"content":"answer"}}]}"# ,375 + r #"{"choices":[{"delta":{},"finish_reason":"stop"}]}"# ,379 + Expected::Thinking("ponder" .to_string ()),380 + Expected::Text("answer" .to_string ()),382 + reason: StopReason::EndTurn,389 + fn refusal_and_filter_fixtures () -> Vec <Fixture> {392 + name: "content filter stop" ,394 + sse (& [r #"{"choices":[{"delta":{},"finish_reason":"content_filter"}]}"# ]),397 + expected: vec! [Expected::Stop {398 + reason: StopReason::ContentFilter,403 + name: "rate limit error body" ,405 + r #"{"error":{"message":"quota","type":"insufficient_quota"}}"# ,407 + expected: vec! [Expected::Fault("PROVIDER_RATE_LIMIT" .to_string ())],410 + name: "malformed json chunk" ,411 + chunks: vec! [sse (& ["{not json}" ])],412 + expected: vec! [Expected::Fault("PROVIDER_PROTOCOL" .to_string ())],415 + name: "truncated before terminal" ,416 + chunks: vec! [sse (& [r #"{"choices":[{"delta":{"content":"partial"}}]}"# ])],418 + Expected::Text("partial" .to_string ()),419 + Expected::Fault("PROVIDER_INCOMPLETE" .to_string ()),423 + name: "data after terminal" ,425 + sse (& [r #"{"choices":[{"delta":{},"finish_reason":"stop"}]}"# ]),427 + sse (& [r #"{"choices":[{"delta":{"content":"late"}}"# ]),432 + reason: StopReason::EndTurn,435 + Expected::Fault("PROVIDER_PROTOCOL" .to_string ()),439 + name: "terminal without finish reason" ,440 + chunks: vec! [sse (& ["[DONE]" ])],441 + expected: vec! [Expected::Fault("PROVIDER_PROTOCOL" .to_string ())],447 + fn openai_adapter_satisfies_conformance () {448 + let failures = conformance_report (449 + &|| Box ::new(OpenAiDecoder::new()),451 + vec! [text_fixture (), tool_fixture (), thinking_fixture ()],452 + refusal_and_filter_fixtures (),456 + .collect::<Vec <_ >>(),458 + assert! (failures.is_empty (), "{failures:?}" );462 + fn chunk_splitting_does_not_change_events () {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}" );+1 / −0 text lines
13 13 ciborium = { workspace = true }ciborium = { workspace = true }14 14 serde_json = { workspace = true }serde_json = { workspace = true }15 15 dirs = { workspace = true }dirs = { workspace = true }
16 + futures = { workspace = true }18 19 default = []No final newline default = []No final newline smith/src/error.rs Modified +90 / −8 text lines
86 + #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]87 + pub enum ProviderFault {91 + retry_after_ms: Option <u64 >,101 + field: Option <String >,127 + pub const fn code (& self) -> &'static str {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" ,141 + pub const fn may_fail_over (& self) -> bool {144 + Self ::RateLimit { .. } | Self ::Overloaded { .. } | Self ::Transient { .. }149 + impl fmt::Display for ProviderFault {150 + fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {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" ),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}" ),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" ),85 170 #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]86 171 pub enum SmithError {pub enum SmithError {95 180 Provider { Provider {182 + fault: ProviderFault,137 220 fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result { fn fmt (& self, f: &mut fmt::Formatter<'_ >) -> fmt::Result {138 221 match self { match self {139 222 Self ::Session { code, message } => write! (f, "session [{code}]: {message}" ), 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 }" ),141 224 Self ::Tool { code, message } => write! (f, "tool [{code}]: {message}" ), Self ::Tool { code, message } => write! (f, "tool [{code}]: {message}" ),142 225 Self ::RecordFailed { Self ::RecordFailed {169 252 #[must_use] #[must_use]170 253 pub fn code (& self) -> &str { pub fn code (& self) -> &str {171 254 match self { match self {172 - Self ::Session { code, .. } | Self ::Provider { code , .. } | Self :: Tool { code, .. } => { 255 + Self ::Session { code, .. } | Self ::Tool { code, .. } => code , 256 + Self ::Provider { fault } => fault.code (),175 257 Self ::RecordFailed { .. } => "RECORD_FAILED" , Self ::RecordFailed { .. } => "RECORD_FAILED" ,176 258 Self ::Frame { fault, .. } => fault.code (), Self ::Frame { fault, .. } => fault.code (),177 259 Self ::Cancelled => "CANCELLED" , Self ::Cancelled => "CANCELLED" ,+4 / −1 text lines
12 12 pub mod id ;pub mod id ;14 14 pub mod message ;pub mod message ;16 18 pub mod stream ;pub mod stream ;18 20 pub mod tool ;pub mod tool ;20 22 pub use config::Config;pub use config::Config;21 - pub use error::{FrameFault, Result , SmithError};23 + pub use error::{FrameFault, ProviderFault , Result , SmithError};22 24 pub use id::{BranchId, EntryId, MessageId, SessionId, ToolCallId, ToolResultId};pub use id::{BranchId, EntryId, MessageId, SessionId, ToolCallId, ToolResultId};23 25 pub use message::{ContentBlock, Message, Role};pub use message::{ContentBlock, Message, Role};
26 + pub use provider::{ProviderParams, ProviderRequest, ProviderStream, StreamFn, StreamItem};24 27 pub use stream::{StopReason, StreamEvent, Usage};pub use stream::{StopReason, StreamEvent, Usage};25 28 pub use tool::{CancelHandle, ToolCall, ToolMetadata, ToolResult};pub use tool::{CancelHandle, ToolCall, ToolMetadata, ToolResult};smith/src/provider.rs Added new file mode 100644+92 / −0 text lines
8 + use crate ::message::Message;9 + use crate ::stream::StreamEvent;10 + use crate ::tool::{CancelHandle, ToolMetadata};11 + use futures::stream::{BoxStream, StreamExt};12 + use std::future::Future;16 + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]17 + pub struct ProviderParams {19 + pub max_output_tokens: Option <u64 >,21 + pub temperature: Option <u32 >,27 + #[derive(Clone, Debug, PartialEq, Eq)]28 + pub struct ProviderRequest {32 + pub messages: Vec <Message>,34 + pub tools: Vec <ToolMetadata>,36 + pub params: ProviderParams,39 + impl ProviderRequest {42 + pub fn new (model: impl Into <String >, messages: Vec <Message>) -> Self {47 + params: ProviderParams::default(),53 + pub fn with_tools (mut self, tools: Vec <ToolMetadata>) -> Self {60 + pub const fn with_params (mut self, params: ProviderParams) -> Self {61 + self.params = params;67 + pub type StreamItem = crate ::error::Result<StreamEvent>;70 + pub type ProviderStream = BoxStream<'static , StreamItem>;73 + pub type StreamFn = Arc<dyn Fn (ProviderRequest, CancelHandle) -> ProviderStream + Send + Sync >;76 + pub fn stream_fn <F, Fut>(f: F) -> StreamFn78 + F: Fn(ProviderRequest, CancelHandle) -> Fut + Send + Sync + 'static ,79 + Fut: Future<Output = crate::error::Result <ProviderStream>> + Send + 'static ,81 + Arc::new(move | request, cancel| {82 + let fut = f (request, cancel);83 + futures::stream::once(async move {85 + Ok (stream) => stream,86 + Err (err) => Box ::pin(futures::stream::iter(std::iter::once(Err (err)))),smith/src/stream.rs Modified +4 / −0 text lines
71 71 StopSequence, StopSequence,