summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorsalmonik <salmonik@tuta.io>2026-11-15 18:00:12 +0100
committersalmonik <salmonik@tuta.io>2026-11-15 18:00:12 +0100
commit8ae5bd48cf233315b5f36a7a6b39002a5e77f74b (patch)
tree71c9b71f90f3cc64544dd506041468ee9bcbcda1 /src
parent0.6.2: resizing no longer duplicates the prompt (diff)
downloadagent686-8ae5bd48cf233315b5f36a7a6b39002a5e77f74b.tar.gz
agent686-8ae5bd48cf233315b5f36a7a6b39002a5e77f74b.zip
0.7.0: resume shows where you left off; no approval for unparsable calls
- --continue prints the last answer, or the last reasoning block if there was none - tool arguments are validated before prompting, so an empty bash call becomes an error for the model instead of a blank approval - empty placeholder tool calls are dropped and reported - sessions tolerate invalid UTF-8 lines from a torn write - AGENT686_DEBUG_STREAM=1 dumps SSE frames
Diffstat (limited to 'src')
-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
5 files changed, 152 insertions, 9 deletions
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 {