aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--CHANGELOG.md20
-rw-r--r--Cargo.lock2
-rw-r--r--Cargo.toml2
-rw-r--r--README.md1
-rw-r--r--src/agent.rs13
-rw-r--r--src/main.rs43
-rw-r--r--src/provider.rs15
-rw-r--r--src/session.rs66
-rw-r--r--src/tools/mod.rs24
-rw-r--r--tests/loop.rs53
-rw-r--r--tests/mock.rs25
-rw-r--r--tests/sessions.rs59
-rw-r--r--tests/tools.rs15
13 files changed, 327 insertions, 11 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 99b92db..5d1e21e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,26 @@ break the interface, **PATCH** for bug fixes.
7file, and the tool schemas the model sees. Anything a script or a resumed session 7file, and the tool schemas the model sees. Anything a script or a resumed session
8could depend on counts as API. 8could depend on counts as API.
9 9
10## 0.7.0
11
12### Added
13- Resuming a session (`--continue` or `--session`) prints the last assistant
14 block before the prompt, or the last reasoning block when the model produced no
15 content. Twenty lines at most, with a pointer to `--show`.
16- `AGENT686_DEBUG_STREAM=1` prints every SSE frame to stderr (truncated), for
17 diagnosing provider quirks without a proxy.
18
19### Fixed
20- A `bash`, `write` or `edit` call with missing or unparsable arguments used to
21 reach the approval prompt, so you were asked to approve an empty command.
22 Arguments are validated before any prompt: invalid JSON and empty required
23 fields are returned to the model as errors instead.
24- Empty placeholder tool calls sent by a provider are dropped and reported,
25 rather than becoming a blank approval.
26- A session containing a line with invalid UTF-8 — the shape a torn write leaves
27 after `kill -9` — could not be opened at all. Reading is now byte-based and
28 lossy per line, so a torn line costs that line, not the session.
29
10## 0.6.2 30## 0.6.2
11 31
12### Fixed 32### Fixed
diff --git a/Cargo.lock b/Cargo.lock
index 0ce01e2..a6ef8f8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
10 10
11[[package]] 11[[package]]
12name = "agent686" 12name = "agent686"
13version = "0.6.2" 13version = "0.7.0"
14dependencies = [ 14dependencies = [
15 "crossterm", 15 "crossterm",
16 "libc", 16 "libc",
diff --git a/Cargo.toml b/Cargo.toml
index 38fc125..72520a4 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
1[package] 1[package]
2name = "agent686" 2name = "agent686"
3version = "0.6.2" 3version = "0.7.0"
4edition = "2021" 4edition = "2021"
5description = "A small coding agent for a 32-bit Debian box" 5description = "A small coding agent for a 32-bit Debian box"
6publish = false 6publish = false
diff --git a/README.md b/README.md
index e4d6fbc..f98e661 100644
--- a/README.md
+++ b/README.md
@@ -30,6 +30,7 @@ export OPENCODE_API_KEY=... # or write it to ~/.config/agent686/key
30./agent686 -c # continue the most recent session 30./agent686 -c # continue the most recent session
31./agent686 --session <id> # resume it, or create it if the id is new 31./agent686 --session <id> # resume it, or create it if the id is new
32./agent686 --list # id, model, message count, age 32./agent686 --list # id, model, message count, age
33./agent686 -c # continue; prints where you left off
33./agent686 --show [id] # render a transcript 34./agent686 --show [id] # render a transcript
34./agent686 --doctor # key, dirs, provider, model 35./agent686 --doctor # key, dirs, provider, model
35./agent686 --yolo "..." # approve every tool call 36./agent686 --yolo "..." # approve every tool call
diff --git a/src/agent.rs b/src/agent.rs
index 4bf19ed..f0e1292 100644
--- a/src/agent.rs
+++ b/src/agent.rs
@@ -342,8 +342,19 @@ fn execute(
342 cancel: &AtomicBool, 342 cancel: &AtomicBool,
343 step: usize, 343 step: usize,
344) -> ToolOutcome { 344) -> ToolOutcome {
345 let args: Value = serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({})); 345 let args: Value = match serde_json::from_str(&call.arguments) {
346 Ok(args) => args,
347 Err(error) => {
348 return ToolOutcome::Failed(format!(
349 "arguments were not valid JSON ({error}); issue the call again with the \
350 complete arguments"
351 ))
352 }
353 };
346 ui::tool_line(step, &call.name, &args); 354 ui::tool_line(step, &call.name, &args);
355 if let Err(error) = tools::validate(&call.name, &args) {
356 return ToolOutcome::Failed(format!("{error}; the call was not run"));
357 }
347 358
348 match tools::approval(&call.name) { 359 match tools::approval(&call.name) {
349 Approval::Never => match tools::run(&call.name, &args, cancel) { 360 Approval::Never => match tools::run(&call.name, &args, cancel) {
diff --git a/src/main.rs b/src/main.rs
index 91d54da..45ca8c6 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -195,6 +195,7 @@ fn run(args: Args) {
195 } 195 }
196 }; 196 };
197 197
198 let resuming = args.session.is_some() || args.continue_last;
198 let (mut session, mut history) = match open_session(&cfg, args.session, args.continue_last) { 199 let (mut session, mut history) = match open_session(&cfg, args.session, args.continue_last) {
199 Ok(pair) => pair, 200 Ok(pair) => pair,
200 Err(message) => { 201 Err(message) => {
@@ -205,6 +206,9 @@ fn run(args: Args) {
205 cfg.session = session.id.clone(); 206 cfg.session = session.id.clone();
206 207
207 warn_if_moved(&session); 208 warn_if_moved(&session);
209 if resuming {
210 print_last_reply(&session.id);
211 }
208 if !session.version.is_empty() && session.version != env!("CARGO_PKG_VERSION") { 212 if !session.version.is_empty() && session.version != env!("CARGO_PKG_VERSION") {
209 eprintln!( 213 eprintln!(
210 "agent686: this session was written by {}; the prompt and tool schemas may \ 214 "agent686: this session was written by {}; the prompt and tool schemas may \
@@ -647,3 +651,42 @@ fn render_message(message: &Value, color: bool) -> String {
647 other => format!("[{other}]\n"), 651 other => format!("[{other}]\n"),
648 } 652 }
649} 653}
654
655/// On resume, show where the conversation left off: the last answer, or the last
656/// reasoning when the model never produced content. Only on a terminal, so piped
657/// runs stay clean.
658fn print_last_reply(id: &str) {
659 if !std::io::stdout().is_terminal() {
660 return;
661 }
662 let Some(reply) = session::last_reply(id) else {
663 return;
664 };
665 let text = if reply.content.trim().is_empty() {
666 reply.reasoning.trim()
667 } else {
668 reply.content.trim()
669 };
670 if text.is_empty() {
671 return;
672 }
673
674 let lines: Vec<&str> = text.lines().collect();
675 let limit = 20;
676 println!();
677 println!("{}", style("2", "── where you left off ──", true));
678 for line in lines.iter().take(limit) {
679 println!("{line}");
680 }
681 if lines.len() > limit {
682 println!(
683 "{}",
684 style(
685 "2",
686 &format!("… {} more line(s); `agent686 --show` for the transcript", lines.len() - limit),
687 true
688 )
689 );
690 }
691 println!();
692}
diff --git a/src/provider.rs b/src/provider.rs
index 1b9e220..0973e8c 100644
--- a/src/provider.rs
+++ b/src/provider.rs
@@ -358,7 +358,17 @@ pub fn chat_with(
358 } 358 }
359 } 359 }
360 360
361 outcome.tool_calls = calls.into_values().collect(); 361 let before = calls.len();
362 outcome.tool_calls = calls
363 .into_values()
364 // Some backends emit an empty placeholder alongside a real call; asking
365 // a human to approve a blank command is worse than dropping it.
366 .filter(|call| !(call.name.is_empty() && call.arguments.trim().is_empty()))
367 .collect();
368 let dropped_calls = before - outcome.tool_calls.len();
369 if dropped_calls > 0 {
370 eprintln!("agent686: ignored {dropped_calls} empty tool call(s)");
371 }
362 if outcome.usage.as_ref().is_some_and(|u| u.is_null()) { 372 if outcome.usage.as_ref().is_some_and(|u| u.is_null()) {
363 outcome.usage = None; 373 outcome.usage = None;
364 } 374 }
@@ -393,6 +403,9 @@ fn handle_event(
393 if data.is_empty() { 403 if data.is_empty() {
394 return false; 404 return false;
395 } 405 }
406 if std::env::var_os("AGENT686_DEBUG_STREAM").is_some() {
407 eprintln!("sse: {}", truncate(data, 400));
408 }
396 if data.trim() == "[DONE]" { 409 if data.trim() == "[DONE]" {
397 *completed = true; 410 *completed = true;
398 return true; 411 return true;
diff --git a/src/session.rs b/src/session.rs
index d017eda..8e0ef02 100644
--- a/src/session.rs
+++ b/src/session.rs
@@ -130,8 +130,8 @@ impl Session {
130 /// that was frozen when the session started. 130 /// that was frozen when the session started.
131 pub fn open(id: &str) -> Result<(Session, Value, Vec<Value>), String> { 131 pub fn open(id: &str) -> Result<(Session, Value, Vec<Value>), String> {
132 let path = sessions_dir().join(format!("{id}.jsonl")); 132 let path = sessions_dir().join(format!("{id}.jsonl"));
133 let file = File::open(&path).map_err(|e| format!("{}: {e}", path.display()))?; 133 let raw = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
134 let reader = BufReader::new(file.try_clone().map_err(|e| e.to_string())?); 134 let _ = File::open(&path);
135 135
136 let mut model = String::new(); 136 let mut model = String::new();
137 let mut system = Value::Null; 137 let mut system = Value::Null;
@@ -140,14 +140,15 @@ impl Session {
140 let mut version = String::new(); 140 let mut version = String::new();
141 let mut messages = Vec::new(); 141 let mut messages = Vec::new();
142 142
143 for line in reader.lines() { 143 for line in raw.split(|&byte| byte == b'\n') {
144 let line = line.map_err(|e| e.to_string())?; 144 if line.is_empty() {
145 if line.trim().is_empty() {
146 continue; 145 continue;
147 } 146 }
148 let value: Value = match serde_json::from_str(&line) { 147 // Lossy decoding: a torn write can split a multi-byte character, and
148 // one bad byte must not make the whole transcript unopenable.
149 let text = String::from_utf8_lossy(line);
150 let value: Value = match serde_json::from_str(&text) {
149 Ok(v) => v, 151 Ok(v) => v,
150 // A torn last line is expected after kill -9; ignore it.
151 Err(_) => continue, 152 Err(_) => continue,
152 }; 153 };
153 match value.get("t").and_then(|t| t.as_str()) { 154 match value.get("t").and_then(|t| t.as_str()) {
@@ -232,6 +233,57 @@ impl Session {
232 } 233 }
233} 234}
234 235
236pub struct LastReply {
237 pub content: String,
238 pub reasoning: String,
239}
240
241/// The last thing the agent said, for the resume banner. Prefers a real answer;
242/// falls back to reasoning when the last block had no content.
243pub fn last_reply(id: &str) -> Option<LastReply> {
244 let raw = std::fs::read(sessions_dir().join(format!("{id}.jsonl"))).ok()?;
245 let mut with_content: Option<LastReply> = None;
246 let mut with_reasoning: Option<LastReply> = None;
247
248 for line in raw.split(|&byte| byte == b'\n') {
249 if line.is_empty() {
250 continue;
251 }
252 let text = String::from_utf8_lossy(line);
253 let Ok(value) = serde_json::from_str::<Value>(&text) else {
254 continue;
255 };
256 if value.get("role").and_then(|role| role.as_str()) != Some("assistant") {
257 continue;
258 }
259 let content = value
260 .get("content")
261 .and_then(|c| c.as_str())
262 .unwrap_or("")
263 .to_string();
264 let reasoning = value
265 .get("_reasoning")
266 .and_then(|r| r.as_str())
267 .unwrap_or("")
268 .to_string();
269 let reply = LastReply {
270 content,
271 reasoning,
272 };
273 if !reply.content.trim().is_empty() {
274 with_content = Some(LastReply {
275 content: reply.content.clone(),
276 reasoning: reply.reasoning.clone(),
277 });
278 }
279 if !reply.reasoning.trim().is_empty() {
280 with_reasoning = Some(reply);
281 }
282 }
283
284 with_content.or(with_reasoning)
285}
286
235pub fn exists(id: &str) -> bool { 287pub fn exists(id: &str) -> bool {
236 sessions_dir().join(format!("{id}.jsonl")).is_file() 288 sessions_dir().join(format!("{id}.jsonl")).is_file()
237} 289}
diff --git a/src/tools/mod.rs b/src/tools/mod.rs
index a8851ab..060dd7b 100644
--- a/src/tools/mod.rs
+++ b/src/tools/mod.rs
@@ -24,6 +24,30 @@ pub fn approval(name: &str) -> Approval {
24 } 24 }
25} 25}
26 26
27/// Rejects a call that cannot possibly run, before a human is asked to approve
28/// it. An empty `cmd` used to mean an approval prompt for `run: `.
29pub fn validate(name: &str, args: &Value) -> Result<(), String> {
30 let text = |key: &str| args.get(key).and_then(|value| value.as_str()).unwrap_or("");
31 let required = |key: &str| {
32 if text(key).trim().is_empty() {
33 Err(format!("`{key}` is required and must not be empty"))
34 } else {
35 Ok(())
36 }
37 };
38
39 match name {
40 "bash" => required("cmd"),
41 "read" | "write" => required("path"),
42 "edit" => {
43 required("path")?;
44 required("old")
45 }
46 "grep" | "glob" => required("pattern"),
47 _ => Ok(()),
48 }
49}
50
27/// Tools that execute immediately. 51/// Tools that execute immediately.
28pub fn run(name: &str, args: &Value, cancel: &std::sync::atomic::AtomicBool) -> Result<String, String> { 52pub fn run(name: &str, args: &Value, cancel: &std::sync::atomic::AtomicBool) -> Result<String, String> {
29 match name { 53 match name {
diff --git a/tests/loop.rs b/tests/loop.rs
index b7e56f9..f90d19d 100644
--- a/tests/loop.rs
+++ b/tests/loop.rs
@@ -334,3 +334,56 @@ fn opening_a_session_with_unanswered_calls_repairs_it() {
334 }); 334 });
335 assert!(repaired, "missing result for call_2 should be synthesised"); 335 assert!(repaired, "missing result for call_2 should be synthesised");
336} 336}
337
338#[test]
339fn an_empty_bash_call_is_never_approved() {
340 let dir = temp_dir("empty-bash");
341 let empty_call = sse(&format!(
342 "data: {}\n\ndata: [DONE]\n\n",
343 json!({
344 "choices": [{
345 "delta": { "tool_calls": [{
346 "index": 0,
347 "id": "call_empty",
348 "function": { "name": "bash", "arguments": "{}" }
349 }]},
350 "finish_reason": "tool_calls"
351 }]
352 })
353 ));
354 let final_round = sse(
355 "data: {\"choices\":[{\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\n\
356 data: [DONE]\n\n",
357 );
358
359 let base = serve_sequence(vec![empty_call, final_round]);
360 std::env::set_var("AGENT686_DATA", dir.join("data"));
361
362 let system = agent::system_prompt();
363 let mut session = Session::create("test-model", &system).unwrap();
364 let cfg = Config {
365 base_url: base,
366 api_key: "test-key".into(),
367 model: "test-model".into(),
368 session: session.id.clone(),
369 yolo: false,
370 };
371 let mut history = agent::new_history(system);
372 // Not a terminal: if this reaches the approval path it is denied, which the
373 // assertion below would catch.
374 let mut approver = Approver::new(false);
375
376 agent::run_turn(
377 &cfg,
378 &mut session,
379 &mut history,
380 "run something",
381 &AtomicBool::new(false),
382 &mut approver,
383 )
384 .expect("the turn should survive a malformed call");
385
386 let result = history[3]["content"].as_str().unwrap();
387 assert!(result.contains("`cmd` is required"), "{result}");
388 assert!(!result.contains("denied"), "must not reach an approval prompt: {result}");
389}
diff --git a/tests/mock.rs b/tests/mock.rs
index 9b9a56d..7e076e3 100644
--- a/tests/mock.rs
+++ b/tests/mock.rs
@@ -442,3 +442,28 @@ fn a_final_frame_without_a_newline_is_not_lost() {
442 .expect("a trailing frame without a newline should still count"); 442 .expect("a trailing frame without a newline should still count");
443 assert_eq!(outcome.content, "last"); 443 assert_eq!(outcome.content, "last");
444} 444}
445
446#[test]
447fn an_empty_placeholder_tool_call_is_dropped() {
448 const SSE: &str = concat!(
449 "HTTP/1.1 200 OK\r\n",
450 "Content-Type: text/event-stream\r\n",
451 "Connection: close\r\n",
452 "\r\n",
453 "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"function\":{\"name\":\"read\",\"arguments\":\"{\\\"path\\\":\\\"a\\\"}\"}},{\"index\":1}]},\"finish_reason\":\"tool_calls\"}]}\n\n",
454 "data: [DONE]\n\n",
455 );
456 let (base, _rx) = serve_once(SSE);
457 let mut sink = Collector::default();
458 let outcome = provider::chat(
459 &config(base),
460 &[json!({ "role": "user", "content": "hi" })],
461 &[],
462 &AtomicBool::new(false),
463 &mut sink,
464 )
465 .expect("chat should succeed");
466
467 assert_eq!(outcome.tool_calls.len(), 1, "{:?}", outcome.tool_calls);
468 assert_eq!(outcome.tool_calls[0].name, "read");
469}
diff --git a/tests/sessions.rs b/tests/sessions.rs
index 1d40f64..df2f3b2 100644
--- a/tests/sessions.rs
+++ b/tests/sessions.rs
@@ -110,3 +110,62 @@ fn listing_reports_the_model_in_use_after_a_switch() {
110 assert_eq!(listed.len(), 1); 110 assert_eq!(listed.len(), 1);
111 assert_eq!(listed[0].model, "model-b"); 111 assert_eq!(listed[0].model, "model-b");
112} 112}
113
114#[test]
115fn a_torn_utf8_line_does_not_brick_a_session() {
116 let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
117 let dir = temp_dir("torn");
118 std::env::set_var("AGENT686_DATA", &dir);
119 let sessions = dir.join("sessions");
120 fs::create_dir_all(&sessions).unwrap();
121
122 let mut raw = Vec::new();
123 raw.extend_from_slice(
124 br#"{"t":"header","session":"torn","model":"m","cwd":"/tmp","system":{"role":"system","content":"s"}}
125"#,
126 );
127 raw.extend_from_slice(br#"{"t":"msg","role":"user","content":"hello"}
128"#);
129 // A killed write that split a multi-byte character.
130 raw.extend_from_slice(b"{\"t\":\"msg\",\"role\":\"user\",\"content\":\"caf\xc3\"}\n");
131 fs::write(sessions.join("torn.jsonl"), raw).unwrap();
132
133 let (_session, _system, messages) = Session::open("torn").expect("torn line must not fail");
134 // Lossy decoding keeps the message (with a replacement character) rather
135 // than dropping a valid JSON line; what matters is that open succeeds.
136 assert_eq!(messages.len(), 2);
137 assert_eq!(messages[0]["content"], "hello");
138 assert!(messages[1]["content"].as_str().unwrap().starts_with("caf"));
139}
140
141#[test]
142fn last_reply_prefers_content_and_falls_back_to_reasoning() {
143 let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
144 let dir = temp_dir("last-reply");
145 std::env::set_var("AGENT686_DATA", &dir);
146
147 let system = json!({ "role": "system", "content": "x" });
148 let mut session = Session::create_as("reply".into(), "m", &system).unwrap();
149 session
150 .append(
151 &json!({ "role": "assistant", "content": "the answer" }),
152 Some("the thinking"),
153 )
154 .unwrap();
155 session
156 .append(&json!({ "role": "assistant", "content": null }), Some("only thinking"))
157 .unwrap();
158
159 let reply = session::last_reply("reply").expect("there is a reply");
160 assert_eq!(reply.content, "the answer", "prefers a real block");
161 assert_eq!(reply.reasoning, "the thinking", "and its own reasoning");
162
163 // With no content anywhere, reasoning is the fallback.
164 let mut session = Session::create_as("reasoning-only".into(), "m", &system).unwrap();
165 session
166 .append(&json!({ "role": "assistant", "content": null }), Some("thoughts"))
167 .unwrap();
168 let reply = session::last_reply("reasoning-only").unwrap();
169 assert!(reply.content.is_empty());
170 assert_eq!(reply.reasoning, "thoughts");
171}
diff --git a/tests/tools.rs b/tests/tools.rs
index 77c1698..a400df0 100644
--- a/tests/tools.rs
+++ b/tests/tools.rs
@@ -419,3 +419,18 @@ fn glob_follows_file_symlinks_but_not_directories() {
419 assert!(text.contains("link.rs"), "{text}"); 419 assert!(text.contains("link.rs"), "{text}");
420 assert!(text.contains("inner.rs"), "{text}"); 420 assert!(text.contains("inner.rs"), "{text}");
421} 421}
422
423#[test]
424fn validate_rejects_calls_that_cannot_run() {
425 use agent686::tools::validate;
426
427 assert!(validate("bash", &json!({ "cmd": "" })).is_err());
428 assert!(validate("bash", &json!({})).is_err());
429 assert!(validate("bash", &json!({ "cmd": "ls" })).is_ok());
430
431 assert!(validate("read", &json!({ "path": " " })).is_err());
432 assert!(validate("edit", &json!({ "path": "a", "old": "" })).is_err());
433 assert!(validate("grep", &json!({ "pattern": "" })).is_err());
434 // Empty content is how you create an empty file.
435 assert!(validate("write", &json!({ "path": "a", "content": "" })).is_ok());
436}