From 8c8f93e598644f6af5538e9ea28463f126f9abcb Mon Sep 17 00:00:00 2001 From: salmonik Date: Wed, 18 Nov 2026 12:39:38 +0100 Subject: 0.10.0: --json, /models /model /forget, git-repo gate for --yolo - --list/--show/--doctor gain --json for scripts - /models lists provider models, /model switches mid-session, /forget prunes sessions - --yolo refused outside a git repo (AGENT686_ALLOW_NOGIT=1 opts out) --- CHANGELOG.md | 14 +++++ Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 1 + src/doctor.rs | 138 +++++++++++++++++++++++++------------------- src/main.rs | 182 ++++++++++++++++++++++++++++++++++++++++++++++++++++------ tests/cli.rs | 99 ++++++++++++++++++++++++++++++++ 7 files changed, 360 insertions(+), 78 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f7bc83f..dc0cc9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,20 @@ break the interface, **PATCH** for bug fixes. file, and the tool schemas the model sees. Anything a script or a resumed session could depend on counts as API. +## 0.10.0 + +### Added +- `--json` for `--list`, `--show` and `--doctor`, so scripts can consume them. +- `/models` lists what the provider offers (the current model marked), and + `/model ` switches mid-session, recording the switch. +- `/forget ` deletes a session; `/forget --all` prunes every session except + the current one. + +### Changed +- `--yolo` is now refused outside a git repository as well as in `$HOME` and `/`, + because git is the documented undo and there is no undo without a `.git`. + `AGENT686_ALLOW_NOGIT=1` opts out. + ## 0.9.2 ### Fixed diff --git a/Cargo.lock b/Cargo.lock index ba44750..ecfdfd2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "agent686" -version = "0.9.1" +version = "0.9.2" dependencies = [ "crossterm", "libc", diff --git a/Cargo.toml b/Cargo.toml index c24fb94..e4a6ecb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "agent686" -version = "0.9.2" +version = "0.10.0" edition = "2021" description = "A small coding agent for Debian-class Linux" publish = false diff --git a/README.md b/README.md index cec5fbd..6f5260a 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ export OPENCODE_API_KEY=... # or write it to ~/.config/agent686/key ./agent686 -c # continue the most recent session ./agent686 --session # resume it, or create it if the id is new ./agent686 --list # id, model, message count, age +./agent686 --list --json # machine-readable ./agent686 --show [id] # render a transcript ./agent686 --doctor # key, dirs, provider, model ./agent686 --yolo "..." # approve every tool call diff --git a/src/doctor.rs b/src/doctor.rs index 65fca50..8baf1f7 100644 --- a/src/doctor.rs +++ b/src/doctor.rs @@ -1,109 +1,129 @@ use std::path::Path; +use serde_json::json; + use crate::config::{self, Config, KeySource}; use crate::provider; use crate::session; -/// Prints the state of everything the harness needs, and checks the things that -/// are cheap to check but expensive to discover mid-turn. -pub fn run(cfg: &Config) -> i32 { +/// Checks the things that are cheap to check but expensive to discover mid-turn. +/// Returns the process exit code; with `json` it prints one JSON object instead +/// of the human-readable rows. +pub fn run(cfg: &Config, json: bool) -> i32 { + let mut checks: Vec<(String, bool, String)> = Vec::new(); let mut failed = false; - - println!( - "agent686 {} · {} · {}", - env!("CARGO_PKG_VERSION"), - std::env::consts::ARCH, - std::env::consts::OS - ); - println!(); + let mut record = |label: &str, ok: bool, detail: String| { + if !ok { + failed = true; + } + checks.push((label.to_string(), ok, detail)); + }; match config::key_source() { - KeySource::Env => row(true, "key", "present in OPENCODE_API_KEY"), + KeySource::Env => record("key", true, "present in OPENCODE_API_KEY".into()), KeySource::File(path) => { - row(true, "key", &format!("present in {}", path.display())); + let mut detail = format!("present in {}", path.display()); use std::os::unix::fs::PermissionsExt; - if let Ok(meta) = std::fs::metadata(&path) { - if meta.permissions().mode() & 0o077 != 0 { - println!( - "{:<13} {:<4} {} is readable by other users; chmod 600 it", - "key perms", - "WARN", - path.display() - ); - } + if std::fs::metadata(&path) + .map(|m| m.permissions().mode() & 0o077 != 0) + .unwrap_or(false) + { + detail.push_str(" (readable by other users; chmod 600 it)"); } + record("key", true, detail); } - KeySource::Missing => { - row( - false, - "key", - "missing — set OPENCODE_API_KEY or write ~/.config/agent686/key", - ); - failed = true; - } + KeySource::Missing => record("key", + false, + "missing — set OPENCODE_API_KEY or write ~/.config/agent686/key".into(), + ), } let sessions = session::sessions_dir(); match probe_dir(&sessions) { - Ok(()) => row(true, "sessions", &sessions.display().to_string()), - Err(error) => { - row(false, "sessions", &format!("{}: {error}", sessions.display())); - failed = true; - } + Ok(()) => record("sessions", true, sessions.display().to_string()), + Err(error) => record( + "sessions", + false, + format!("{}: {error}", sessions.display()), + ), } let history = session::data_root().join("history"); match std::fs::read_to_string(&history) { - Ok(text) => row( + Ok(text) => record( + "history", true, + format!("{} ({} entries)", history.display(), text.lines().count()), + ), + Err(_) => record( "history", - &format!("{} ({} entries)", history.display(), text.lines().count()), + true, + format!("{} (new)", history.display()), ), - Err(_) => row(true, "history", &format!("{} (new)", history.display())), } - row(true, "provider", &cfg.base_url); - row(true, "model", &cfg.model); + record("provider", true, cfg.base_url.clone()); + record("model", true, cfg.model.clone()); if cfg.api_key.is_empty() { - row(false, "auth", "skipped: no key"); - failed = true; + record("auth", false, "skipped: no key".into()); } else { match provider::models(cfg) { Ok(models) => { - row(true, "auth", &format!("ok — {} models visible", models.len())); + record("auth", true, format!("ok — {} models visible", models.len())); if models.iter().any(|id| id == &cfg.model) { - row(true, "model known", "yes"); + record("model known", true, "yes".into()); } else { - row( - false, + record( "model known", - "no — the provider does not list this id; pick another with --model", + false, + "no — the provider does not list this id; pick another with --model".into(), ); - failed = true; } } - Err(error) => { - row(false, "auth", &error.to_string()); - failed = true; - } + Err(error) => record("auth", false, error.to_string()), + } + } + + if json { + let checks_json: serde_json::Map = checks + .iter() + .map(|(label, ok, detail)| (label.clone(), json!({ "ok": ok, "detail": detail }))) + .collect(); + let doc = json!({ + "version": env!("CARGO_PKG_VERSION"), + "arch": std::env::consts::ARCH, + "os": std::env::consts::OS, + "ok": !failed, + "checks": checks_json, + }); + println!("{}", serde_json::to_string(&doc).unwrap_or_default()); + } else { + println!( + "agent686 {} · {} · {}", + env!("CARGO_PKG_VERSION"), + std::env::consts::ARCH, + std::env::consts::OS + ); + println!(); + for (label, ok, detail) in &checks { + println!("{:<13} {:<4} {detail}", label, if *ok { "ok" } else { "FAIL" }); + } + println!(); + if failed { + println!("some checks failed"); + } else { + println!("all checks passed"); } } - println!(); if failed { - println!("some checks failed"); 1 } else { - println!("all checks passed"); 0 } } -fn row(ok: bool, label: &str, detail: &str) { - println!("{:<13} {:<4} {detail}", label, if ok { "ok" } else { "FAIL" }); -} - fn probe_dir(dir: &Path) -> std::io::Result<()> { std::fs::create_dir_all(dir)?; let probe = dir.join(".doctor-probe"); diff --git a/src/main.rs b/src/main.rs index b17359b..a425d71 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,6 @@ use std::io::{BufRead, IsTerminal, Write}; +use serde_json::json; +use std::time::UNIX_EPOCH; use std::path::PathBuf; use std::time::SystemTime; @@ -60,6 +62,7 @@ struct Args { show: Option>, doctor: bool, yolo: bool, + json: bool, } fn main() { @@ -84,6 +87,7 @@ fn parse_args() -> Result { show: None, doctor: false, yolo: false, + json: false, }; let mut words: Vec = Vec::new(); let mut iter = std::env::args().skip(1).peekable(); @@ -137,6 +141,7 @@ fn parse_args() -> Result { } "--doctor" => args.doctor = true, "--yolo" => args.yolo = true, + "--json" => args.json = true, "-V" | "--version" => { println!("agent686 {}", env!("CARGO_PKG_VERSION")); std::process::exit(0); @@ -201,12 +206,12 @@ fn run(args: Args) { signal::install(); if let Some(id) = args.show { - show_session(id); + show_session(id, args.json); return; } if args.list { - print_sessions(); + print_sessions(args.json); return; } @@ -214,7 +219,7 @@ fn run(args: Args) { let mut config = Config::resolve_lenient(args.model, args.base_url, args.yolo); // `/models` needs the session header too, even though this is not a turn. config.session = session::new_id(); - std::process::exit(doctor::run(&config)); + std::process::exit(doctor::run(&config, args.json)); } let mut cfg = match Config::resolve(args.model, args.base_url, args.yolo) { @@ -249,7 +254,7 @@ fn run(args: Args) { if !session.model.is_empty() && session.model != cfg.model { let _ = session.record_model(&cfg.model); } - refuse_yolo_at_home(&cfg); + refuse_yolo(&cfg); let mut approver = Approver::new(cfg.yolo); let watched = agent::agents_md(); @@ -313,6 +318,19 @@ fn run(args: Args) { continue; } + if text == "/models" { + list_models(&cfg); + continue; + } + if let Some(model) = text.strip_prefix("/model ") { + switch_model(&mut cfg, &mut session, model.trim()); + continue; + } + if text == "/forget" || text.starts_with("/forget ") { + forget_sessions(&text, &session); + continue; + } + match text.as_str() { "/exit" | "/quit" => break, "/help" => { @@ -421,6 +439,82 @@ fn open_session( /// The system prompt is frozen with the directory the session started in. If the /// user resumes from somewhere else, tools and prompt disagree. +fn list_models(cfg: &Config) { + match agent686::provider::models(cfg) { + Ok(models) => { + for model in models { + if model == cfg.model { + println!("* {model}"); + } else { + println!(" {model}"); + } + } + } + Err(error) => eprintln!("agent686: {error}"), + } +} + +fn switch_model(cfg: &mut Config, session: &mut Session, model: &str) { + if model.is_empty() { + eprintln!("agent686: /model needs a model id"); + return; + } + if model == cfg.model { + eprintln!("agent686: already using {model}"); + return; + } + cfg.model = model.to_string(); + // The prompt and tool schemas are unchanged, but the model differs, so the + // provider's prefix cache restarts. + match session.record_model(model) { + Ok(()) => eprintln!("agent686: switched to {model}"), + Err(error) => eprintln!("agent686: {error}"), + } +} + +fn forget_sessions(text: &str, current: &Session) { + let dir = session::sessions_dir(); + let target = text.trim_start_matches("/forget").trim(); + if target == "--all" { + let removed = remove_all_except(&dir, ¤t.id); + eprintln!("agent686: removed {removed} session(s)"); + return; + } + if target.is_empty() { + eprintln!("agent686: /forget or /forget --all"); + return; + } + if target == current.id { + eprintln!("agent686: that is the current session; /forget it from elsewhere"); + return; + } + let path = dir.join(format!("{target}.jsonl")); + match std::fs::remove_file(&path) { + Ok(()) => eprintln!("agent686: removed {target}"), + Err(error) => eprintln!("agent686: {target}: {error}"), + } +} + +fn remove_all_except(dir: &std::path::Path, keep: &str) -> usize { + let mut removed = 0; + let Ok(entries) = std::fs::read_dir(dir) else { + return 0; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.extension().and_then(|e| e.to_str()) != Some("jsonl") { + continue; + } + if path.file_stem().and_then(|s| s.to_str()) == Some(keep) { + continue; + } + if std::fs::remove_file(&path).is_ok() { + removed += 1; + } + } + removed +} + fn warn_if_moved(session: &Session) { if session.cwd.is_empty() { return; @@ -456,7 +550,7 @@ fn warn_if_changed(watched: &Option<(PathBuf, SystemTime)>, warned: &mut bool) { } } -fn print_sessions() { +fn print_sessions(json: bool) { let sessions = match session::list() { Ok(sessions) => sessions, Err(error) => { @@ -464,6 +558,23 @@ fn print_sessions() { return; } }; + if json { + let rows: Vec = sessions + .iter() + .map(|info| { + json!({ + "id": info.id, + "model": info.model, + "messages": info.messages, + "modified_ms": info.modified.duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as u64).unwrap_or(0), + "path": info.path.display().to_string(), + }) + }) + .collect(); + println!("{}", serde_json::to_string(&rows).unwrap_or_else(|_| "[]".into())); + return; + } if sessions.is_empty() { println!("no sessions"); return; @@ -496,29 +607,49 @@ fn ago(modified: SystemTime) -> String { } } -/// `--yolo` with no approval at all in `$HOME` or `/` is how a transcript ends up -/// overwriting `.bashrc` or deleting a checkout. Refuse it unless asked twice. -fn refuse_yolo_at_home(cfg: &Config) { +/// `--yolo` with no approval and no undo is how a transcript ends up deleting a +/// checkout. Git is the documented undo, so `--yolo` needs a repository unless +/// asked twice. `$HOME` and `/` are refused outright. +fn refuse_yolo(cfg: &Config) { if !cfg.yolo { return; } - if std::env::var_os("AGENT686_ALLOW_HOME").is_some() { - return; - } let Ok(cwd) = std::env::current_dir() else { return; }; + let home = std::env::var_os("HOME").map(PathBuf::from); let at_home = home.as_deref() == Some(cwd.as_path()); let at_root = cwd.parent().is_none(); - if at_home || at_root { + if (at_home || at_root) && std::env::var_os("AGENT686_ALLOW_HOME").is_none() { eprintln!( "agent686: refusing --yolo in {} — the model can overwrite anything here. \ - Run inside a project directory, or set AGENT686_ALLOW_HOME=1.", + Run inside a project, or set AGENT686_ALLOW_HOME=1.", cwd.display() ); std::process::exit(2); } + + if !in_git_repo(&cwd) && std::env::var_os("AGENT686_ALLOW_NOGIT").is_none() { + eprintln!( + "agent686: refusing --yolo outside a git repository ({} has no .git), so \ + there is no undo. Run git init, or set AGENT686_ALLOW_NOGIT=1.", + cwd.display() + ); + std::process::exit(2); + } +} + +fn in_git_repo(dir: &std::path::Path) -> bool { + let mut current = dir.to_path_buf(); + loop { + if current.join(".git").exists() { + return true; + } + if !current.pop() { + return false; + } + } } fn style(code: &str, text: &str, color: bool) -> String { @@ -548,7 +679,7 @@ fn truncate_line(line: &str, max: usize) -> String { /// Renders a transcript: what was said, what was asked, what came back. Reads /// the file without locking so it works while a session is open elsewhere. -fn show_session(id: Option) { +fn show_session(id: Option, json: bool) { let id = match id.or_else(|| session::latest().ok().flatten()) { Some(id) => id, None => { @@ -571,8 +702,9 @@ fn show_session(id: Option) { let mut model = String::from("?"); let mut cwd = String::new(); - let mut messages = 0usize; + let mut count = 0usize; let mut rendered = Vec::new(); + let mut messages_json: Vec = Vec::new(); for line in text.lines() { let value: Value = match serde_json::from_str(line) { @@ -598,18 +730,34 @@ fn show_session(id: Option) { } } Some("msg") => { - messages += 1; + count += 1; + let mut message = value.clone(); + if let Some(object) = message.as_object_mut() { + object.remove("t"); + } + messages_json.push(message.clone()); rendered.push(render_message(&value, color)); } _ => {} } } + if json { + let doc = json!({ + "id": id, + "model": model, + "cwd": cwd, + "messages": messages_json, + }); + println!("{}", serde_json::to_string(&doc).unwrap_or_default()); + return; + } + println!( "{}", style( "1", - &format!("session {id} · {model} · {messages} messages"), + &format!("session {id} · {model} · {count} messages"), color ) ); diff --git a/tests/cli.rs b/tests/cli.rs index 80eb96d..72edbd1 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -103,6 +103,7 @@ fn yolo_in_home_can_be_forced() { .env("HOME", &home) .env("OPENCODE_API_KEY", "test") .env("AGENT686_ALLOW_HOME", "1") + .env("AGENT686_ALLOW_NOGIT", "1") .args(["--yolo", "--session", "forced"]) .stdin(std::process::Stdio::null()) .output() @@ -170,3 +171,101 @@ fn a_flag_shaped_value_is_rejected_unless_attached() { .join(".local/share/agent686/sessions/-abc.jsonl") .exists()); } + +#[test] +fn yolo_is_refused_outside_a_git_repo() { + let home = temp_home("nogit"); + let dir = home.join("proj"); + fs::create_dir_all(&dir).unwrap(); + + let output = agent() + .current_dir(&dir) + .env("HOME", &home) + .env("OPENCODE_API_KEY", "test") + .arg("--yolo") + .stdin(std::process::Stdio::null()) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(2), "{output:?}"); + assert!( + String::from_utf8_lossy(&output.stderr).contains("git repository"), + "{:?}", + String::from_utf8_lossy(&output.stderr) + ); + + let output = agent() + .current_dir(&dir) + .env("HOME", &home) + .env("OPENCODE_API_KEY", "test") + .env("AGENT686_ALLOW_NOGIT", "1") + .args(["--yolo", "--session", "ok"]) + .stdin(std::process::Stdio::null()) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(0), "{output:?}"); +} + +#[test] +fn yolo_is_allowed_inside_a_git_repo() { + let home = temp_home("git-repo"); + let dir = home.join("repo"); + fs::create_dir_all(dir.join(".git")).unwrap(); + + let output = agent() + .current_dir(&dir) + .env("HOME", &home) + .env("OPENCODE_API_KEY", "test") + .args(["--yolo", "--session", "inside"]) + .stdin(std::process::Stdio::null()) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(0), "{output:?}"); +} + +#[test] +fn list_and_show_and_doctor_support_json() { + use serde_json::json; + + let home = temp_home("json"); + let sessions = home.join(".local/share/agent686/sessions"); + fs::create_dir_all(&sessions).unwrap(); + let lines = [ + json!({"t":"header","session":"demo","model":"m","cwd":"/tmp","version":"0.0.0", + "system":{"role":"system","content":"s"}}), + json!({"t":"msg","role":"user","content":"hi"}), + json!({"t":"msg","role":"assistant","content":"yo","_reasoning":"r"}), + ]; + let body: String = lines.iter().map(|line| format!("{line}\n")).collect(); + fs::write(sessions.join("demo.jsonl"), body).unwrap(); + + let list = agent().env("HOME", &home).args(["--list", "--json"]).output().unwrap(); + assert!(list.status.success(), "{list:?}"); + let list_json: serde_json::Value = serde_json::from_slice(&list.stdout).unwrap(); + assert!(list_json.is_array()); + assert_eq!(list_json[0]["id"], "demo"); + + let show = agent() + .env("HOME", &home) + .args(["--show", "demo", "--json"]) + .output() + .unwrap(); + assert!(show.status.success(), "{show:?}"); + let show_json: serde_json::Value = serde_json::from_slice(&show.stdout).unwrap(); + assert_eq!(show_json["id"], "demo"); + assert_eq!(show_json["messages"].as_array().unwrap().len(), 2); + assert_eq!(show_json["messages"][1]["_reasoning"], "r"); + + let doctor = agent() + .env("HOME", &home) + .env_remove("OPENCODE_API_KEY") + .args(["--doctor", "--json"]) + .output() + .unwrap(); + assert_eq!(doctor.status.code(), Some(1), "{doctor:?}"); + let doctor_json: serde_json::Value = serde_json::from_slice(&doctor.stdout).unwrap(); + assert_eq!(doctor_json["ok"], false); + assert!(doctor_json["checks"]["key"]["detail"] + .as_str() + .unwrap() + .contains("missing")); +} -- cgit v1.2.3