From 714534475818e6e5dced91ecad100ca9e286ccce Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 15:37:56 +0100 Subject: 0.4.1 + 0.4.2: abort integrity, stream completeness, tool-call indexing - an aborted multi-call step now answers every announced tool call - sessions with unanswered calls are repaired by appending results - a stream without [DONE]/finish_reason is an error, not an answer - tool call deltas keyed by index can no longer vanish or invent empty calls - one-shot exit codes: 130 aborted, 3 denied --- src/provider.rs | 128 ++++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 101 insertions(+), 27 deletions(-) (limited to 'src/provider.rs') diff --git a/src/provider.rs b/src/provider.rs index 16c9013..b45282e 100644 --- a/src/provider.rs +++ b/src/provider.rs @@ -115,6 +115,23 @@ impl SseDecoder { self.buf.drain(..start); out } + + /// Anything left when the connection closes without a final newline. + pub fn finish(&mut self) -> Vec { + let mut out = Vec::new(); + if !self.buf.is_empty() { + let mut line = &self.buf[..]; + if line.last() == Some(&b'\r') { + line = &line[..line.len() - 1]; + } + if let Some(payload) = line.strip_prefix(b"data:") { + let payload = payload.strip_prefix(b" ").unwrap_or(payload); + out.push(String::from_utf8_lossy(payload).into_owned()); + } + self.buf.clear(); + } + out + } } const MAX_ATTEMPTS: usize = 4; @@ -290,9 +307,12 @@ pub fn chat( let mut decoder = SseDecoder::new(); let mut buf = [0u8; 8192]; let mut reader = resp.body_mut().as_reader(); + let mut calls: std::collections::BTreeMap = std::collections::BTreeMap::new(); + let mut completed = false; let mut done = false; + let mut dropped = 0usize; - while !done { + loop { // Blocking reads mean an abort is only noticed when bytes arrive or the // per-read timeout fires. Good enough: the model streams constantly. if cancel.load(Ordering::Relaxed) { @@ -304,31 +324,83 @@ pub fn chat( Err(e) => return Err(Error::Transport(e.to_string())), }; for data in decoder.feed(&buf[..n]) { - if data.is_empty() { - continue; - } - if data.trim() == "[DONE]" { + if handle_event(&data, &mut outcome, &mut calls, &mut completed, &mut dropped, sink) { done = true; break; } - let chunk: Chunk = match serde_json::from_str(&data) { - Ok(c) => c, - // A malformed frame is dropped rather than killing the turn. - Err(_) => continue, - }; - apply_chunk(&chunk, &mut outcome, sink); + } + if done { + break; + } + } + + // A final `data:` frame with no trailing newline is legitimate. + if !done { + for data in decoder.finish() { + if handle_event(&data, &mut outcome, &mut calls, &mut completed, &mut dropped, sink) { + break; + } } } + outcome.tool_calls = calls.into_values().collect(); if outcome.usage.as_ref().is_some_and(|u| u.is_null()) { outcome.usage = None; } + if dropped > 0 { + eprintln!("agent686: ignored {dropped} malformed stream frame(s)"); + } + + // A connection that closes early, or a 200 that is not SSE at all, must not + // be recorded as a complete answer. + if !completed { + return Err(Error::Transport(format!( + "stream ended before completion ({} bytes of text, {} tool call(s)); \ + the turn was not recorded as answered", + outcome.content.len(), + outcome.tool_calls.len() + ))); + } + sink.done(&outcome, started.elapsed()); Ok(outcome) } -fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { +fn handle_event( + data: &str, + outcome: &mut Outcome, + calls: &mut std::collections::BTreeMap, + completed: &mut bool, + dropped: &mut usize, + sink: &mut dyn Sink, +) -> bool { + if data.is_empty() { + return false; + } + if data.trim() == "[DONE]" { + *completed = true; + return true; + } + match serde_json::from_str::(data) { + Ok(chunk) => { + if chunk.choices.iter().any(|choice| choice.finish_reason.is_some()) { + *completed = true; + } + apply_chunk(&chunk, outcome, calls, sink); + } + // Counted and reported rather than silently swallowed. + Err(_) => *dropped += 1, + } + false +} + +fn apply_chunk( + chunk: &Chunk, + outcome: &mut Outcome, + calls: &mut std::collections::BTreeMap, + sink: &mut dyn Sink, +) { if let Some(usage) = &chunk.usage { outcome.usage = Some(usage.clone()); } @@ -345,9 +417,9 @@ fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { sink.text(t); } } - if let Some(calls) = &choice.delta.tool_calls { - for call in calls { - accumulate_tool_call(&mut outcome.tool_calls, call); + if let Some(deltas) = &choice.delta.tool_calls { + for delta in deltas { + accumulate_tool_call(calls, delta); } } if let Some(finish) = &choice.finish_reason { @@ -357,18 +429,19 @@ fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { } /// Tool call deltas arrive split across chunks and are keyed by `index`: the -/// name and id usually come once, the arguments a fragment at a time. -fn accumulate_tool_call(calls: &mut Vec, delta: &ToolCallDelta) { - while calls.len() <= delta.index { - let index = calls.len(); - calls.push(ToolCall { - index, - id: String::new(), - name: String::new(), - arguments: String::new(), - }); - } - let call = &mut calls[delta.index]; +/// name and id usually come once, the arguments a fragment at a time. A map +/// keyed by index means a missing or non-contiguous index cannot invent an +/// empty call or shift the others. +fn accumulate_tool_call( + calls: &mut std::collections::BTreeMap, + delta: &ToolCallDelta, +) { + let call = calls.entry(delta.index).or_insert_with(|| ToolCall { + index: delta.index, + id: String::new(), + name: String::new(), + arguments: String::new(), + }); if let Some(id) = &delta.id { call.id.push_str(id); } @@ -434,6 +507,7 @@ struct Delta { #[derive(Debug, Deserialize)] struct ToolCallDelta { + #[serde(default)] index: usize, #[serde(default)] id: Option, -- cgit v1.2.3