summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorsalmonik <salmon@2137697.xyz>2026-11-23 20:36:22 +0100
committersalmonik <salmon@2137697.xyz>2026-11-23 20:36:22 +0100
commite803aa488c3a95193d3e3ae358b640c299f8f121 (patch)
tree0af80401445159ca40a8ab3d7bbf39094ab5db77 /src
parent0.12.1: accept `command` as an alias for `cmd` in bash (diff)
downloadagent686-e803aa488c3a95193d3e3ae358b640c299f8f121.tar.gz
agent686-e803aa488c3a95193d3e3ae358b640c299f8f121.zip
License
Diffstat (limited to 'src')
-rw-r--r--src/agent.rs46
-rw-r--r--src/config.rs7
-rw-r--r--src/doctor.rs28
-rw-r--r--src/git.rs7
-rw-r--r--src/lib.rs7
-rw-r--r--src/line.rs21
-rw-r--r--src/main.rs7
-rw-r--r--src/provider.rs61
-rw-r--r--src/session.rs15
-rw-r--r--src/signal.rs7
-rw-r--r--src/tools/fs.rs38
-rw-r--r--src/tools/mod.rs7
-rw-r--r--src/tools/shell.rs23
-rw-r--r--src/ui.rs7
14 files changed, 213 insertions, 68 deletions
diff --git a/src/agent.rs b/src/agent.rs
index f575908..b30c876 100644
--- a/src/agent.rs
+++ b/src/agent.rs
@@ -1,3 +1,10 @@
1/*
2 * This file is part of agent686
3 * Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 * https://git.2137697.xyz/agent686
6 */
7
1use std::path::PathBuf; 8use std::path::PathBuf;
2use std::process::Command; 9use std::process::Command;
3use std::sync::atomic::AtomicBool; 10use std::sync::atomic::AtomicBool;
@@ -201,27 +208,23 @@ pub fn run_turn(
201 208
202 steps += 1; 209 steps += 1;
203 let mut renderer = Renderer::new(); 210 let mut renderer = Renderer::new();
204 let mut outcome = match provider::chat_with( 211 let mut outcome =
205 &client, 212 match provider::chat_with(&client, cfg, history, &schemas, cancel, &mut renderer) {
206 cfg, 213 Ok(outcome) => outcome,
207 history, 214 Err(Error::Aborted) => {
208 &schemas, 215 aborted = true;
209 cancel, 216 break;
210 &mut renderer, 217 }
211 ) { 218 Err(error) => return Err(error),
212 Ok(outcome) => outcome, 219 };
213 Err(Error::Aborted) => {
214 aborted = true;
215 break;
216 }
217 Err(error) => return Err(error),
218 };
219 220
220 // A call with no name cannot be replayed to the provider at all, so it 221 // A call with no name cannot be replayed to the provider at all, so it
221 // is dropped. A *named* call with no arguments is kept: the model is told 222 // is dropped. A *named* call with no arguments is kept: the model is told
222 // what arrived and can retry, which is better than silence. 223 // what arrived and can retry, which is better than silence.
223 let before = outcome.tool_calls.len(); 224 let before = outcome.tool_calls.len();
224 outcome.tool_calls.retain(|call| !call.name.trim().is_empty()); 225 outcome
226 .tool_calls
227 .retain(|call| !call.name.trim().is_empty());
225 if outcome.tool_calls.len() < before { 228 if outcome.tool_calls.len() < before {
226 eprintln!( 229 eprintln!(
227 "agent686: ignored {} tool call(s) with no name", 230 "agent686: ignored {} tool call(s) with no name",
@@ -240,7 +243,12 @@ pub fn run_turn(
240 truncated = Some("the model hit its output limit; the answer is cut off".into()); 243 truncated = Some("the model hit its output limit; the answer is cut off".into());
241 } 244 }
242 let assistant = assistant_message(&outcome); 245 let assistant = assistant_message(&outcome);
243 push(session, history, assistant, Some(outcome.reasoning.as_str())); 246 push(
247 session,
248 history,
249 assistant,
250 Some(outcome.reasoning.as_str()),
251 );
244 252
245 if outcome.tool_calls.is_empty() { 253 if outcome.tool_calls.is_empty() {
246 last = Some(outcome); 254 last = Some(outcome);
@@ -389,8 +397,8 @@ fn execute(
389 args 397 args
390 }; 398 };
391 // The bash approval prompt prints the command; do not print it here too. 399 // The bash approval prompt prints the command; do not print it here too.
392 let repeat_detail = !(tools::approval(&call.name) == Approval::EveryCall 400 let repeat_detail =
393 && approver.will_prompt_bash()); 401 !(tools::approval(&call.name) == Approval::EveryCall && approver.will_prompt_bash());
394 ui::tool_line(label, &call.name, &args, repeat_detail); 402 ui::tool_line(label, &call.name, &args, repeat_detail);
395 if let Err(error) = tools::validate(&call.name, &args) { 403 if let Err(error) = tools::validate(&call.name, &args) {
396 return ToolOutcome::Failed(format!("{error}; the call was not run")); 404 return ToolOutcome::Failed(format!("{error}; the call was not run"));
diff --git a/src/config.rs b/src/config.rs
index a314f38..0c95485 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -1,3 +1,10 @@
1/*
2 * This file is part of agent686
3 * Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 * https://git.2137697.xyz/agent686
6 */
7
1use std::path::PathBuf; 8use std::path::PathBuf;
2 9
3use serde::Deserialize; 10use serde::Deserialize;
diff --git a/src/doctor.rs b/src/doctor.rs
index 8baf1f7..e7b949e 100644
--- a/src/doctor.rs
+++ b/src/doctor.rs
@@ -1,3 +1,10 @@
1/*
2 * This file is part of agent686
3 * Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 * https://git.2137697.xyz/agent686
6 */
7
1use std::path::Path; 8use std::path::Path;
2 9
3use serde_json::json; 10use serde_json::json;
@@ -32,7 +39,8 @@ pub fn run(cfg: &Config, json: bool) -> i32 {
32 } 39 }
33 record("key", true, detail); 40 record("key", true, detail);
34 } 41 }
35 KeySource::Missing => record("key", 42 KeySource::Missing => record(
43 "key",
36 false, 44 false,
37 "missing — set OPENCODE_API_KEY or write ~/.config/agent686/key".into(), 45 "missing — set OPENCODE_API_KEY or write ~/.config/agent686/key".into(),
38 ), 46 ),
@@ -55,11 +63,7 @@ pub fn run(cfg: &Config, json: bool) -> i32 {
55 true, 63 true,
56 format!("{} ({} entries)", history.display(), text.lines().count()), 64 format!("{} ({} entries)", history.display(), text.lines().count()),
57 ), 65 ),
58 Err(_) => record( 66 Err(_) => record("history", true, format!("{} (new)", history.display())),
59 "history",
60 true,
61 format!("{} (new)", history.display()),
62 ),
63 } 67 }
64 68
65 record("provider", true, cfg.base_url.clone()); 69 record("provider", true, cfg.base_url.clone());
@@ -70,7 +74,11 @@ pub fn run(cfg: &Config, json: bool) -> i32 {
70 } else { 74 } else {
71 match provider::models(cfg) { 75 match provider::models(cfg) {
72 Ok(models) => { 76 Ok(models) => {
73 record("auth", true, format!("ok — {} models visible", models.len())); 77 record(
78 "auth",
79 true,
80 format!("ok — {} models visible", models.len()),
81 );
74 if models.iter().any(|id| id == &cfg.model) { 82 if models.iter().any(|id| id == &cfg.model) {
75 record("model known", true, "yes".into()); 83 record("model known", true, "yes".into());
76 } else { 84 } else {
@@ -107,7 +115,11 @@ pub fn run(cfg: &Config, json: bool) -> i32 {
107 ); 115 );
108 println!(); 116 println!();
109 for (label, ok, detail) in &checks { 117 for (label, ok, detail) in &checks {
110 println!("{:<13} {:<4} {detail}", label, if *ok { "ok" } else { "FAIL" }); 118 println!(
119 "{:<13} {:<4} {detail}",
120 label,
121 if *ok { "ok" } else { "FAIL" }
122 );
111 } 123 }
112 println!(); 124 println!();
113 if failed { 125 if failed {
diff --git a/src/git.rs b/src/git.rs
index 78348af..a36ce50 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -1,3 +1,10 @@
1/*
2 * This file is part of agent686
3 * Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 * https://git.2137697.xyz/agent686
6 */
7
1//! Git helpers for the checkpoint/undo feature. In a separate module so they 8//! Git helpers for the checkpoint/undo feature. In a separate module so they
2//! are unit-testable without driving the whole CLI. 9//! are unit-testable without driving the whole CLI.
3 10
diff --git a/src/lib.rs b/src/lib.rs
index b1e0592..a3f3b52 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,3 +1,10 @@
1/*
2 * This file is part of agent686
3 * Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 * https://git.2137697.xyz/agent686
6 */
7
1pub mod agent; 8pub mod agent;
2pub mod config; 9pub mod config;
3pub mod doctor; 10pub mod doctor;
diff --git a/src/line.rs b/src/line.rs
index 9877c48..e178f5b 100644
--- a/src/line.rs
+++ b/src/line.rs
@@ -1,3 +1,10 @@
1/*
2 * This file is part of agent686
3 * Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 * https://git.2137697.xyz/agent686
6 */
7
1use std::io::{self, IsTerminal, Write}; 8use std::io::{self, IsTerminal, Write};
2use std::os::unix::fs::PermissionsExt; 9use std::os::unix::fs::PermissionsExt;
3use std::path::PathBuf; 10use std::path::PathBuf;
@@ -5,8 +12,8 @@ use std::path::PathBuf;
5use crossterm::cursor::{MoveToColumn, MoveUp}; 12use crossterm::cursor::{MoveToColumn, MoveUp};
6use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; 13use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
7use crossterm::event::{DisableBracketedPaste, EnableBracketedPaste}; 14use crossterm::event::{DisableBracketedPaste, EnableBracketedPaste};
8use crossterm::terminal::{self, Clear, ClearType};
9use crossterm::execute; 15use crossterm::execute;
16use crossterm::terminal::{self, Clear, ClearType};
10 17
11const HISTORY_LIMIT: usize = 200; 18const HISTORY_LIMIT: usize = 200;
12 19
@@ -311,12 +318,7 @@ struct DrawState {
311 cursor_row: usize, 318 cursor_row: usize,
312} 319}
313 320
314fn draw( 321fn draw(prompt: &str, buffer: &[char], cursor: usize, state: &mut DrawState) -> io::Result<()> {
315 prompt: &str,
316 buffer: &[char],
317 cursor: usize,
318 state: &mut DrawState,
319) -> io::Result<()> {
320 let mut out = io::stdout(); 322 let mut out = io::stdout();
321 draw_to(&mut out, prompt, buffer, cursor, state)?; 323 draw_to(&mut out, prompt, buffer, cursor, state)?;
322 out.flush() 324 out.flush()
@@ -396,7 +398,10 @@ fn load_history() -> Vec<String> {
396 lines.drain(..lines.len() - HISTORY_LIMIT); 398 lines.drain(..lines.len() - HISTORY_LIMIT);
397 // Keep the file from growing without bound, not just the in-memory list. 399 // Keep the file from growing without bound, not just the in-memory list.
398 if lines.len() * 2 < text.lines().count() { 400 if lines.len() * 2 < text.lines().count() {
399 let body: Vec<String> = lines.iter().map(|line| line.replace('\n', "\u{0}")).collect(); 401 let body: Vec<String> = lines
402 .iter()
403 .map(|line| line.replace('\n', "\u{0}"))
404 .collect();
400 let _ = std::fs::write(&path, format!("{}\n", body.join("\n"))); 405 let _ = std::fs::write(&path, format!("{}\n", body.join("\n")));
401 } 406 }
402 } 407 }
diff --git a/src/main.rs b/src/main.rs
index a591c07..ba296d9 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,3 +1,10 @@
1/*
2 * This file is part of agent686
3 * Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 * https://git.2137697.xyz/agent686
6 */
7
1use std::io::{BufRead, IsTerminal, Write}; 8use std::io::{BufRead, IsTerminal, Write};
2use std::path::Path; 9use std::path::Path;
3use serde_json::json; 10use serde_json::json;
diff --git a/src/provider.rs b/src/provider.rs
index b5dca62..2f8bcfc 100644
--- a/src/provider.rs
+++ b/src/provider.rs
@@ -1,3 +1,10 @@
1/*
2 * This file is part of agent686
3 * Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 * https://git.2137697.xyz/agent686
6 */
7
1use std::io::Read; 8use std::io::Read;
2use std::sync::atomic::{AtomicBool, Ordering}; 9use std::sync::atomic::{AtomicBool, Ordering};
3use std::time::{Duration, Instant}; 10use std::time::{Duration, Instant};
@@ -183,9 +190,7 @@ fn explain(status: u16, message: &str) -> String {
183 ); 190 );
184 } 191 }
185 if status == 401 || status == 403 { 192 if status == 401 || status == 403 {
186 return format!( 193 return format!("{message}\n\ncheck the key: OPENCODE_API_KEY or ~/.config/agent686/key");
187 "{message}\n\ncheck the key: OPENCODE_API_KEY or ~/.config/agent686/key"
188 );
189 } 194 }
190 if status == 429 { 195 if status == 429 {
191 return format!( 196 return format!(
@@ -261,7 +266,10 @@ pub fn chat_with(
261 .header("Content-Type", "application/json") 266 .header("Content-Type", "application/json")
262 .header("Accept", "text/event-stream") 267 .header("Accept", "text/event-stream")
263 .header("Authorization", format!("Bearer {}", cfg.api_key)) 268 .header("Authorization", format!("Bearer {}", cfg.api_key))
264 .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))); 269 .header(
270 "User-Agent",
271 concat!("agent686/", env!("CARGO_PKG_VERSION")),
272 );
265 // OpenCode requires a stable per-conversation id for routing and 273 // OpenCode requires a stable per-conversation id for routing and
266 // prompt caching; a plain OpenAI-compatible endpoint must not get it. 274 // prompt caching; a plain OpenAI-compatible endpoint must not get it.
267 if cfg.provider.needs_session_header() { 275 if cfg.provider.needs_session_header() {
@@ -347,7 +355,14 @@ pub fn chat_with(
347 Err(e) => return Err(Error::Transport(e.to_string())), 355 Err(e) => return Err(Error::Transport(e.to_string())),
348 }; 356 };
349 for data in decoder.feed(&buf[..n]) { 357 for data in decoder.feed(&buf[..n]) {
350 if handle_event(&data, &mut outcome, &mut calls, &mut completed, &mut dropped, sink) { 358 if handle_event(
359 &data,
360 &mut outcome,
361 &mut calls,
362 &mut completed,
363 &mut dropped,
364 sink,
365 ) {
351 done = true; 366 done = true;
352 break; 367 break;
353 } 368 }
@@ -360,7 +375,14 @@ pub fn chat_with(
360 // A final `data:` frame with no trailing newline is legitimate. 375 // A final `data:` frame with no trailing newline is legitimate.
361 if !done { 376 if !done {
362 for data in decoder.finish() { 377 for data in decoder.finish() {
363 if handle_event(&data, &mut outcome, &mut calls, &mut completed, &mut dropped, sink) { 378 if handle_event(
379 &data,
380 &mut outcome,
381 &mut calls,
382 &mut completed,
383 &mut dropped,
384 sink,
385 ) {
364 break; 386 break;
365 } 387 }
366 } 388 }
@@ -389,7 +411,8 @@ pub fn chat_with(
389 // be recorded as a complete answer. Lenient mode tolerates local servers 411 // be recorded as a complete answer. Lenient mode tolerates local servers
390 // that finish with text but no [DONE]/finish_reason. 412 // that finish with text but no [DONE]/finish_reason.
391 if !completed { 413 if !completed {
392 let lenient_ok = cfg.lenient && outcome.tool_calls.is_empty() && !outcome.content.is_empty(); 414 let lenient_ok =
415 cfg.lenient && outcome.tool_calls.is_empty() && !outcome.content.is_empty();
393 if !lenient_ok { 416 if !lenient_ok {
394 return Err(Error::Transport(format!( 417 return Err(Error::Transport(format!(
395 "stream ended before completion ({} bytes of text, {} tool call(s)); \ 418 "stream ended before completion ({} bytes of text, {} tool call(s)); \
@@ -424,7 +447,11 @@ fn handle_event(
424 } 447 }
425 match serde_json::from_str::<Chunk>(data) { 448 match serde_json::from_str::<Chunk>(data) {
426 Ok(chunk) => { 449 Ok(chunk) => {
427 if chunk.choices.iter().any(|choice| choice.finish_reason.is_some()) { 450 if chunk
451 .choices
452 .iter()
453 .any(|choice| choice.finish_reason.is_some())
454 {
428 *completed = true; 455 *completed = true;
429 } 456 }
430 apply_chunk(&chunk, outcome, calls, sink); 457 apply_chunk(&chunk, outcome, calls, sink);
@@ -575,11 +602,16 @@ pub fn summarize(cfg: &Config, messages: &[Value]) -> Result<String, Error> {
575 .post(&cfg.endpoint()) 602 .post(&cfg.endpoint())
576 .header("Content-Type", "application/json") 603 .header("Content-Type", "application/json")
577 .header("Authorization", format!("Bearer {}", cfg.api_key)) 604 .header("Authorization", format!("Bearer {}", cfg.api_key))
578 .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))); 605 .header(
606 "User-Agent",
607 concat!("agent686/", env!("CARGO_PKG_VERSION")),
608 );
579 if cfg.provider.needs_session_header() { 609 if cfg.provider.needs_session_header() {
580 request = request.header("x-opencode-session", &cfg.session); 610 request = request.header("x-opencode-session", &cfg.session);
581 } 611 }
582 let mut response = request.send(bytes).map_err(|e| Error::Transport(e.to_string()))?; 612 let mut response = request
613 .send(bytes)
614 .map_err(|e| Error::Transport(e.to_string()))?;
583 615
584 let status = response.status().as_u16(); 616 let status = response.status().as_u16();
585 let text = response 617 let text = response
@@ -610,11 +642,16 @@ pub fn models(cfg: &Config) -> Result<Vec<String>, Error> {
610 let mut request = agent 642 let mut request = agent
611 .get(&url) 643 .get(&url)
612 .header("Authorization", format!("Bearer {}", cfg.api_key)) 644 .header("Authorization", format!("Bearer {}", cfg.api_key))
613 .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))); 645 .header(
646 "User-Agent",
647 concat!("agent686/", env!("CARGO_PKG_VERSION")),
648 );
614 if cfg.provider.needs_session_header() { 649 if cfg.provider.needs_session_header() {
615 request = request.header("x-opencode-session", &cfg.session); 650 request = request.header("x-opencode-session", &cfg.session);
616 } 651 }
617 let mut response = request.call().map_err(|e| Error::Transport(e.to_string()))?; 652 let mut response = request
653 .call()
654 .map_err(|e| Error::Transport(e.to_string()))?;
618 655
619 let status = response.status().as_u16(); 656 let status = response.status().as_u16();
620 let body = response 657 let body = response
diff --git a/src/session.rs b/src/session.rs
index 8fc6d29..a75b4c3 100644
--- a/src/session.rs
+++ b/src/session.rs
@@ -1,3 +1,10 @@
1/*
2 * This file is part of agent686
3 * Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 * https://git.2137697.xyz/agent686
6 */
7
1use std::fs::{File, OpenOptions}; 8use std::fs::{File, OpenOptions};
2use std::hash::{Hash, Hasher}; 9use std::hash::{Hash, Hasher};
3use std::io::{BufRead, BufReader, Read, Write}; 10use std::io::{BufRead, BufReader, Read, Write};
@@ -54,9 +61,7 @@ fn restrict(path: &Path, mode: u32) {
54fn lock_exclusive(file: &File, id: &str) -> Result<(), String> { 61fn lock_exclusive(file: &File, id: &str) -> Result<(), String> {
55 let locked = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }; 62 let locked = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
56 if locked != 0 { 63 if locked != 0 {
57 return Err(format!( 64 return Err(format!("session {id} is already open in another process"));
58 "session {id} is already open in another process"
59 ));
60 } 65 }
61 Ok(()) 66 Ok(())
62} 67}
@@ -258,7 +263,9 @@ impl Session {
258 pub fn rewrite(&mut self, system: &Value, messages: &[Value]) -> Result<(), String> { 263 pub fn rewrite(&mut self, system: &Value, messages: &[Value]) -> Result<(), String> {
259 use std::io::{Seek, SeekFrom, Write}; 264 use std::io::{Seek, SeekFrom, Write};
260 self.file.set_len(0).map_err(|e| e.to_string())?; 265 self.file.set_len(0).map_err(|e| e.to_string())?;
261 self.file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?; 266 self.file
267 .seek(SeekFrom::Start(0))
268 .map_err(|e| e.to_string())?;
262 let header = json!({ 269 let header = json!({
263 "t": "header", 270 "t": "header",
264 "session": self.id, 271 "session": self.id,
diff --git a/src/signal.rs b/src/signal.rs
index c11f078..80d571b 100644
--- a/src/signal.rs
+++ b/src/signal.rs
@@ -1,3 +1,10 @@
1/*
2 * This file is part of agent686
3 * Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 * https://git.2137697.xyz/agent686
6 */
7
1use std::sync::atomic::{AtomicBool, Ordering}; 8use std::sync::atomic::{AtomicBool, Ordering};
2 9
3/// Set by the first Ctrl-C. Cleared between turns. 10/// Set by the first Ctrl-C. Cleared between turns.
diff --git a/src/tools/fs.rs b/src/tools/fs.rs
index ac0a475..0075590 100644
--- a/src/tools/fs.rs
+++ b/src/tools/fs.rs
@@ -1,3 +1,10 @@
1/*
2 * This file is part of agent686
3 * Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 * https://git.2137697.xyz/agent686
6 */
7
1use std::fs; 8use std::fs;
2use std::io::{BufRead, BufReader}; 9use std::io::{BufRead, BufReader};
3use std::path::{Path, PathBuf}; 10use std::path::{Path, PathBuf};
@@ -30,8 +37,15 @@ const SKIP_DIRS: &[&str] = &[
30/// human agrees. The file is re-read at apply time, so an edit made while the 37/// human agrees. The file is re-read at apply time, so an edit made while the
31/// approval prompt was open is not silently discarded. 38/// approval prompt was open is not silently discarded.
32pub enum Change { 39pub enum Change {
33 Write { path: String, content: String }, 40 Write {
34 Edit { path: String, old: String, new: String }, 41 path: String,
42 content: String,
43 },
44 Edit {
45 path: String,
46 old: String,
47 new: String,
48 },
35} 49}
36 50
37impl Change { 51impl Change {
@@ -157,9 +171,11 @@ fn locate(text: &str, old: &str) -> Result<Span, String> {
157 } 171 }
158 } 172 }
159 173
160 Err("text to replace was not found. Read the file and copy the exact text, \ 174 Err(
175 "text to replace was not found. Read the file and copy the exact text, \
161 including indentation." 176 including indentation."
162 .to_string()) 177 .to_string(),
178 )
163} 179}
164 180
165/// Byte offset in the original text for an offset in the CRLF-normalised text. 181/// Byte offset in the original text for an offset in the CRLF-normalised text.
@@ -262,7 +278,11 @@ pub fn plan_edit(args: &Value) -> Result<Change, String> {
262 278
263pub fn read(args: &Value) -> Result<String, String> { 279pub fn read(args: &Value) -> Result<String, String> {
264 let path = req(args, "path")?; 280 let path = req(args, "path")?;
265 let offset = args.get("offset").and_then(|v| v.as_u64()).unwrap_or(1).max(1); 281 let offset = args
282 .get("offset")
283 .and_then(|v| v.as_u64())
284 .unwrap_or(1)
285 .max(1);
266 let offset = usize::try_from(offset) 286 let offset = usize::try_from(offset)
267 .map_err(|_| format!("offset {offset} is too large for this build"))?; 287 .map_err(|_| format!("offset {offset} is too large for this build"))?;
268 let limit = args 288 let limit = args
@@ -622,7 +642,8 @@ fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
622 walk(&path, out); 642 walk(&path, out);
623 } else if file_type.is_file() { 643 } else if file_type.is_file() {
624 out.push(path); 644 out.push(path);
625 } else if file_type.is_symlink() && fs::metadata(&path).map(|m| m.is_file()).unwrap_or(false) 645 } else if file_type.is_symlink()
646 && fs::metadata(&path).map(|m| m.is_file()).unwrap_or(false)
626 { 647 {
627 // Follow file symlinks; symlinked directories are skipped so a loop 648 // Follow file symlinks; symlinked directories are skipped so a loop
628 // cannot walk forever. 649 // cannot walk forever.
@@ -679,7 +700,10 @@ fn new_file_preview(path: &str, content: &str) -> String {
679 out.push_str(&format!("+ {}\n", clip(line, 200))); 700 out.push_str(&format!("+ {}\n", clip(line, 200)));
680 } 701 }
681 if lines.len() > PREVIEW_BUDGET { 702 if lines.len() > PREVIEW_BUDGET {
682 out.push_str(&format!("… {} more line(s)\n", lines.len() - PREVIEW_BUDGET)); 703 out.push_str(&format!(
704 "… {} more line(s)\n",
705 lines.len() - PREVIEW_BUDGET
706 ));
683 } 707 }
684 out 708 out
685} 709}
diff --git a/src/tools/mod.rs b/src/tools/mod.rs
index 5d6189f..43176c3 100644
--- a/src/tools/mod.rs
+++ b/src/tools/mod.rs
@@ -1,3 +1,10 @@
1/*
2 * This file is part of agent686
3 * Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 * https://git.2137697.xyz/agent686
6 */
7
1pub mod fs; 8pub mod fs;
2pub mod shell; 9pub mod shell;
3 10
diff --git a/src/tools/shell.rs b/src/tools/shell.rs
index c64bab3..7f909bc 100644
--- a/src/tools/shell.rs
+++ b/src/tools/shell.rs
@@ -1,3 +1,10 @@
1/*
2 * This file is part of agent686
3 * Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 * https://git.2137697.xyz/agent686
6 */
7
1use std::fs::File; 8use std::fs::File;
2use std::io::{Read, Seek, SeekFrom}; 9use std::io::{Read, Seek, SeekFrom};
3use std::os::unix::process::{CommandExt, ExitStatusExt}; 10use std::os::unix::process::{CommandExt, ExitStatusExt};
@@ -32,11 +39,7 @@ impl Drop for TempGuard {
32 } 39 }
33} 40}
34 41
35pub fn bash( 42pub fn bash(args: &Value, timeout: Duration, cancel: &AtomicBool) -> Result<String, String> {
36 args: &Value,
37 timeout: Duration,
38 cancel: &AtomicBool,
39) -> Result<String, String> {
40 let cmd = match args 43 let cmd = match args
41 .get("cmd") 44 .get("cmd")
42 .or_else(|| args.get("command")) 45 .or_else(|| args.get("command"))
@@ -146,14 +149,14 @@ pub fn bash(
146 } else if aborted { 149 } else if aborted {
147 "[aborted by the user]".to_string() 150 "[aborted by the user]".to_string()
148 } else if timed_out { 151 } else if timed_out {
149 format!("[timed out after {:.1}s; process killed]", timeout.as_secs_f64()) 152 format!(
153 "[timed out after {:.1}s; process killed]",
154 timeout.as_secs_f64()
155 )
150 } else { 156 } else {
151 match status.code() { 157 match status.code() {
152 Some(code) => format!("[exit {code}]"), 158 Some(code) => format!("[exit {code}]"),
153 None => format!( 159 None => format!("[killed by signal {}]", status.signal().unwrap_or_default()),
154 "[killed by signal {}]",
155 status.signal().unwrap_or_default()
156 ),
157 } 160 }
158 }; 161 };
159 162
diff --git a/src/ui.rs b/src/ui.rs
index e778eee..9931a7d 100644
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -1,3 +1,10 @@
1/*
2 * This file is part of agent686
3 * Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
4 * SPDX-License-Identifier: GPL-3.0-or-later
5 * https://git.2137697.xyz/agent686
6 */
7
1use std::io::{IsTerminal, Write}; 8use std::io::{IsTerminal, Write};
2use std::sync::OnceLock; 9use std::sync::OnceLock;
3use std::time::Duration; 10use std::time::Duration;