aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/agent.rs156
-rw-r--r--src/main.rs22
-rw-r--r--src/provider.rs128
-rw-r--r--src/ui.rs26
4 files changed, 268 insertions, 64 deletions
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)]
99pub struct TurnReport {
100 pub steps: usize,
101 pub aborted: bool,
102 pub denied: usize,
103}
104
105pub enum ToolOutcome {
106 Ok(String),
107 Denied,
108 Failed(String),
109}
110
111impl 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
181fn 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.
242fn 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
284fn 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
120const MAX_ATTEMPTS: usize = 4; 137const 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
331fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { 370fn 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
398fn 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
361fn 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(); 435fn 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)]
436struct ToolCallDelta { 509struct ToolCallDelta {
510 #[serde(default)]
437 index: usize, 511 index: usize,
438 #[serde(default)] 512 #[serde(default)]
439 id: Option<String>, 513 id: Option<String>,
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) {
104 let _ = std::io::stdout().flush(); 104 let _ = std::io::stdout().flush();
105} 105}
106 106
107pub fn tool_result(result: &Result<String, String>) { 107pub 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}