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 --- CHANGELOG.md | 28 ++++++++++ Cargo.toml | 2 +- src/agent.rs | 156 ++++++++++++++++++++++++++++++++++++++++++++++++-------- src/main.rs | 22 ++++++-- src/provider.rs | 128 ++++++++++++++++++++++++++++++++++++---------- src/ui.rs | 26 +++++----- tests/loop.rs | 135 ++++++++++++++++++++++++++++++++++++++++++++++++ tests/mock.rs | 116 +++++++++++++++++++++++++++++++++++++++++ twocalls.log | 0 9 files changed, 548 insertions(+), 65 deletions(-) create mode 100644 twocalls.log diff --git a/CHANGELOG.md b/CHANGELOG.md index f20bc9a..9867621 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,34 @@ break the interface, **PATCH** for bug fixes. file, and the tool schemas the model sees. Anything a script or a resumed session could depend on counts as API. +## 0.4.2 + +### Fixed +- A stream that ends without `[DONE]` or a `finish_reason` is now an error, not an + empty or truncated answer. A provider returning ordinary JSON to a streaming + request used to be recorded as an empty assistant message; a dropped connection + mid-answer used to be recorded as a finished one. +- A tool-call delta without `index` no longer loses the whole call, and + non-contiguous indexes no longer invent an empty call. +- A final `data:` frame with no trailing newline is processed instead of dropped. +- Malformed frames are counted and reported instead of silently swallowed. + +## 0.4.1 + +### Fixed +- Aborting a step that announced several tool calls used to leave the remaining + calls unanswered, which the provider rejects and which made the session + permanently unresumable. Remaining calls now get an "aborted" result, and + sessions opened in that state are repaired by appending the missing results. +- A Ctrl-C pressed after a turn finished could abort the next prompt; the flag is + cleared when a turn starts. +- `run_turn` cleared the global cancel flag rather than the one it was given. +- One-shot mode now exits 130 when aborted and 3 when a tool call was denied, + instead of 0 for both. +- `bash` approval offered `[y/N/a]` but treated `a` as "no"; it now offers + `[y/N]`, matching its documented every-call behaviour. +- A non-terminal stdin now says up front that writes and commands will be denied. + ## 0.4.0 ### Changed diff --git a/Cargo.toml b/Cargo.toml index d531c4b..51c046a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "agent686" -version = "0.4.0" +version = "0.4.2" edition = "2021" description = "A small coding agent for a 32-bit Debian box" publish = false diff --git a/src/agent.rs b/src/agent.rs index 7e652ed..46da069 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -95,6 +95,46 @@ pub fn new_history(system: Value) -> Vec { vec![system] } +#[derive(Debug, Default, Clone, Copy)] +pub struct TurnReport { + pub steps: usize, + pub aborted: bool, + pub denied: usize, +} + +pub enum ToolOutcome { + Ok(String), + Denied, + Failed(String), +} + +impl ToolOutcome { + fn content(&self) -> String { + match self { + ToolOutcome::Ok(output) => output.clone(), + ToolOutcome::Denied => "error: denied by the user".to_string(), + ToolOutcome::Failed(error) => format!("error: {error}"), + } + } + + fn summary(&self) -> String { + match self { + ToolOutcome::Ok(output) => output + .lines() + .find(|line| !line.trim().is_empty()) + .unwrap_or("") + .trim() + .to_string(), + ToolOutcome::Denied => "denied".to_string(), + ToolOutcome::Failed(error) => format!("error: {error}"), + } + } + + fn denied(&self) -> bool { + matches!(self, ToolOutcome::Denied) + } +} + /// Runs one turn to completion: model, tools, model, ... until the model answers /// without asking for a tool. Every message that is sent is also appended to the /// session file, in order, before the next request. @@ -105,8 +145,11 @@ pub fn run_turn( prompt: &str, cancel: &AtomicBool, approver: &mut Approver, -) -> Result<(), Error> { +) -> Result { + // A Ctrl-C pressed after the previous turn finished must not abort this one. + cancel.store(false, std::sync::atomic::Ordering::SeqCst); let started = Instant::now(); + repair_tool_results(session, history); let user = json!({ "role": "user", "content": prompt }); push(session, history, user, None); @@ -114,11 +157,12 @@ pub fn run_turn( let schemas = tools::schemas(); let mut steps = 0usize; let mut last: Option = None; + let mut aborted = false; + let mut denied = 0usize; loop { if cancel.load(std::sync::atomic::Ordering::Relaxed) { - crate::signal::reset(); - eprintln!("aborted"); + aborted = true; break; } @@ -127,8 +171,7 @@ pub fn run_turn( let mut outcome = match provider::chat(cfg, history, &schemas, cancel, &mut renderer) { Ok(outcome) => outcome, Err(Error::Aborted) => { - crate::signal::reset(); - eprintln!("aborted"); + aborted = true; break; } Err(error) => return Err(error), @@ -152,54 +195,123 @@ pub fn run_turn( last = Some(outcome); for call in calls { + // Cancelling between calls still has to answer every tool call the + // assistant message announced: an unanswered id makes the session + // permanently unusable, because history is never rewritten. if cancel.load(std::sync::atomic::Ordering::Relaxed) { - crate::signal::reset(); - eprintln!("aborted"); - break; + aborted = true; } - let result = execute(&call, approver); - ui::tool_result(&result); - let content = match result { - Ok(output) => output, - Err(error) => format!("error: {error}"), + let result = if aborted { + ToolOutcome::Failed("aborted by the user before this call ran".into()) + } else { + execute(&call, approver) }; + if result.denied() { + denied += 1; + } + ui::tool_result(&result.summary(), aborted); let message = json!({ "role": "tool", "tool_call_id": call.id, - "content": content, + "content": result.content(), }); push(session, history, message, None); } + + if aborted { + break; + } } + if aborted { + eprintln!("aborted"); + } if let Some(outcome) = last { ui::status(steps, started.elapsed(), &outcome); } - Ok(()) + Ok(TurnReport { + steps, + aborted, + denied, + }) } -fn execute(call: &provider::ToolCall, approver: &mut Approver) -> Result { +/// Any assistant message whose tool calls never got results would be rejected by +/// the provider, and the transcript is append-only. Repair by appending the +/// missing results, which is legal: only rewriting is forbidden. +fn repair_tool_results(session: &mut Session, history: &mut Vec) { + let index = match history.iter().rposition(|message| { + message.get("role").and_then(|role| role.as_str()) == Some("assistant") + && message + .get("tool_calls") + .and_then(|calls| calls.as_array()) + .is_some_and(|calls| !calls.is_empty()) + }) { + Some(index) => index, + None => return, + }; + + let ids: Vec = history[index]["tool_calls"] + .as_array() + .map(|calls| { + calls + .iter() + .filter_map(|call| call.get("id").and_then(|id| id.as_str())) + .map(|id| id.to_string()) + .collect() + }) + .unwrap_or_default(); + + let answered: std::collections::HashSet = history[index + 1..] + .iter() + .filter_map(|message| message.get("tool_call_id").and_then(|id| id.as_str())) + .map(|id| id.to_string()) + .collect(); + + for id in ids { + if answered.contains(&id) { + continue; + } + let message = json!({ + "role": "tool", + "tool_call_id": id, + "content": "error: this call was interrupted before it ran", + }); + push(session, history, message, None); + } +} + +fn execute(call: &provider::ToolCall, approver: &mut Approver) -> ToolOutcome { let args: Value = serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({})); ui::tool_line(&call.name, &args); match tools::approval(&call.name) { - Approval::Never => tools::run(&call.name, &args), + Approval::Never => match tools::run(&call.name, &args) { + Ok(output) => ToolOutcome::Ok(output), + Err(error) => ToolOutcome::Failed(error), + }, Approval::Once => match tools::plan(&call.name, &args) { Ok(change) => { if approver.allow_edit(change.path(), &change.preview()) { - change.apply() + match change.apply() { + Ok(output) => ToolOutcome::Ok(output), + Err(error) => ToolOutcome::Failed(error), + } } else { - Err("denied by the user".into()) + ToolOutcome::Denied } } - Err(error) => Err(error), + Err(error) => ToolOutcome::Failed(error), }, Approval::EveryCall => { let cmd = args.get("cmd").and_then(|v| v.as_str()).unwrap_or(""); if approver.allow_bash(cmd) { - tools::run(&call.name, &args) + match tools::run(&call.name, &args) { + Ok(output) => ToolOutcome::Ok(output), + Err(error) => ToolOutcome::Failed(error), + } } else { - Err("denied by the user".into()) + ToolOutcome::Denied } } } diff --git a/src/main.rs b/src/main.rs index ccd4e37..9a5012f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -114,7 +114,7 @@ fn main() { if !prompt_words.is_empty() { let prompt = prompt_words.join(" "); - if let Err(error) = agent::run_turn( + match agent::run_turn( &cfg, &mut session, &mut history, @@ -122,14 +122,30 @@ fn main() { &signal::CANCEL, &mut approver, ) { - eprintln!("agent686: {error}"); - std::process::exit(1); + Ok(report) => { + if report.aborted { + std::process::exit(130); + } + if report.denied > 0 { + std::process::exit(3); + } + } + Err(error) => { + eprintln!("agent686: {error}"); + std::process::exit(1); + } } return; } let mut editor = Editor::new(); let interactive = editor.is_interactive(); + if !interactive && !cfg.yolo { + eprintln!( + "agent686: stdin is not a terminal, so write/edit/bash will be denied; \ + pass --yolo to allow them" + ); + } if interactive { eprintln!( "agent686 · {} · session {}{}", 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, diff --git a/src/ui.rs b/src/ui.rs index 2ec0821..38546ab 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -104,14 +104,13 @@ pub fn tool_line(name: &str, args: &serde_json::Value) { let _ = std::io::stdout().flush(); } -pub fn tool_result(result: &Result) { - let text = match result { - Ok(output) => output, - Err(error) => error, +pub fn tool_result(summary: &str, aborted: bool) { + let text = if aborted { + "aborted".to_string() + } else { + crate::provider::truncate(summary.trim(), 100) }; - let first = text.lines().find(|l| !l.trim().is_empty()).unwrap_or(""); - let summary = crate::provider::truncate(first.trim(), 100); - println!(" {} {}", paint("2", "└"), paint("2", &summary)); + println!(" {} {}", paint("2", "└"), paint("2", &text)); let _ = std::io::stdout().flush(); } @@ -163,7 +162,7 @@ impl Approver { self.yolo } - fn ask(&self, question: &str) -> Answer { + fn ask(&self, question: &str, allow_always: bool) -> Answer { if self.yolo { return Answer::Yes; } @@ -174,7 +173,8 @@ impl Approver { ); return Answer::No; } - print!("\n{} {} ", question, paint("2", "[y/N/a]")); + let hint = if allow_always { "[y/N/a]" } else { "[y/N]" }; + print!("\n{} {} ", question, paint("2", hint)); let _ = std::io::stdout().flush(); let mut line = String::new(); @@ -183,7 +183,7 @@ impl Approver { } match line.trim().to_ascii_lowercase().as_str() { "y" | "yes" => Answer::Yes, - "a" | "always" => Answer::Always, + "a" | "always" if allow_always => Answer::Always, _ => Answer::No, } } @@ -194,7 +194,7 @@ impl Approver { return true; } println!("{preview}"); - match self.ask(&format!("apply this change to {path}?")) { + match self.ask(&format!("apply this change to {path}?"), true) { Answer::Yes => true, Answer::Always => { self.edits_allowed = true; @@ -209,6 +209,8 @@ impl Approver { if self.yolo { return true; } - self.ask(&format!("run: {}", crate::provider::truncate(cmd, 200))) == Answer::Yes + // Bash prompts every call by design, so "always" is not offered here. + self.ask(&format!("run: {}", crate::provider::truncate(cmd, 200)), false) + == Answer::Yes } } diff --git a/tests/loop.rs b/tests/loop.rs index d77d890..ac137da 100644 --- a/tests/loop.rs +++ b/tests/loop.rs @@ -190,3 +190,138 @@ fn a_denied_tool_call_is_returned_as_data() { ); assert_eq!(history[4]["content"], "understood"); } + +fn tool_call(index: usize, id: &str, name: &str, arguments: serde_json::Value) -> serde_json::Value { + json!({ + "index": index, + "id": id, + "function": { "name": name, "arguments": arguments.to_string() } + }) +} + +#[test] +fn aborting_between_tool_calls_answers_every_call() { + let dir = temp_dir("abort-mid-calls"); + let slow = sse(&format!( + "data: {}\n\ndata: [DONE]\n\n", + json!({ + "choices": [{ + "delta": { "tool_calls": [ + tool_call(0, "call_a", "bash", json!({ "cmd": "sleep 0.5" })), + tool_call(1, "call_b", "write", json!({ "path": dir.join("b.txt"), "content": "b" })), + tool_call(2, "call_c", "write", json!({ "path": dir.join("c.txt"), "content": "c" })) + ]}, + "finish_reason": "tool_calls" + }] + }) + )); + // If the harness wrongly continues after the abort, it would consume this. + let after = sse( + "data: {\"choices\":[{\"delta\":{\"content\":\"should not be reached\"},\"finish_reason\":\"stop\"}]}\n\n\ + data: [DONE]\n\n", + ); + + let base = serve_sequence(vec![slow, after]); + std::env::set_var("AGENT686_DATA", dir.join("data")); + + let system = agent::system_prompt(); + let mut session = Session::create("test-model", &system).unwrap(); + let cfg = Config { + base_url: base, + api_key: "test-key".into(), + model: "test-model".into(), + session: session.id.clone(), + yolo: true, + }; + let mut history = agent::new_history(system); + let mut approver = Approver::new(true); + let cancel = std::sync::Arc::new(AtomicBool::new(false)); + + let flag = cancel.clone(); + thread::spawn(move || { + thread::sleep(std::time::Duration::from_millis(150)); + flag.store(true, std::sync::atomic::Ordering::SeqCst); + }); + + let report = agent::run_turn( + &cfg, + &mut session, + &mut history, + "do three things", + &cancel, + &mut approver, + ) + .expect("an abort is not an error"); + + assert!(report.aborted); + + // Every announced tool call must have exactly one result, or the provider + // rejects the session forever and the transcript cannot be rewritten. + let answered: Vec = history + .iter() + .filter(|message| message.get("role").and_then(|r| r.as_str()) == Some("tool")) + .filter_map(|message| message.get("tool_call_id").and_then(|id| id.as_str()).map(|s| s.to_string())) + .collect(); + assert_eq!(answered, vec!["call_a", "call_b", "call_c"], "{answered:?}"); + + // The loop stopped: no assistant text was ever appended. + assert_eq!(history.last().unwrap()["role"], "tool"); + assert!(fs::read_to_string(session.path()).unwrap().lines().count() >= 5); +} + +#[test] +fn opening_a_session_with_unanswered_calls_repairs_it() { + let dir = temp_dir("repair"); + std::env::set_var("AGENT686_DATA", dir.join("data")); + + let base = serve_sequence(vec![sse( + "data: {\"choices\":[{\"delta\":{\"content\":\"carrying on\"},\"finish_reason\":\"stop\"}]}\n\n\ + data: [DONE]\n\n", + )]); + + let system = agent::system_prompt(); + let mut session = Session::create("test-model", &system).unwrap(); + let mut history = agent::new_history(system); + + // A transcript shape left behind by an older build: two calls, one result. + let assistant = json!({ + "role": "assistant", + "content": null, + "tool_calls": [ + { "id": "call_1", "type": "function", "function": { "name": "read", "arguments": "{}" } }, + { "id": "call_2", "type": "function", "function": { "name": "read", "arguments": "{}" } } + ] + }); + session.append(&assistant, None).unwrap(); + history.push(assistant); + let partial = json!({ "role": "tool", "tool_call_id": "call_1", "content": "ok" }); + session.append(&partial, None).unwrap(); + history.push(partial); + + let cfg = Config { + base_url: base, + api_key: "test-key".into(), + model: "test-model".into(), + session: session.id.clone(), + yolo: true, + }; + let mut approver = Approver::new(true); + agent::run_turn( + &cfg, + &mut session, + &mut history, + "go on", + &AtomicBool::new(false), + &mut approver, + ) + .expect("repair should let the turn run"); + + let repaired = history.iter().any(|message| { + message.get("tool_call_id").and_then(|id| id.as_str()) == Some("call_2") + && message + .get("content") + .and_then(|c| c.as_str()) + .is_some_and(|c| c.contains("interrupted")) + }); + assert!(repaired, "missing result for call_2 should be synthesised"); +} diff --git a/tests/mock.rs b/tests/mock.rs index 9b3cd5a..9b9a56d 100644 --- a/tests/mock.rs +++ b/tests/mock.rs @@ -326,3 +326,119 @@ fn auth_failure_says_where_the_key_lives() { let message = format!("{error}"); assert!(message.contains("OPENCODE_API_KEY"), "{message}"); } + +#[test] +fn a_truncated_stream_is_an_error_not_an_answer() { + const TRUNCATED: &str = concat!( + "HTTP/1.1 200 OK\r\n", + "Content-Type: text/event-stream\r\n", + "Connection: close\r\n", + "\r\n", + "data: {\"choices\":[{\"delta\":{\"content\":\"partial\"}}]}\n\n", + ); + let (base, _rx) = serve_once(TRUNCATED); + let mut sink = Collector::default(); + let error = provider::chat( + &config(base), + &[json!({ "role": "user", "content": "hi" })], + &[], + &AtomicBool::new(false), + &mut sink, + ) + .expect_err("a stream without [DONE] or finish_reason must fail"); + + let message = format!("{error}"); + assert!(message.contains("ended before completion"), "{message}"); +} + +#[test] +fn a_non_sse_200_is_an_error_not_an_empty_answer() { + const JSON: &str = concat!( + "HTTP/1.1 200 OK\r\n", + "Content-Type: application/json\r\n", + "Connection: close\r\n", + "\r\n", + "{\"id\":\"x\",\"choices\":[{\"message\":{\"content\":\"hello\"}}]}", + ); + let (base, _rx) = serve_once(JSON); + let mut sink = Collector::default(); + let error = provider::chat( + &config(base), + &[json!({ "role": "user", "content": "hi" })], + &[], + &AtomicBool::new(false), + &mut sink, + ) + .expect_err("a non-streaming body must not look like a blank answer"); + assert!(format!("{error}").contains("ended before completion")); +} + +#[test] +fn finish_reason_without_done_marker_is_accepted() { + const SSE: &str = concat!( + "HTTP/1.1 200 OK\r\n", + "Content-Type: text/event-stream\r\n", + "Connection: close\r\n", + "\r\n", + "data: {\"choices\":[{\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\n", + ); + let (base, _rx) = serve_once(SSE); + let mut sink = Collector::default(); + let outcome = provider::chat( + &config(base), + &[json!({ "role": "user", "content": "hi" })], + &[], + &AtomicBool::new(false), + &mut sink, + ) + .expect("finish_reason is enough"); + assert_eq!(outcome.content, "ok"); +} + +#[test] +fn a_tool_call_without_an_index_still_assembles() { + const SSE: &str = concat!( + "HTTP/1.1 200 OK\r\n", + "Content-Type: text/event-stream\r\n", + "Connection: close\r\n", + "\r\n", + "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"id\":\"call_1\",\"function\":{\"name\":\"read\",\"arguments\":\"{\\\"path\\\":\\\"a\\\"}\"}}]},\"finish_reason\":\"tool_calls\"}]}\n\n", + "data: [DONE]\n\n", + ); + let (base, _rx) = serve_once(SSE); + let mut sink = Collector::default(); + let outcome = provider::chat( + &config(base), + &[json!({ "role": "user", "content": "hi" })], + &[], + &AtomicBool::new(false), + &mut sink, + ) + .expect("chat should succeed"); + + assert_eq!(outcome.tool_calls.len(), 1); + assert_eq!(outcome.tool_calls[0].name, "read"); + assert_eq!(outcome.tool_calls[0].arguments, "{\"path\":\"a\"}"); +} + +#[test] +fn a_final_frame_without_a_newline_is_not_lost() { + const SSE: &str = concat!( + "HTTP/1.1 200 OK\r\n", + "Content-Type: text/event-stream\r\n", + "Connection: close\r\n", + "\r\n", + "data: {\"choices\":[{\"delta\":{\"content\":\"last\"},\"finish_reason\":\"stop\"}]}", + ); + let (base, _rx) = serve_once(SSE); + let mut sink = Collector::default(); + let outcome = provider::chat( + &config(base), + &[json!({ "role": "user", "content": "hi" })], + &[], + &AtomicBool::new(false), + &mut sink, + ) + .expect("a trailing frame without a newline should still count"); + assert_eq!(outcome.content, "last"); +} diff --git a/twocalls.log b/twocalls.log new file mode 100644 index 0000000..e69de29 -- cgit v1.2.3