From e803aa488c3a95193d3e3ae358b640c299f8f121 Mon Sep 17 00:00:00 2001 From: salmonik Date: Mon, 23 Nov 2026 20:36:22 +0100 Subject: License --- src/agent.rs | 46 +++++++++++++++++++++++----------------- src/config.rs | 7 +++++++ src/doctor.rs | 28 ++++++++++++++++++------- src/git.rs | 7 +++++++ src/lib.rs | 7 +++++++ src/line.rs | 21 ++++++++++++------- src/main.rs | 7 +++++++ src/provider.rs | 61 +++++++++++++++++++++++++++++++++++++++++++----------- src/session.rs | 15 ++++++++++---- src/signal.rs | 7 +++++++ src/tools/fs.rs | 38 +++++++++++++++++++++++++++------- src/tools/mod.rs | 7 +++++++ src/tools/shell.rs | 23 +++++++++++--------- src/ui.rs | 7 +++++++ 14 files changed, 213 insertions(+), 68 deletions(-) (limited to 'src') 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 @@ +/* + * This file is part of agent686 + * Copyright (C) 2026 Salmonik + * SPDX-License-Identifier: GPL-3.0-or-later + * https://git.2137697.xyz/agent686 + */ + use std::path::PathBuf; use std::process::Command; use std::sync::atomic::AtomicBool; @@ -201,27 +208,23 @@ pub fn run_turn( steps += 1; let mut renderer = Renderer::new(); - let mut outcome = match provider::chat_with( - &client, - cfg, - history, - &schemas, - cancel, - &mut renderer, - ) { - Ok(outcome) => outcome, - Err(Error::Aborted) => { - aborted = true; - break; - } - Err(error) => return Err(error), - }; + let mut outcome = + match provider::chat_with(&client, cfg, history, &schemas, cancel, &mut renderer) { + Ok(outcome) => outcome, + Err(Error::Aborted) => { + aborted = true; + break; + } + Err(error) => return Err(error), + }; // A call with no name cannot be replayed to the provider at all, so it // is dropped. A *named* call with no arguments is kept: the model is told // what arrived and can retry, which is better than silence. let before = outcome.tool_calls.len(); - outcome.tool_calls.retain(|call| !call.name.trim().is_empty()); + outcome + .tool_calls + .retain(|call| !call.name.trim().is_empty()); if outcome.tool_calls.len() < before { eprintln!( "agent686: ignored {} tool call(s) with no name", @@ -240,7 +243,12 @@ pub fn run_turn( truncated = Some("the model hit its output limit; the answer is cut off".into()); } let assistant = assistant_message(&outcome); - push(session, history, assistant, Some(outcome.reasoning.as_str())); + push( + session, + history, + assistant, + Some(outcome.reasoning.as_str()), + ); if outcome.tool_calls.is_empty() { last = Some(outcome); @@ -389,8 +397,8 @@ fn execute( args }; // The bash approval prompt prints the command; do not print it here too. - let repeat_detail = !(tools::approval(&call.name) == Approval::EveryCall - && approver.will_prompt_bash()); + let repeat_detail = + !(tools::approval(&call.name) == Approval::EveryCall && approver.will_prompt_bash()); ui::tool_line(label, &call.name, &args, repeat_detail); if let Err(error) = tools::validate(&call.name, &args) { 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 @@ +/* + * This file is part of agent686 + * Copyright (C) 2026 Salmonik + * SPDX-License-Identifier: GPL-3.0-or-later + * https://git.2137697.xyz/agent686 + */ + use std::path::PathBuf; use 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 @@ +/* + * This file is part of agent686 + * Copyright (C) 2026 Salmonik + * SPDX-License-Identifier: GPL-3.0-or-later + * https://git.2137697.xyz/agent686 + */ + use std::path::Path; use serde_json::json; @@ -32,7 +39,8 @@ pub fn run(cfg: &Config, json: bool) -> i32 { } record("key", true, detail); } - KeySource::Missing => record("key", + KeySource::Missing => record( + "key", false, "missing — set OPENCODE_API_KEY or write ~/.config/agent686/key".into(), ), @@ -55,11 +63,7 @@ pub fn run(cfg: &Config, json: bool) -> i32 { true, format!("{} ({} entries)", history.display(), text.lines().count()), ), - Err(_) => record( - "history", - true, - format!("{} (new)", history.display()), - ), + Err(_) => record("history", true, format!("{} (new)", history.display())), } record("provider", true, cfg.base_url.clone()); @@ -70,7 +74,11 @@ pub fn run(cfg: &Config, json: bool) -> i32 { } else { match provider::models(cfg) { Ok(models) => { - record("auth", true, format!("ok — {} models visible", models.len())); + record( + "auth", + true, + format!("ok — {} models visible", models.len()), + ); if models.iter().any(|id| id == &cfg.model) { record("model known", true, "yes".into()); } else { @@ -107,7 +115,11 @@ pub fn run(cfg: &Config, json: bool) -> i32 { ); println!(); for (label, ok, detail) in &checks { - println!("{:<13} {:<4} {detail}", label, if *ok { "ok" } else { "FAIL" }); + println!( + "{:<13} {:<4} {detail}", + label, + if *ok { "ok" } else { "FAIL" } + ); } println!(); 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 @@ +/* + * This file is part of agent686 + * Copyright (C) 2026 Salmonik + * SPDX-License-Identifier: GPL-3.0-or-later + * https://git.2137697.xyz/agent686 + */ + //! Git helpers for the checkpoint/undo feature. In a separate module so they //! are unit-testable without driving the whole CLI. 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 @@ +/* + * This file is part of agent686 + * Copyright (C) 2026 Salmonik + * SPDX-License-Identifier: GPL-3.0-or-later + * https://git.2137697.xyz/agent686 + */ + pub mod agent; pub mod config; pub 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 @@ +/* + * This file is part of agent686 + * Copyright (C) 2026 Salmonik + * SPDX-License-Identifier: GPL-3.0-or-later + * https://git.2137697.xyz/agent686 + */ + use std::io::{self, IsTerminal, Write}; use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; @@ -5,8 +12,8 @@ use std::path::PathBuf; use crossterm::cursor::{MoveToColumn, MoveUp}; use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; use crossterm::event::{DisableBracketedPaste, EnableBracketedPaste}; -use crossterm::terminal::{self, Clear, ClearType}; use crossterm::execute; +use crossterm::terminal::{self, Clear, ClearType}; const HISTORY_LIMIT: usize = 200; @@ -311,12 +318,7 @@ struct DrawState { cursor_row: usize, } -fn draw( - prompt: &str, - buffer: &[char], - cursor: usize, - state: &mut DrawState, -) -> io::Result<()> { +fn draw(prompt: &str, buffer: &[char], cursor: usize, state: &mut DrawState) -> io::Result<()> { let mut out = io::stdout(); draw_to(&mut out, prompt, buffer, cursor, state)?; out.flush() @@ -396,7 +398,10 @@ fn load_history() -> Vec { lines.drain(..lines.len() - HISTORY_LIMIT); // Keep the file from growing without bound, not just the in-memory list. if lines.len() * 2 < text.lines().count() { - let body: Vec = lines.iter().map(|line| line.replace('\n', "\u{0}")).collect(); + let body: Vec = lines + .iter() + .map(|line| line.replace('\n', "\u{0}")) + .collect(); let _ = std::fs::write(&path, format!("{}\n", body.join("\n"))); } } 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 @@ +/* + * This file is part of agent686 + * Copyright (C) 2026 Salmonik + * SPDX-License-Identifier: GPL-3.0-or-later + * https://git.2137697.xyz/agent686 + */ + use std::io::{BufRead, IsTerminal, Write}; use std::path::Path; use 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 @@ +/* + * This file is part of agent686 + * Copyright (C) 2026 Salmonik + * SPDX-License-Identifier: GPL-3.0-or-later + * https://git.2137697.xyz/agent686 + */ + use std::io::Read; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; @@ -183,9 +190,7 @@ fn explain(status: u16, message: &str) -> String { ); } if status == 401 || status == 403 { - return format!( - "{message}\n\ncheck the key: OPENCODE_API_KEY or ~/.config/agent686/key" - ); + return format!("{message}\n\ncheck the key: OPENCODE_API_KEY or ~/.config/agent686/key"); } if status == 429 { return format!( @@ -261,7 +266,10 @@ pub fn chat_with( .header("Content-Type", "application/json") .header("Accept", "text/event-stream") .header("Authorization", format!("Bearer {}", cfg.api_key)) - .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))); + .header( + "User-Agent", + concat!("agent686/", env!("CARGO_PKG_VERSION")), + ); // OpenCode requires a stable per-conversation id for routing and // prompt caching; a plain OpenAI-compatible endpoint must not get it. if cfg.provider.needs_session_header() { @@ -347,7 +355,14 @@ pub fn chat_with( Err(e) => return Err(Error::Transport(e.to_string())), }; for data in decoder.feed(&buf[..n]) { - if handle_event(&data, &mut outcome, &mut calls, &mut completed, &mut dropped, sink) { + if handle_event( + &data, + &mut outcome, + &mut calls, + &mut completed, + &mut dropped, + sink, + ) { done = true; break; } @@ -360,7 +375,14 @@ pub fn chat_with( // A final `data:` frame with no trailing newline is legitimate. if !done { for data in decoder.finish() { - if handle_event(&data, &mut outcome, &mut calls, &mut completed, &mut dropped, sink) { + if handle_event( + &data, + &mut outcome, + &mut calls, + &mut completed, + &mut dropped, + sink, + ) { break; } } @@ -389,7 +411,8 @@ pub fn chat_with( // be recorded as a complete answer. Lenient mode tolerates local servers // that finish with text but no [DONE]/finish_reason. if !completed { - let lenient_ok = cfg.lenient && outcome.tool_calls.is_empty() && !outcome.content.is_empty(); + let lenient_ok = + cfg.lenient && outcome.tool_calls.is_empty() && !outcome.content.is_empty(); if !lenient_ok { return Err(Error::Transport(format!( "stream ended before completion ({} bytes of text, {} tool call(s)); \ @@ -424,7 +447,11 @@ fn handle_event( } match serde_json::from_str::(data) { Ok(chunk) => { - if chunk.choices.iter().any(|choice| choice.finish_reason.is_some()) { + if chunk + .choices + .iter() + .any(|choice| choice.finish_reason.is_some()) + { *completed = true; } apply_chunk(&chunk, outcome, calls, sink); @@ -575,11 +602,16 @@ pub fn summarize(cfg: &Config, messages: &[Value]) -> Result { .post(&cfg.endpoint()) .header("Content-Type", "application/json") .header("Authorization", format!("Bearer {}", cfg.api_key)) - .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))); + .header( + "User-Agent", + concat!("agent686/", env!("CARGO_PKG_VERSION")), + ); if cfg.provider.needs_session_header() { request = request.header("x-opencode-session", &cfg.session); } - let mut response = request.send(bytes).map_err(|e| Error::Transport(e.to_string()))?; + let mut response = request + .send(bytes) + .map_err(|e| Error::Transport(e.to_string()))?; let status = response.status().as_u16(); let text = response @@ -610,11 +642,16 @@ pub fn models(cfg: &Config) -> Result, Error> { let mut request = agent .get(&url) .header("Authorization", format!("Bearer {}", cfg.api_key)) - .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))); + .header( + "User-Agent", + concat!("agent686/", env!("CARGO_PKG_VERSION")), + ); if cfg.provider.needs_session_header() { request = request.header("x-opencode-session", &cfg.session); } - let mut response = request.call().map_err(|e| Error::Transport(e.to_string()))?; + let mut response = request + .call() + .map_err(|e| Error::Transport(e.to_string()))?; let status = response.status().as_u16(); 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 @@ +/* + * This file is part of agent686 + * Copyright (C) 2026 Salmonik + * SPDX-License-Identifier: GPL-3.0-or-later + * https://git.2137697.xyz/agent686 + */ + use std::fs::{File, OpenOptions}; use std::hash::{Hash, Hasher}; use std::io::{BufRead, BufReader, Read, Write}; @@ -54,9 +61,7 @@ fn restrict(path: &Path, mode: u32) { fn lock_exclusive(file: &File, id: &str) -> Result<(), String> { let locked = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }; if locked != 0 { - return Err(format!( - "session {id} is already open in another process" - )); + return Err(format!("session {id} is already open in another process")); } Ok(()) } @@ -258,7 +263,9 @@ impl Session { pub fn rewrite(&mut self, system: &Value, messages: &[Value]) -> Result<(), String> { use std::io::{Seek, SeekFrom, Write}; self.file.set_len(0).map_err(|e| e.to_string())?; - self.file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?; + self.file + .seek(SeekFrom::Start(0)) + .map_err(|e| e.to_string())?; let header = json!({ "t": "header", "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 @@ +/* + * This file is part of agent686 + * Copyright (C) 2026 Salmonik + * SPDX-License-Identifier: GPL-3.0-or-later + * https://git.2137697.xyz/agent686 + */ + use std::sync::atomic::{AtomicBool, Ordering}; /// 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 @@ +/* + * This file is part of agent686 + * Copyright (C) 2026 Salmonik + * SPDX-License-Identifier: GPL-3.0-or-later + * https://git.2137697.xyz/agent686 + */ + use std::fs; use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; @@ -30,8 +37,15 @@ const SKIP_DIRS: &[&str] = &[ /// human agrees. The file is re-read at apply time, so an edit made while the /// approval prompt was open is not silently discarded. pub enum Change { - Write { path: String, content: String }, - Edit { path: String, old: String, new: String }, + Write { + path: String, + content: String, + }, + Edit { + path: String, + old: String, + new: String, + }, } impl Change { @@ -157,9 +171,11 @@ fn locate(text: &str, old: &str) -> Result { } } - Err("text to replace was not found. Read the file and copy the exact text, \ + Err( + "text to replace was not found. Read the file and copy the exact text, \ including indentation." - .to_string()) + .to_string(), + ) } /// 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 { pub fn read(args: &Value) -> Result { let path = req(args, "path")?; - let offset = args.get("offset").and_then(|v| v.as_u64()).unwrap_or(1).max(1); + let offset = args + .get("offset") + .and_then(|v| v.as_u64()) + .unwrap_or(1) + .max(1); let offset = usize::try_from(offset) .map_err(|_| format!("offset {offset} is too large for this build"))?; let limit = args @@ -622,7 +642,8 @@ fn walk(dir: &Path, out: &mut Vec) { walk(&path, out); } else if file_type.is_file() { out.push(path); - } else if file_type.is_symlink() && fs::metadata(&path).map(|m| m.is_file()).unwrap_or(false) + } else if file_type.is_symlink() + && fs::metadata(&path).map(|m| m.is_file()).unwrap_or(false) { // Follow file symlinks; symlinked directories are skipped so a loop // cannot walk forever. @@ -679,7 +700,10 @@ fn new_file_preview(path: &str, content: &str) -> String { out.push_str(&format!("+ {}\n", clip(line, 200))); } if lines.len() > PREVIEW_BUDGET { - out.push_str(&format!("… {} more line(s)\n", lines.len() - PREVIEW_BUDGET)); + out.push_str(&format!( + "… {} more line(s)\n", + lines.len() - PREVIEW_BUDGET + )); } out } 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 @@ +/* + * This file is part of agent686 + * Copyright (C) 2026 Salmonik + * SPDX-License-Identifier: GPL-3.0-or-later + * https://git.2137697.xyz/agent686 + */ + pub mod fs; pub mod shell; 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 @@ +/* + * This file is part of agent686 + * Copyright (C) 2026 Salmonik + * SPDX-License-Identifier: GPL-3.0-or-later + * https://git.2137697.xyz/agent686 + */ + use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use std::os::unix::process::{CommandExt, ExitStatusExt}; @@ -32,11 +39,7 @@ impl Drop for TempGuard { } } -pub fn bash( - args: &Value, - timeout: Duration, - cancel: &AtomicBool, -) -> Result { +pub fn bash(args: &Value, timeout: Duration, cancel: &AtomicBool) -> Result { let cmd = match args .get("cmd") .or_else(|| args.get("command")) @@ -146,14 +149,14 @@ pub fn bash( } else if aborted { "[aborted by the user]".to_string() } else if timed_out { - format!("[timed out after {:.1}s; process killed]", timeout.as_secs_f64()) + format!( + "[timed out after {:.1}s; process killed]", + timeout.as_secs_f64() + ) } else { match status.code() { Some(code) => format!("[exit {code}]"), - None => format!( - "[killed by signal {}]", - status.signal().unwrap_or_default() - ), + None => format!("[killed by signal {}]", status.signal().unwrap_or_default()), } }; 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 @@ +/* + * This file is part of agent686 + * Copyright (C) 2026 Salmonik + * SPDX-License-Identifier: GPL-3.0-or-later + * https://git.2137697.xyz/agent686 + */ + use std::io::{IsTerminal, Write}; use std::sync::OnceLock; use std::time::Duration; -- cgit v1.2.3