diff options
Diffstat (limited to '')
| -rw-r--r-- | CHANGELOG.md | 28 | ||||
| -rw-r--r-- | Cargo.toml | 2 | ||||
| -rw-r--r-- | src/agent.rs | 156 | ||||
| -rw-r--r-- | src/main.rs | 22 | ||||
| -rw-r--r-- | src/provider.rs | 128 | ||||
| -rw-r--r-- | src/ui.rs | 26 | ||||
| -rw-r--r-- | tests/loop.rs | 135 | ||||
| -rw-r--r-- | tests/mock.rs | 116 | ||||
| -rw-r--r-- | twocalls.log | 0 |
9 files changed, 548 insertions, 65 deletions
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. | |||
| 7 | file, and the tool schemas the model sees. Anything a script or a resumed session | 7 | file, and the tool schemas the model sees. Anything a script or a resumed session |
| 8 | could depend on counts as API. | 8 | could depend on counts as API. |
| 9 | 9 | ||
| 10 | ## 0.4.2 | ||
| 11 | |||
| 12 | ### Fixed | ||
| 13 | - A stream that ends without `[DONE]` or a `finish_reason` is now an error, not an | ||
| 14 | empty or truncated answer. A provider returning ordinary JSON to a streaming | ||
| 15 | request used to be recorded as an empty assistant message; a dropped connection | ||
| 16 | mid-answer used to be recorded as a finished one. | ||
| 17 | - A tool-call delta without `index` no longer loses the whole call, and | ||
| 18 | non-contiguous indexes no longer invent an empty call. | ||
| 19 | - A final `data:` frame with no trailing newline is processed instead of dropped. | ||
| 20 | - Malformed frames are counted and reported instead of silently swallowed. | ||
| 21 | |||
| 22 | ## 0.4.1 | ||
| 23 | |||
| 24 | ### Fixed | ||
| 25 | - Aborting a step that announced several tool calls used to leave the remaining | ||
| 26 | calls unanswered, which the provider rejects and which made the session | ||
| 27 | permanently unresumable. Remaining calls now get an "aborted" result, and | ||
| 28 | sessions opened in that state are repaired by appending the missing results. | ||
| 29 | - A Ctrl-C pressed after a turn finished could abort the next prompt; the flag is | ||
| 30 | cleared when a turn starts. | ||
| 31 | - `run_turn` cleared the global cancel flag rather than the one it was given. | ||
| 32 | - One-shot mode now exits 130 when aborted and 3 when a tool call was denied, | ||
| 33 | instead of 0 for both. | ||
| 34 | - `bash` approval offered `[y/N/a]` but treated `a` as "no"; it now offers | ||
| 35 | `[y/N]`, matching its documented every-call behaviour. | ||
| 36 | - A non-terminal stdin now says up front that writes and commands will be denied. | ||
| 37 | |||
| 10 | ## 0.4.0 | 38 | ## 0.4.0 |
| 11 | 39 | ||
| 12 | ### Changed | 40 | ### Changed |
| @@ -1,6 +1,6 @@ | |||
| 1 | [package] | 1 | [package] |
| 2 | name = "agent686" | 2 | name = "agent686" |
| 3 | version = "0.4.0" | 3 | version = "0.4.2" |
| 4 | edition = "2021" | 4 | edition = "2021" |
| 5 | description = "A small coding agent for a 32-bit Debian box" | 5 | description = "A small coding agent for a 32-bit Debian box" |
| 6 | publish = false | 6 | 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<Value> { | |||
| 95 | vec![system] | 95 | vec![system] |
| 96 | } | 96 | } |
| 97 | 97 | ||
| 98 | #[derive(Debug, Default, Clone, Copy)] | ||
| 99 | pub struct TurnReport { | ||
| 100 | pub steps: usize, | ||
| 101 | pub aborted: bool, | ||
| 102 | pub denied: usize, | ||
| 103 | } | ||
| 104 | |||
| 105 | pub enum ToolOutcome { | ||
| 106 | Ok(String), | ||
| 107 | Denied, | ||
| 108 | Failed(String), | ||
| 109 | } | ||
| 110 | |||
| 111 | impl ToolOutcome { | ||
| 112 | fn content(&self) -> String { | ||
| 113 | match self { | ||
| 114 | ToolOutcome::Ok(output) => output.clone(), | ||
| 115 | ToolOutcome::Denied => "error: denied by the user".to_string(), | ||
| 116 | ToolOutcome::Failed(error) => format!("error: {error}"), | ||
| 117 | } | ||
| 118 | } | ||
| 119 | |||
| 120 | fn summary(&self) -> String { | ||
| 121 | match self { | ||
| 122 | ToolOutcome::Ok(output) => output | ||
| 123 | .lines() | ||
| 124 | .find(|line| !line.trim().is_empty()) | ||
| 125 | .unwrap_or("") | ||
| 126 | .trim() | ||
| 127 | .to_string(), | ||
| 128 | ToolOutcome::Denied => "denied".to_string(), | ||
| 129 | ToolOutcome::Failed(error) => format!("error: {error}"), | ||
| 130 | } | ||
| 131 | } | ||
| 132 | |||
| 133 | fn denied(&self) -> bool { | ||
| 134 | matches!(self, ToolOutcome::Denied) | ||
| 135 | } | ||
| 136 | } | ||
| 137 | |||
| 98 | /// Runs one turn to completion: model, tools, model, ... until the model answers | 138 | /// Runs one turn to completion: model, tools, model, ... until the model answers |
| 99 | /// without asking for a tool. Every message that is sent is also appended to the | 139 | /// without asking for a tool. Every message that is sent is also appended to the |
| 100 | /// session file, in order, before the next request. | 140 | /// session file, in order, before the next request. |
| @@ -105,8 +145,11 @@ pub fn run_turn( | |||
| 105 | prompt: &str, | 145 | prompt: &str, |
| 106 | cancel: &AtomicBool, | 146 | cancel: &AtomicBool, |
| 107 | approver: &mut Approver, | 147 | approver: &mut Approver, |
| 108 | ) -> Result<(), Error> { | 148 | ) -> Result<TurnReport, Error> { |
| 149 | // A Ctrl-C pressed after the previous turn finished must not abort this one. | ||
| 150 | cancel.store(false, std::sync::atomic::Ordering::SeqCst); | ||
| 109 | let started = Instant::now(); | 151 | let started = Instant::now(); |
| 152 | repair_tool_results(session, history); | ||
| 110 | 153 | ||
| 111 | let user = json!({ "role": "user", "content": prompt }); | 154 | let user = json!({ "role": "user", "content": prompt }); |
| 112 | push(session, history, user, None); | 155 | push(session, history, user, None); |
| @@ -114,11 +157,12 @@ pub fn run_turn( | |||
| 114 | let schemas = tools::schemas(); | 157 | let schemas = tools::schemas(); |
| 115 | let mut steps = 0usize; | 158 | let mut steps = 0usize; |
| 116 | let mut last: Option<Outcome> = None; | 159 | let mut last: Option<Outcome> = None; |
| 160 | let mut aborted = false; | ||
| 161 | let mut denied = 0usize; | ||
| 117 | 162 | ||
| 118 | loop { | 163 | loop { |
| 119 | if cancel.load(std::sync::atomic::Ordering::Relaxed) { | 164 | if cancel.load(std::sync::atomic::Ordering::Relaxed) { |
| 120 | crate::signal::reset(); | 165 | aborted = true; |
| 121 | eprintln!("aborted"); | ||
| 122 | break; | 166 | break; |
| 123 | } | 167 | } |
| 124 | 168 | ||
| @@ -127,8 +171,7 @@ pub fn run_turn( | |||
| 127 | let mut outcome = match provider::chat(cfg, history, &schemas, cancel, &mut renderer) { | 171 | let mut outcome = match provider::chat(cfg, history, &schemas, cancel, &mut renderer) { |
| 128 | Ok(outcome) => outcome, | 172 | Ok(outcome) => outcome, |
| 129 | Err(Error::Aborted) => { | 173 | Err(Error::Aborted) => { |
| 130 | crate::signal::reset(); | 174 | aborted = true; |
| 131 | eprintln!("aborted"); | ||
| 132 | break; | 175 | break; |
| 133 | } | 176 | } |
| 134 | Err(error) => return Err(error), | 177 | Err(error) => return Err(error), |
| @@ -152,54 +195,123 @@ pub fn run_turn( | |||
| 152 | last = Some(outcome); | 195 | last = Some(outcome); |
| 153 | 196 | ||
| 154 | for call in calls { | 197 | for call in calls { |
| 198 | // Cancelling between calls still has to answer every tool call the | ||
| 199 | // assistant message announced: an unanswered id makes the session | ||
| 200 | // permanently unusable, because history is never rewritten. | ||
| 155 | if cancel.load(std::sync::atomic::Ordering::Relaxed) { | 201 | if cancel.load(std::sync::atomic::Ordering::Relaxed) { |
| 156 | crate::signal::reset(); | 202 | aborted = true; |
| 157 | eprintln!("aborted"); | ||
| 158 | break; | ||
| 159 | } | 203 | } |
| 160 | let result = execute(&call, approver); | 204 | let result = if aborted { |
| 161 | ui::tool_result(&result); | 205 | ToolOutcome::Failed("aborted by the user before this call ran".into()) |
| 162 | let content = match result { | 206 | } else { |
| 163 | Ok(output) => output, | 207 | execute(&call, approver) |
| 164 | Err(error) => format!("error: {error}"), | ||
| 165 | }; | 208 | }; |
| 209 | if result.denied() { | ||
| 210 | denied += 1; | ||
| 211 | } | ||
| 212 | ui::tool_result(&result.summary(), aborted); | ||
| 166 | let message = json!({ | 213 | let message = json!({ |
| 167 | "role": "tool", | 214 | "role": "tool", |
| 168 | "tool_call_id": call.id, | 215 | "tool_call_id": call.id, |
| 169 | "content": content, | 216 | "content": result.content(), |
| 170 | }); | 217 | }); |
| 171 | push(session, history, message, None); | 218 | push(session, history, message, None); |
| 172 | } | 219 | } |
| 220 | |||
| 221 | if aborted { | ||
| 222 | break; | ||
| 223 | } | ||
| 173 | } | 224 | } |
| 174 | 225 | ||
| 226 | if aborted { | ||
| 227 | eprintln!("aborted"); | ||
| 228 | } | ||
| 175 | if let Some(outcome) = last { | 229 | if let Some(outcome) = last { |
| 176 | ui::status(steps, started.elapsed(), &outcome); | 230 | ui::status(steps, started.elapsed(), &outcome); |
| 177 | } | 231 | } |
| 178 | Ok(()) | 232 | Ok(TurnReport { |
| 233 | steps, | ||
| 234 | aborted, | ||
| 235 | denied, | ||
| 236 | }) | ||
| 179 | } | 237 | } |
| 180 | 238 | ||
| 181 | fn execute(call: &provider::ToolCall, approver: &mut Approver) -> Result<String, String> { | 239 | /// Any assistant message whose tool calls never got results would be rejected by |
| 240 | /// the provider, and the transcript is append-only. Repair by appending the | ||
| 241 | /// missing results, which is legal: only rewriting is forbidden. | ||
| 242 | fn repair_tool_results(session: &mut Session, history: &mut Vec<Value>) { | ||
| 243 | let index = match history.iter().rposition(|message| { | ||
| 244 | message.get("role").and_then(|role| role.as_str()) == Some("assistant") | ||
| 245 | && message | ||
| 246 | .get("tool_calls") | ||
| 247 | .and_then(|calls| calls.as_array()) | ||
| 248 | .is_some_and(|calls| !calls.is_empty()) | ||
| 249 | }) { | ||
| 250 | Some(index) => index, | ||
| 251 | None => return, | ||
| 252 | }; | ||
| 253 | |||
| 254 | let ids: Vec<String> = history[index]["tool_calls"] | ||
| 255 | .as_array() | ||
| 256 | .map(|calls| { | ||
| 257 | calls | ||
| 258 | .iter() | ||
| 259 | .filter_map(|call| call.get("id").and_then(|id| id.as_str())) | ||
| 260 | .map(|id| id.to_string()) | ||
| 261 | .collect() | ||
| 262 | }) | ||
| 263 | .unwrap_or_default(); | ||
| 264 | |||
| 265 | let answered: std::collections::HashSet<String> = history[index + 1..] | ||
| 266 | .iter() | ||
| 267 | .filter_map(|message| message.get("tool_call_id").and_then(|id| id.as_str())) | ||
| 268 | .map(|id| id.to_string()) | ||
| 269 | .collect(); | ||
| 270 | |||
| 271 | for id in ids { | ||
| 272 | if answered.contains(&id) { | ||
| 273 | continue; | ||
| 274 | } | ||
| 275 | let message = json!({ | ||
| 276 | "role": "tool", | ||
| 277 | "tool_call_id": id, | ||
| 278 | "content": "error: this call was interrupted before it ran", | ||
| 279 | }); | ||
| 280 | push(session, history, message, None); | ||
| 281 | } | ||
| 282 | } | ||
| 283 | |||
| 284 | fn execute(call: &provider::ToolCall, approver: &mut Approver) -> ToolOutcome { | ||
| 182 | let args: Value = serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({})); | 285 | let args: Value = serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({})); |
| 183 | ui::tool_line(&call.name, &args); | 286 | ui::tool_line(&call.name, &args); |
| 184 | 287 | ||
| 185 | match tools::approval(&call.name) { | 288 | match tools::approval(&call.name) { |
| 186 | Approval::Never => tools::run(&call.name, &args), | 289 | Approval::Never => match tools::run(&call.name, &args) { |
| 290 | Ok(output) => ToolOutcome::Ok(output), | ||
| 291 | Err(error) => ToolOutcome::Failed(error), | ||
| 292 | }, | ||
| 187 | Approval::Once => match tools::plan(&call.name, &args) { | 293 | Approval::Once => match tools::plan(&call.name, &args) { |
| 188 | Ok(change) => { | 294 | Ok(change) => { |
| 189 | if approver.allow_edit(change.path(), &change.preview()) { | 295 | if approver.allow_edit(change.path(), &change.preview()) { |
| 190 | change.apply() | 296 | match change.apply() { |
| 297 | Ok(output) => ToolOutcome::Ok(output), | ||
| 298 | Err(error) => ToolOutcome::Failed(error), | ||
| 299 | } | ||
| 191 | } else { | 300 | } else { |
| 192 | Err("denied by the user".into()) | 301 | ToolOutcome::Denied |
| 193 | } | 302 | } |
| 194 | } | 303 | } |
| 195 | Err(error) => Err(error), | 304 | Err(error) => ToolOutcome::Failed(error), |
| 196 | }, | 305 | }, |
| 197 | Approval::EveryCall => { | 306 | Approval::EveryCall => { |
| 198 | let cmd = args.get("cmd").and_then(|v| v.as_str()).unwrap_or(""); | 307 | let cmd = args.get("cmd").and_then(|v| v.as_str()).unwrap_or(""); |
| 199 | if approver.allow_bash(cmd) { | 308 | if approver.allow_bash(cmd) { |
| 200 | tools::run(&call.name, &args) | 309 | match tools::run(&call.name, &args) { |
| 310 | Ok(output) => ToolOutcome::Ok(output), | ||
| 311 | Err(error) => ToolOutcome::Failed(error), | ||
| 312 | } | ||
| 201 | } else { | 313 | } else { |
| 202 | Err("denied by the user".into()) | 314 | ToolOutcome::Denied |
| 203 | } | 315 | } |
| 204 | } | 316 | } |
| 205 | } | 317 | } |
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() { | |||
| 114 | 114 | ||
| 115 | if !prompt_words.is_empty() { | 115 | if !prompt_words.is_empty() { |
| 116 | let prompt = prompt_words.join(" "); | 116 | let prompt = prompt_words.join(" "); |
| 117 | if let Err(error) = agent::run_turn( | 117 | match agent::run_turn( |
| 118 | &cfg, | 118 | &cfg, |
| 119 | &mut session, | 119 | &mut session, |
| 120 | &mut history, | 120 | &mut history, |
| @@ -122,14 +122,30 @@ fn main() { | |||
| 122 | &signal::CANCEL, | 122 | &signal::CANCEL, |
| 123 | &mut approver, | 123 | &mut approver, |
| 124 | ) { | 124 | ) { |
| 125 | eprintln!("agent686: {error}"); | 125 | Ok(report) => { |
| 126 | std::process::exit(1); | 126 | if report.aborted { |
| 127 | std::process::exit(130); | ||
| 128 | } | ||
| 129 | if report.denied > 0 { | ||
| 130 | std::process::exit(3); | ||
| 131 | } | ||
| 132 | } | ||
| 133 | Err(error) => { | ||
| 134 | eprintln!("agent686: {error}"); | ||
| 135 | std::process::exit(1); | ||
| 136 | } | ||
| 127 | } | 137 | } |
| 128 | return; | 138 | return; |
| 129 | } | 139 | } |
| 130 | 140 | ||
| 131 | let mut editor = Editor::new(); | 141 | let mut editor = Editor::new(); |
| 132 | let interactive = editor.is_interactive(); | 142 | let interactive = editor.is_interactive(); |
| 143 | if !interactive && !cfg.yolo { | ||
| 144 | eprintln!( | ||
| 145 | "agent686: stdin is not a terminal, so write/edit/bash will be denied; \ | ||
| 146 | pass --yolo to allow them" | ||
| 147 | ); | ||
| 148 | } | ||
| 133 | if interactive { | 149 | if interactive { |
| 134 | eprintln!( | 150 | eprintln!( |
| 135 | "agent686 · {} · session {}{}", | 151 | "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 { | |||
| 115 | self.buf.drain(..start); | 115 | self.buf.drain(..start); |
| 116 | out | 116 | out |
| 117 | } | 117 | } |
| 118 | |||
| 119 | /// Anything left when the connection closes without a final newline. | ||
| 120 | pub fn finish(&mut self) -> Vec<String> { | ||
| 121 | let mut out = Vec::new(); | ||
| 122 | if !self.buf.is_empty() { | ||
| 123 | let mut line = &self.buf[..]; | ||
| 124 | if line.last() == Some(&b'\r') { | ||
| 125 | line = &line[..line.len() - 1]; | ||
| 126 | } | ||
| 127 | if let Some(payload) = line.strip_prefix(b"data:") { | ||
| 128 | let payload = payload.strip_prefix(b" ").unwrap_or(payload); | ||
| 129 | out.push(String::from_utf8_lossy(payload).into_owned()); | ||
| 130 | } | ||
| 131 | self.buf.clear(); | ||
| 132 | } | ||
| 133 | out | ||
| 134 | } | ||
| 118 | } | 135 | } |
| 119 | 136 | ||
| 120 | const MAX_ATTEMPTS: usize = 4; | 137 | const MAX_ATTEMPTS: usize = 4; |
| @@ -290,9 +307,12 @@ pub fn chat( | |||
| 290 | let mut decoder = SseDecoder::new(); | 307 | let mut decoder = SseDecoder::new(); |
| 291 | let mut buf = [0u8; 8192]; | 308 | let mut buf = [0u8; 8192]; |
| 292 | let mut reader = resp.body_mut().as_reader(); | 309 | let mut reader = resp.body_mut().as_reader(); |
| 310 | let mut calls: std::collections::BTreeMap<usize, ToolCall> = std::collections::BTreeMap::new(); | ||
| 311 | let mut completed = false; | ||
| 293 | let mut done = false; | 312 | let mut done = false; |
| 313 | let mut dropped = 0usize; | ||
| 294 | 314 | ||
| 295 | while !done { | 315 | loop { |
| 296 | // Blocking reads mean an abort is only noticed when bytes arrive or the | 316 | // Blocking reads mean an abort is only noticed when bytes arrive or the |
| 297 | // per-read timeout fires. Good enough: the model streams constantly. | 317 | // per-read timeout fires. Good enough: the model streams constantly. |
| 298 | if cancel.load(Ordering::Relaxed) { | 318 | if cancel.load(Ordering::Relaxed) { |
| @@ -304,31 +324,83 @@ pub fn chat( | |||
| 304 | Err(e) => return Err(Error::Transport(e.to_string())), | 324 | Err(e) => return Err(Error::Transport(e.to_string())), |
| 305 | }; | 325 | }; |
| 306 | for data in decoder.feed(&buf[..n]) { | 326 | for data in decoder.feed(&buf[..n]) { |
| 307 | if data.is_empty() { | 327 | if handle_event(&data, &mut outcome, &mut calls, &mut completed, &mut dropped, sink) { |
| 308 | continue; | ||
| 309 | } | ||
| 310 | if data.trim() == "[DONE]" { | ||
| 311 | done = true; | 328 | done = true; |
| 312 | break; | 329 | break; |
| 313 | } | 330 | } |
| 314 | let chunk: Chunk = match serde_json::from_str(&data) { | 331 | } |
| 315 | Ok(c) => c, | 332 | if done { |
| 316 | // A malformed frame is dropped rather than killing the turn. | 333 | break; |
| 317 | Err(_) => continue, | 334 | } |
| 318 | }; | 335 | } |
| 319 | apply_chunk(&chunk, &mut outcome, sink); | 336 | |
| 337 | // A final `data:` frame with no trailing newline is legitimate. | ||
| 338 | if !done { | ||
| 339 | for data in decoder.finish() { | ||
| 340 | if handle_event(&data, &mut outcome, &mut calls, &mut completed, &mut dropped, sink) { | ||
| 341 | break; | ||
| 342 | } | ||
| 320 | } | 343 | } |
| 321 | } | 344 | } |
| 322 | 345 | ||
| 346 | outcome.tool_calls = calls.into_values().collect(); | ||
| 323 | if outcome.usage.as_ref().is_some_and(|u| u.is_null()) { | 347 | if outcome.usage.as_ref().is_some_and(|u| u.is_null()) { |
| 324 | outcome.usage = None; | 348 | outcome.usage = None; |
| 325 | } | 349 | } |
| 326 | 350 | ||
| 351 | if dropped > 0 { | ||
| 352 | eprintln!("agent686: ignored {dropped} malformed stream frame(s)"); | ||
| 353 | } | ||
| 354 | |||
| 355 | // A connection that closes early, or a 200 that is not SSE at all, must not | ||
| 356 | // be recorded as a complete answer. | ||
| 357 | if !completed { | ||
| 358 | return Err(Error::Transport(format!( | ||
| 359 | "stream ended before completion ({} bytes of text, {} tool call(s)); \ | ||
| 360 | the turn was not recorded as answered", | ||
| 361 | outcome.content.len(), | ||
| 362 | outcome.tool_calls.len() | ||
| 363 | ))); | ||
| 364 | } | ||
| 365 | |||
| 327 | sink.done(&outcome, started.elapsed()); | 366 | sink.done(&outcome, started.elapsed()); |
| 328 | Ok(outcome) | 367 | Ok(outcome) |
| 329 | } | 368 | } |
| 330 | 369 | ||
| 331 | fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { | 370 | fn handle_event( |
| 371 | data: &str, | ||
| 372 | outcome: &mut Outcome, | ||
| 373 | calls: &mut std::collections::BTreeMap<usize, ToolCall>, | ||
| 374 | completed: &mut bool, | ||
| 375 | dropped: &mut usize, | ||
| 376 | sink: &mut dyn Sink, | ||
| 377 | ) -> bool { | ||
| 378 | if data.is_empty() { | ||
| 379 | return false; | ||
| 380 | } | ||
| 381 | if data.trim() == "[DONE]" { | ||
| 382 | *completed = true; | ||
| 383 | return true; | ||
| 384 | } | ||
| 385 | match serde_json::from_str::<Chunk>(data) { | ||
| 386 | Ok(chunk) => { | ||
| 387 | if chunk.choices.iter().any(|choice| choice.finish_reason.is_some()) { | ||
| 388 | *completed = true; | ||
| 389 | } | ||
| 390 | apply_chunk(&chunk, outcome, calls, sink); | ||
| 391 | } | ||
| 392 | // Counted and reported rather than silently swallowed. | ||
| 393 | Err(_) => *dropped += 1, | ||
| 394 | } | ||
| 395 | false | ||
| 396 | } | ||
| 397 | |||
| 398 | fn apply_chunk( | ||
| 399 | chunk: &Chunk, | ||
| 400 | outcome: &mut Outcome, | ||
| 401 | calls: &mut std::collections::BTreeMap<usize, ToolCall>, | ||
| 402 | sink: &mut dyn Sink, | ||
| 403 | ) { | ||
| 332 | if let Some(usage) = &chunk.usage { | 404 | if let Some(usage) = &chunk.usage { |
| 333 | outcome.usage = Some(usage.clone()); | 405 | outcome.usage = Some(usage.clone()); |
| 334 | } | 406 | } |
| @@ -345,9 +417,9 @@ fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { | |||
| 345 | sink.text(t); | 417 | sink.text(t); |
| 346 | } | 418 | } |
| 347 | } | 419 | } |
| 348 | if let Some(calls) = &choice.delta.tool_calls { | 420 | if let Some(deltas) = &choice.delta.tool_calls { |
| 349 | for call in calls { | 421 | for delta in deltas { |
| 350 | accumulate_tool_call(&mut outcome.tool_calls, call); | 422 | accumulate_tool_call(calls, delta); |
| 351 | } | 423 | } |
| 352 | } | 424 | } |
| 353 | if let Some(finish) = &choice.finish_reason { | 425 | if let Some(finish) = &choice.finish_reason { |
| @@ -357,18 +429,19 @@ fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { | |||
| 357 | } | 429 | } |
| 358 | 430 | ||
| 359 | /// Tool call deltas arrive split across chunks and are keyed by `index`: the | 431 | /// Tool call deltas arrive split across chunks and are keyed by `index`: the |
| 360 | /// name and id usually come once, the arguments a fragment at a time. | 432 | /// name and id usually come once, the arguments a fragment at a time. A map |
| 361 | fn accumulate_tool_call(calls: &mut Vec<ToolCall>, delta: &ToolCallDelta) { | 433 | /// keyed by index means a missing or non-contiguous index cannot invent an |
| 362 | while calls.len() <= delta.index { | 434 | /// empty call or shift the others. |
| 363 | let index = calls.len(); | 435 | fn accumulate_tool_call( |
| 364 | calls.push(ToolCall { | 436 | calls: &mut std::collections::BTreeMap<usize, ToolCall>, |
| 365 | index, | 437 | delta: &ToolCallDelta, |
| 366 | id: String::new(), | 438 | ) { |
| 367 | name: String::new(), | 439 | let call = calls.entry(delta.index).or_insert_with(|| ToolCall { |
| 368 | arguments: String::new(), | 440 | index: delta.index, |
| 369 | }); | 441 | id: String::new(), |
| 370 | } | 442 | name: String::new(), |
| 371 | let call = &mut calls[delta.index]; | 443 | arguments: String::new(), |
| 444 | }); | ||
| 372 | if let Some(id) = &delta.id { | 445 | if let Some(id) = &delta.id { |
| 373 | call.id.push_str(id); | 446 | call.id.push_str(id); |
| 374 | } | 447 | } |
| @@ -434,6 +507,7 @@ struct Delta { | |||
| 434 | 507 | ||
| 435 | #[derive(Debug, Deserialize)] | 508 | #[derive(Debug, Deserialize)] |
| 436 | struct ToolCallDelta { | 509 | struct ToolCallDelta { |
| 510 | #[serde(default)] | ||
| 437 | index: usize, | 511 | index: usize, |
| 438 | #[serde(default)] | 512 | #[serde(default)] |
| 439 | id: Option<String>, | 513 | id: Option<String>, |
| @@ -104,14 +104,13 @@ pub fn tool_line(name: &str, args: &serde_json::Value) { | |||
| 104 | let _ = std::io::stdout().flush(); | 104 | let _ = std::io::stdout().flush(); |
| 105 | } | 105 | } |
| 106 | 106 | ||
| 107 | pub fn tool_result(result: &Result<String, String>) { | 107 | pub fn tool_result(summary: &str, aborted: bool) { |
| 108 | let text = match result { | 108 | let text = if aborted { |
| 109 | Ok(output) => output, | 109 | "aborted".to_string() |
| 110 | Err(error) => error, | 110 | } else { |
| 111 | crate::provider::truncate(summary.trim(), 100) | ||
| 111 | }; | 112 | }; |
| 112 | let first = text.lines().find(|l| !l.trim().is_empty()).unwrap_or(""); | 113 | println!(" {} {}", paint("2", "â””"), paint("2", &text)); |
| 113 | let summary = crate::provider::truncate(first.trim(), 100); | ||
| 114 | println!(" {} {}", paint("2", "â””"), paint("2", &summary)); | ||
| 115 | let _ = std::io::stdout().flush(); | 114 | let _ = std::io::stdout().flush(); |
| 116 | } | 115 | } |
| 117 | 116 | ||
| @@ -163,7 +162,7 @@ impl Approver { | |||
| 163 | self.yolo | 162 | self.yolo |
| 164 | } | 163 | } |
| 165 | 164 | ||
| 166 | fn ask(&self, question: &str) -> Answer { | 165 | fn ask(&self, question: &str, allow_always: bool) -> Answer { |
| 167 | if self.yolo { | 166 | if self.yolo { |
| 168 | return Answer::Yes; | 167 | return Answer::Yes; |
| 169 | } | 168 | } |
| @@ -174,7 +173,8 @@ impl Approver { | |||
| 174 | ); | 173 | ); |
| 175 | return Answer::No; | 174 | return Answer::No; |
| 176 | } | 175 | } |
| 177 | print!("\n{} {} ", question, paint("2", "[y/N/a]")); | 176 | let hint = if allow_always { "[y/N/a]" } else { "[y/N]" }; |
| 177 | print!("\n{} {} ", question, paint("2", hint)); | ||
| 178 | let _ = std::io::stdout().flush(); | 178 | let _ = std::io::stdout().flush(); |
| 179 | 179 | ||
| 180 | let mut line = String::new(); | 180 | let mut line = String::new(); |
| @@ -183,7 +183,7 @@ impl Approver { | |||
| 183 | } | 183 | } |
| 184 | match line.trim().to_ascii_lowercase().as_str() { | 184 | match line.trim().to_ascii_lowercase().as_str() { |
| 185 | "y" | "yes" => Answer::Yes, | 185 | "y" | "yes" => Answer::Yes, |
| 186 | "a" | "always" => Answer::Always, | 186 | "a" | "always" if allow_always => Answer::Always, |
| 187 | _ => Answer::No, | 187 | _ => Answer::No, |
| 188 | } | 188 | } |
| 189 | } | 189 | } |
| @@ -194,7 +194,7 @@ impl Approver { | |||
| 194 | return true; | 194 | return true; |
| 195 | } | 195 | } |
| 196 | println!("{preview}"); | 196 | println!("{preview}"); |
| 197 | match self.ask(&format!("apply this change to {path}?")) { | 197 | match self.ask(&format!("apply this change to {path}?"), true) { |
| 198 | Answer::Yes => true, | 198 | Answer::Yes => true, |
| 199 | Answer::Always => { | 199 | Answer::Always => { |
| 200 | self.edits_allowed = true; | 200 | self.edits_allowed = true; |
| @@ -209,6 +209,8 @@ impl Approver { | |||
| 209 | if self.yolo { | 209 | if self.yolo { |
| 210 | return true; | 210 | return true; |
| 211 | } | 211 | } |
| 212 | self.ask(&format!("run: {}", crate::provider::truncate(cmd, 200))) == Answer::Yes | 212 | // Bash prompts every call by design, so "always" is not offered here. |
| 213 | self.ask(&format!("run: {}", crate::provider::truncate(cmd, 200)), false) | ||
| 214 | == Answer::Yes | ||
| 213 | } | 215 | } |
| 214 | } | 216 | } |
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() { | |||
| 190 | ); | 190 | ); |
| 191 | assert_eq!(history[4]["content"], "understood"); | 191 | assert_eq!(history[4]["content"], "understood"); |
| 192 | } | 192 | } |
| 193 | |||
| 194 | fn tool_call(index: usize, id: &str, name: &str, arguments: serde_json::Value) -> serde_json::Value { | ||
| 195 | json!({ | ||
| 196 | "index": index, | ||
| 197 | "id": id, | ||
| 198 | "function": { "name": name, "arguments": arguments.to_string() } | ||
| 199 | }) | ||
| 200 | } | ||
| 201 | |||
| 202 | #[test] | ||
| 203 | fn aborting_between_tool_calls_answers_every_call() { | ||
| 204 | let dir = temp_dir("abort-mid-calls"); | ||
| 205 | let slow = sse(&format!( | ||
| 206 | "data: {}\n\ndata: [DONE]\n\n", | ||
| 207 | json!({ | ||
| 208 | "choices": [{ | ||
| 209 | "delta": { "tool_calls": [ | ||
| 210 | tool_call(0, "call_a", "bash", json!({ "cmd": "sleep 0.5" })), | ||
| 211 | tool_call(1, "call_b", "write", json!({ "path": dir.join("b.txt"), "content": "b" })), | ||
| 212 | tool_call(2, "call_c", "write", json!({ "path": dir.join("c.txt"), "content": "c" })) | ||
| 213 | ]}, | ||
| 214 | "finish_reason": "tool_calls" | ||
| 215 | }] | ||
| 216 | }) | ||
| 217 | )); | ||
| 218 | // If the harness wrongly continues after the abort, it would consume this. | ||
| 219 | let after = sse( | ||
| 220 | "data: {\"choices\":[{\"delta\":{\"content\":\"should not be reached\"},\"finish_reason\":\"stop\"}]}\n\n\ | ||
| 221 | data: [DONE]\n\n", | ||
| 222 | ); | ||
| 223 | |||
| 224 | let base = serve_sequence(vec![slow, after]); | ||
| 225 | std::env::set_var("AGENT686_DATA", dir.join("data")); | ||
| 226 | |||
| 227 | let system = agent::system_prompt(); | ||
| 228 | let mut session = Session::create("test-model", &system).unwrap(); | ||
| 229 | let cfg = Config { | ||
| 230 | base_url: base, | ||
| 231 | api_key: "test-key".into(), | ||
| 232 | model: "test-model".into(), | ||
| 233 | session: session.id.clone(), | ||
| 234 | yolo: true, | ||
| 235 | }; | ||
| 236 | let mut history = agent::new_history(system); | ||
| 237 | let mut approver = Approver::new(true); | ||
| 238 | let cancel = std::sync::Arc::new(AtomicBool::new(false)); | ||
| 239 | |||
| 240 | let flag = cancel.clone(); | ||
| 241 | thread::spawn(move || { | ||
| 242 | thread::sleep(std::time::Duration::from_millis(150)); | ||
| 243 | flag.store(true, std::sync::atomic::Ordering::SeqCst); | ||
| 244 | }); | ||
| 245 | |||
| 246 | let report = agent::run_turn( | ||
| 247 | &cfg, | ||
| 248 | &mut session, | ||
| 249 | &mut history, | ||
| 250 | "do three things", | ||
| 251 | &cancel, | ||
| 252 | &mut approver, | ||
| 253 | ) | ||
| 254 | .expect("an abort is not an error"); | ||
| 255 | |||
| 256 | assert!(report.aborted); | ||
| 257 | |||
| 258 | // Every announced tool call must have exactly one result, or the provider | ||
| 259 | // rejects the session forever and the transcript cannot be rewritten. | ||
| 260 | let answered: Vec<String> = history | ||
| 261 | .iter() | ||
| 262 | .filter(|message| message.get("role").and_then(|r| r.as_str()) == Some("tool")) | ||
| 263 | .filter_map(|message| message.get("tool_call_id").and_then(|id| id.as_str()).map(|s| s.to_string())) | ||
| 264 | .collect(); | ||
| 265 | assert_eq!(answered, vec!["call_a", "call_b", "call_c"], "{answered:?}"); | ||
| 266 | |||
| 267 | // The loop stopped: no assistant text was ever appended. | ||
| 268 | assert_eq!(history.last().unwrap()["role"], "tool"); | ||
| 269 | assert!(fs::read_to_string(session.path()).unwrap().lines().count() >= 5); | ||
| 270 | } | ||
| 271 | |||
| 272 | #[test] | ||
| 273 | fn opening_a_session_with_unanswered_calls_repairs_it() { | ||
| 274 | let dir = temp_dir("repair"); | ||
| 275 | std::env::set_var("AGENT686_DATA", dir.join("data")); | ||
| 276 | |||
| 277 | let base = serve_sequence(vec![sse( | ||
| 278 | "data: {\"choices\":[{\"delta\":{\"content\":\"carrying on\"},\"finish_reason\":\"stop\"}]}\n\n\ | ||
| 279 | data: [DONE]\n\n", | ||
| 280 | )]); | ||
| 281 | |||
| 282 | let system = agent::system_prompt(); | ||
| 283 | let mut session = Session::create("test-model", &system).unwrap(); | ||
| 284 | let mut history = agent::new_history(system); | ||
| 285 | |||
| 286 | // A transcript shape left behind by an older build: two calls, one result. | ||
| 287 | let assistant = json!({ | ||
| 288 | "role": "assistant", | ||
| 289 | "content": null, | ||
| 290 | "tool_calls": [ | ||
| 291 | { "id": "call_1", "type": "function", "function": { "name": "read", "arguments": "{}" } }, | ||
| 292 | { "id": "call_2", "type": "function", "function": { "name": "read", "arguments": "{}" } } | ||
| 293 | ] | ||
| 294 | }); | ||
| 295 | session.append(&assistant, None).unwrap(); | ||
| 296 | history.push(assistant); | ||
| 297 | let partial = json!({ "role": "tool", "tool_call_id": "call_1", "content": "ok" }); | ||
| 298 | session.append(&partial, None).unwrap(); | ||
| 299 | history.push(partial); | ||
| 300 | |||
| 301 | let cfg = Config { | ||
| 302 | base_url: base, | ||
| 303 | api_key: "test-key".into(), | ||
| 304 | model: "test-model".into(), | ||
| 305 | session: session.id.clone(), | ||
| 306 | yolo: true, | ||
| 307 | }; | ||
| 308 | let mut approver = Approver::new(true); | ||
| 309 | agent::run_turn( | ||
| 310 | &cfg, | ||
| 311 | &mut session, | ||
| 312 | &mut history, | ||
| 313 | "go on", | ||
| 314 | &AtomicBool::new(false), | ||
| 315 | &mut approver, | ||
| 316 | ) | ||
| 317 | .expect("repair should let the turn run"); | ||
| 318 | |||
| 319 | let repaired = history.iter().any(|message| { | ||
| 320 | message.get("tool_call_id").and_then(|id| id.as_str()) == Some("call_2") | ||
| 321 | && message | ||
| 322 | .get("content") | ||
| 323 | .and_then(|c| c.as_str()) | ||
| 324 | .is_some_and(|c| c.contains("interrupted")) | ||
| 325 | }); | ||
| 326 | assert!(repaired, "missing result for call_2 should be synthesised"); | ||
| 327 | } | ||
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() { | |||
| 326 | let message = format!("{error}"); | 326 | let message = format!("{error}"); |
| 327 | assert!(message.contains("OPENCODE_API_KEY"), "{message}"); | 327 | assert!(message.contains("OPENCODE_API_KEY"), "{message}"); |
| 328 | } | 328 | } |
| 329 | |||
| 330 | #[test] | ||
| 331 | fn a_truncated_stream_is_an_error_not_an_answer() { | ||
| 332 | const TRUNCATED: &str = concat!( | ||
| 333 | "HTTP/1.1 200 OK\r\n", | ||
| 334 | "Content-Type: text/event-stream\r\n", | ||
| 335 | "Connection: close\r\n", | ||
| 336 | "\r\n", | ||
| 337 | "data: {\"choices\":[{\"delta\":{\"content\":\"partial\"}}]}\n\n", | ||
| 338 | ); | ||
| 339 | let (base, _rx) = serve_once(TRUNCATED); | ||
| 340 | let mut sink = Collector::default(); | ||
| 341 | let error = provider::chat( | ||
| 342 | &config(base), | ||
| 343 | &[json!({ "role": "user", "content": "hi" })], | ||
| 344 | &[], | ||
| 345 | &AtomicBool::new(false), | ||
| 346 | &mut sink, | ||
| 347 | ) | ||
| 348 | .expect_err("a stream without [DONE] or finish_reason must fail"); | ||
| 349 | |||
| 350 | let message = format!("{error}"); | ||
| 351 | assert!(message.contains("ended before completion"), "{message}"); | ||
| 352 | } | ||
| 353 | |||
| 354 | #[test] | ||
| 355 | fn a_non_sse_200_is_an_error_not_an_empty_answer() { | ||
| 356 | const JSON: &str = concat!( | ||
| 357 | "HTTP/1.1 200 OK\r\n", | ||
| 358 | "Content-Type: application/json\r\n", | ||
| 359 | "Connection: close\r\n", | ||
| 360 | "\r\n", | ||
| 361 | "{\"id\":\"x\",\"choices\":[{\"message\":{\"content\":\"hello\"}}]}", | ||
| 362 | ); | ||
| 363 | let (base, _rx) = serve_once(JSON); | ||
| 364 | let mut sink = Collector::default(); | ||
| 365 | let error = provider::chat( | ||
| 366 | &config(base), | ||
| 367 | &[json!({ "role": "user", "content": "hi" })], | ||
| 368 | &[], | ||
| 369 | &AtomicBool::new(false), | ||
| 370 | &mut sink, | ||
| 371 | ) | ||
| 372 | .expect_err("a non-streaming body must not look like a blank answer"); | ||
| 373 | assert!(format!("{error}").contains("ended before completion")); | ||
| 374 | } | ||
| 375 | |||
| 376 | #[test] | ||
| 377 | fn finish_reason_without_done_marker_is_accepted() { | ||
| 378 | const SSE: &str = concat!( | ||
| 379 | "HTTP/1.1 200 OK\r\n", | ||
| 380 | "Content-Type: text/event-stream\r\n", | ||
| 381 | "Connection: close\r\n", | ||
| 382 | "\r\n", | ||
| 383 | "data: {\"choices\":[{\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\n", | ||
| 384 | ); | ||
| 385 | let (base, _rx) = serve_once(SSE); | ||
| 386 | let mut sink = Collector::default(); | ||
| 387 | let outcome = provider::chat( | ||
| 388 | &config(base), | ||
| 389 | &[json!({ "role": "user", "content": "hi" })], | ||
| 390 | &[], | ||
| 391 | &AtomicBool::new(false), | ||
| 392 | &mut sink, | ||
| 393 | ) | ||
| 394 | .expect("finish_reason is enough"); | ||
| 395 | assert_eq!(outcome.content, "ok"); | ||
| 396 | } | ||
| 397 | |||
| 398 | #[test] | ||
| 399 | fn a_tool_call_without_an_index_still_assembles() { | ||
| 400 | const SSE: &str = concat!( | ||
| 401 | "HTTP/1.1 200 OK\r\n", | ||
| 402 | "Content-Type: text/event-stream\r\n", | ||
| 403 | "Connection: close\r\n", | ||
| 404 | "\r\n", | ||
| 405 | "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"id\":\"call_1\",\"function\":{\"name\":\"read\",\"arguments\":\"{\\\"path\\\":\\\"a\\\"}\"}}]},\"finish_reason\":\"tool_calls\"}]}\n\n", | ||
| 406 | "data: [DONE]\n\n", | ||
| 407 | ); | ||
| 408 | let (base, _rx) = serve_once(SSE); | ||
| 409 | let mut sink = Collector::default(); | ||
| 410 | let outcome = provider::chat( | ||
| 411 | &config(base), | ||
| 412 | &[json!({ "role": "user", "content": "hi" })], | ||
| 413 | &[], | ||
| 414 | &AtomicBool::new(false), | ||
| 415 | &mut sink, | ||
| 416 | ) | ||
| 417 | .expect("chat should succeed"); | ||
| 418 | |||
| 419 | assert_eq!(outcome.tool_calls.len(), 1); | ||
| 420 | assert_eq!(outcome.tool_calls[0].name, "read"); | ||
| 421 | assert_eq!(outcome.tool_calls[0].arguments, "{\"path\":\"a\"}"); | ||
| 422 | } | ||
| 423 | |||
| 424 | #[test] | ||
| 425 | fn a_final_frame_without_a_newline_is_not_lost() { | ||
| 426 | const SSE: &str = concat!( | ||
| 427 | "HTTP/1.1 200 OK\r\n", | ||
| 428 | "Content-Type: text/event-stream\r\n", | ||
| 429 | "Connection: close\r\n", | ||
| 430 | "\r\n", | ||
| 431 | "data: {\"choices\":[{\"delta\":{\"content\":\"last\"},\"finish_reason\":\"stop\"}]}", | ||
| 432 | ); | ||
| 433 | let (base, _rx) = serve_once(SSE); | ||
| 434 | let mut sink = Collector::default(); | ||
| 435 | let outcome = provider::chat( | ||
| 436 | &config(base), | ||
| 437 | &[json!({ "role": "user", "content": "hi" })], | ||
| 438 | &[], | ||
| 439 | &AtomicBool::new(false), | ||
| 440 | &mut sink, | ||
| 441 | ) | ||
| 442 | .expect("a trailing frame without a newline should still count"); | ||
| 443 | assert_eq!(outcome.content, "last"); | ||
| 444 | } | ||
diff --git a/twocalls.log b/twocalls.log new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/twocalls.log | |||
