summaryrefslogtreecommitdiffstats
path: root/src/agent.rs
diff options
context:
space:
mode:
authorsalmonik <salmonik@tuta.io>2026-11-15 15:37:56 +0100
committersalmonik <salmonik@tuta.io>2026-11-15 15:37:56 +0100
commit714534475818e6e5dced91ecad100ca9e286ccce (patch)
treedd36ffe02376e06bd92d9e3650bcd4ddb21d0768 /src/agent.rs
parent0.4.0: grep takes a regular expression, fixed=true for literals (diff)
downloadagent686-714534475818e6e5dced91ecad100ca9e286ccce.tar.gz
agent686-714534475818e6e5dced91ecad100ca9e286ccce.zip
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
Diffstat (limited to 'src/agent.rs')
-rw-r--r--src/agent.rs156
1 files changed, 134 insertions, 22 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 }