diff options
| author | salmonik <salmonik@tuta.io> | 2026-11-18 12:39:38 +0100 |
|---|---|---|
| committer | salmonik <salmonik@tuta.io> | 2026-11-18 12:39:38 +0100 |
| commit | 8c8f93e598644f6af5538e9ea28463f126f9abcb (patch) | |
| tree | 47fd5e49724a5e9ba175f0c232360ddda591e7ab | |
| parent | 0.9.2: doc accuracy and UX fixes from the review (diff) | |
| download | agent686-8c8f93e598644f6af5538e9ea28463f126f9abcb.tar.gz agent686-8c8f93e598644f6af5538e9ea28463f126f9abcb.zip | |
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)
Diffstat (limited to '')
| -rw-r--r-- | CHANGELOG.md | 14 | ||||
| -rw-r--r-- | Cargo.lock | 2 | ||||
| -rw-r--r-- | Cargo.toml | 2 | ||||
| -rw-r--r-- | README.md | 1 | ||||
| -rw-r--r-- | src/doctor.rs | 138 | ||||
| -rw-r--r-- | src/main.rs | 182 | ||||
| -rw-r--r-- | 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. | |||
| 7 | file, and the tool schemas the model sees. Anything a script or a resumed session | 7 | file, and the tool schemas the model sees. Anything a script or a resumed session |
| 8 | could depend on counts as API. | 8 | could depend on counts as API. |
| 9 | 9 | ||
| 10 | ## 0.10.0 | ||
| 11 | |||
| 12 | ### Added | ||
| 13 | - `--json` for `--list`, `--show` and `--doctor`, so scripts can consume them. | ||
| 14 | - `/models` lists what the provider offers (the current model marked), and | ||
| 15 | `/model <id>` switches mid-session, recording the switch. | ||
| 16 | - `/forget <id>` deletes a session; `/forget --all` prunes every session except | ||
| 17 | the current one. | ||
| 18 | |||
| 19 | ### Changed | ||
| 20 | - `--yolo` is now refused outside a git repository as well as in `$HOME` and `/`, | ||
| 21 | because git is the documented undo and there is no undo without a `.git`. | ||
| 22 | `AGENT686_ALLOW_NOGIT=1` opts out. | ||
| 23 | |||
| 10 | ## 0.9.2 | 24 | ## 0.9.2 |
| 11 | 25 | ||
| 12 | ### Fixed | 26 | ### Fixed |
| @@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" | |||
| 10 | 10 | ||
| 11 | [[package]] | 11 | [[package]] |
| 12 | name = "agent686" | 12 | name = "agent686" |
| 13 | version = "0.9.1" | 13 | version = "0.9.2" |
| 14 | dependencies = [ | 14 | dependencies = [ |
| 15 | "crossterm", | 15 | "crossterm", |
| 16 | "libc", | 16 | "libc", |
| @@ -1,6 +1,6 @@ | |||
| 1 | [package] | 1 | [package] |
| 2 | name = "agent686" | 2 | name = "agent686" |
| 3 | version = "0.9.2" | 3 | version = "0.10.0" |
| 4 | edition = "2021" | 4 | edition = "2021" |
| 5 | description = "A small coding agent for Debian-class Linux" | 5 | description = "A small coding agent for Debian-class Linux" |
| 6 | publish = false | 6 | publish = false |
| @@ -49,6 +49,7 @@ export OPENCODE_API_KEY=... # or write it to ~/.config/agent686/key | |||
| 49 | ./agent686 -c # continue the most recent session | 49 | ./agent686 -c # continue the most recent session |
| 50 | ./agent686 --session <id> # resume it, or create it if the id is new | 50 | ./agent686 --session <id> # resume it, or create it if the id is new |
| 51 | ./agent686 --list # id, model, message count, age | 51 | ./agent686 --list # id, model, message count, age |
| 52 | ./agent686 --list --json # machine-readable | ||
| 52 | ./agent686 --show [id] # render a transcript | 53 | ./agent686 --show [id] # render a transcript |
| 53 | ./agent686 --doctor # key, dirs, provider, model | 54 | ./agent686 --doctor # key, dirs, provider, model |
| 54 | ./agent686 --yolo "..." # approve every tool call | 55 | ./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 @@ | |||
| 1 | use std::path::Path; | 1 | use std::path::Path; |
| 2 | 2 | ||
| 3 | use serde_json::json; | ||
| 4 | |||
| 3 | use crate::config::{self, Config, KeySource}; | 5 | use crate::config::{self, Config, KeySource}; |
| 4 | use crate::provider; | 6 | use crate::provider; |
| 5 | use crate::session; | 7 | use crate::session; |
| 6 | 8 | ||
| 7 | /// Prints the state of everything the harness needs, and checks the things that | 9 | /// Checks the things that are cheap to check but expensive to discover mid-turn. |
| 8 | /// are cheap to check but expensive to discover mid-turn. | 10 | /// Returns the process exit code; with `json` it prints one JSON object instead |
| 9 | pub fn run(cfg: &Config) -> i32 { | 11 | /// of the human-readable rows. |
| 12 | pub fn run(cfg: &Config, json: bool) -> i32 { | ||
| 13 | let mut checks: Vec<(String, bool, String)> = Vec::new(); | ||
| 10 | let mut failed = false; | 14 | let mut failed = false; |
| 11 | 15 | let mut record = |label: &str, ok: bool, detail: String| { | |
| 12 | println!( | 16 | if !ok { |
| 13 | "agent686 {} · {} · {}", | 17 | failed = true; |
| 14 | env!("CARGO_PKG_VERSION"), | 18 | } |
| 15 | std::env::consts::ARCH, | 19 | checks.push((label.to_string(), ok, detail)); |
| 16 | std::env::consts::OS | 20 | }; |
| 17 | ); | ||
| 18 | println!(); | ||
| 19 | 21 | ||
| 20 | match config::key_source() { | 22 | match config::key_source() { |
| 21 | KeySource::Env => row(true, "key", "present in OPENCODE_API_KEY"), | 23 | KeySource::Env => record("key", true, "present in OPENCODE_API_KEY".into()), |
| 22 | KeySource::File(path) => { | 24 | KeySource::File(path) => { |
| 23 | row(true, "key", &format!("present in {}", path.display())); | 25 | let mut detail = format!("present in {}", path.display()); |
| 24 | use std::os::unix::fs::PermissionsExt; | 26 | use std::os::unix::fs::PermissionsExt; |
| 25 | if let Ok(meta) = std::fs::metadata(&path) { | 27 | if std::fs::metadata(&path) |
| 26 | if meta.permissions().mode() & 0o077 != 0 { | 28 | .map(|m| m.permissions().mode() & 0o077 != 0) |
| 27 | println!( | 29 | .unwrap_or(false) |
| 28 | "{:<13} {:<4} {} is readable by other users; chmod 600 it", | 30 | { |
| 29 | "key perms", | 31 | detail.push_str(" (readable by other users; chmod 600 it)"); |
| 30 | "WARN", | ||
| 31 | path.display() | ||
| 32 | ); | ||
| 33 | } | ||
| 34 | } | 32 | } |
| 33 | record("key", true, detail); | ||
| 35 | } | 34 | } |
| 36 | KeySource::Missing => { | 35 | KeySource::Missing => record("key", |
| 37 | row( | 36 | false, |
| 38 | false, | 37 | "missing — set OPENCODE_API_KEY or write ~/.config/agent686/key".into(), |
| 39 | "key", | 38 | ), |
| 40 | "missing — set OPENCODE_API_KEY or write ~/.config/agent686/key", | ||
| 41 | ); | ||
| 42 | failed = true; | ||
| 43 | } | ||
| 44 | } | 39 | } |
| 45 | 40 | ||
| 46 | let sessions = session::sessions_dir(); | 41 | let sessions = session::sessions_dir(); |
| 47 | match probe_dir(&sessions) { | 42 | match probe_dir(&sessions) { |
| 48 | Ok(()) => row(true, "sessions", &sessions.display().to_string()), | 43 | Ok(()) => record("sessions", true, sessions.display().to_string()), |
| 49 | Err(error) => { | 44 | Err(error) => record( |
| 50 | row(false, "sessions", &format!("{}: {error}", sessions.display())); | 45 | "sessions", |
| 51 | failed = true; | 46 | false, |
| 52 | } | 47 | format!("{}: {error}", sessions.display()), |
| 48 | ), | ||
| 53 | } | 49 | } |
| 54 | 50 | ||
| 55 | let history = session::data_root().join("history"); | 51 | let history = session::data_root().join("history"); |
| 56 | match std::fs::read_to_string(&history) { | 52 | match std::fs::read_to_string(&history) { |
| 57 | Ok(text) => row( | 53 | Ok(text) => record( |
| 54 | "history", | ||
| 58 | true, | 55 | true, |
| 56 | format!("{} ({} entries)", history.display(), text.lines().count()), | ||
| 57 | ), | ||
| 58 | Err(_) => record( | ||
| 59 | "history", | 59 | "history", |
| 60 | &format!("{} ({} entries)", history.display(), text.lines().count()), | 60 | true, |
| 61 | format!("{} (new)", history.display()), | ||
| 61 | ), | 62 | ), |
| 62 | Err(_) => row(true, "history", &format!("{} (new)", history.display())), | ||
| 63 | } | 63 | } |
| 64 | 64 | ||
| 65 | row(true, "provider", &cfg.base_url); | 65 | record("provider", true, cfg.base_url.clone()); |
| 66 | row(true, "model", &cfg.model); | 66 | record("model", true, cfg.model.clone()); |
| 67 | 67 | ||
| 68 | if cfg.api_key.is_empty() { | 68 | if cfg.api_key.is_empty() { |
| 69 | row(false, "auth", "skipped: no key"); | 69 | record("auth", false, "skipped: no key".into()); |
| 70 | failed = true; | ||
| 71 | } else { | 70 | } else { |
| 72 | match provider::models(cfg) { | 71 | match provider::models(cfg) { |
| 73 | Ok(models) => { | 72 | Ok(models) => { |
| 74 | row(true, "auth", &format!("ok — {} models visible", models.len())); | 73 | record("auth", true, format!("ok — {} models visible", models.len())); |
| 75 | if models.iter().any(|id| id == &cfg.model) { | 74 | if models.iter().any(|id| id == &cfg.model) { |
| 76 | row(true, "model known", "yes"); | 75 | record("model known", true, "yes".into()); |
| 77 | } else { | 76 | } else { |
| 78 | row( | 77 | record( |
| 79 | false, | ||
| 80 | "model known", | 78 | "model known", |
| 81 | "no — the provider does not list this id; pick another with --model", | 79 | false, |
| 80 | "no — the provider does not list this id; pick another with --model".into(), | ||
| 82 | ); | 81 | ); |
| 83 | failed = true; | ||
| 84 | } | 82 | } |
| 85 | } | 83 | } |
| 86 | Err(error) => { | 84 | Err(error) => record("auth", false, error.to_string()), |
| 87 | row(false, "auth", &error.to_string()); | 85 | } |
| 88 | failed = true; | 86 | } |
| 89 | } | 87 | |
| 88 | if json { | ||
| 89 | let checks_json: serde_json::Map<String, serde_json::Value> = checks | ||
| 90 | .iter() | ||
| 91 | .map(|(label, ok, detail)| (label.clone(), json!({ "ok": ok, "detail": detail }))) | ||
| 92 | .collect(); | ||
| 93 | let doc = json!({ | ||
| 94 | "version": env!("CARGO_PKG_VERSION"), | ||
| 95 | "arch": std::env::consts::ARCH, | ||
| 96 | "os": std::env::consts::OS, | ||
| 97 | "ok": !failed, | ||
| 98 | "checks": checks_json, | ||
| 99 | }); | ||
| 100 | println!("{}", serde_json::to_string(&doc).unwrap_or_default()); | ||
| 101 | } else { | ||
| 102 | println!( | ||
| 103 | "agent686 {} · {} · {}", | ||
| 104 | env!("CARGO_PKG_VERSION"), | ||
| 105 | std::env::consts::ARCH, | ||
| 106 | std::env::consts::OS | ||
| 107 | ); | ||
| 108 | println!(); | ||
| 109 | for (label, ok, detail) in &checks { | ||
| 110 | println!("{:<13} {:<4} {detail}", label, if *ok { "ok" } else { "FAIL" }); | ||
| 111 | } | ||
| 112 | println!(); | ||
| 113 | if failed { | ||
| 114 | println!("some checks failed"); | ||
| 115 | } else { | ||
| 116 | println!("all checks passed"); | ||
| 90 | } | 117 | } |
| 91 | } | 118 | } |
| 92 | 119 | ||
| 93 | println!(); | ||
| 94 | if failed { | 120 | if failed { |
| 95 | println!("some checks failed"); | ||
| 96 | 1 | 121 | 1 |
| 97 | } else { | 122 | } else { |
| 98 | println!("all checks passed"); | ||
| 99 | 0 | 123 | 0 |
| 100 | } | 124 | } |
| 101 | } | 125 | } |
| 102 | 126 | ||
| 103 | fn row(ok: bool, label: &str, detail: &str) { | ||
| 104 | println!("{:<13} {:<4} {detail}", label, if ok { "ok" } else { "FAIL" }); | ||
| 105 | } | ||
| 106 | |||
| 107 | fn probe_dir(dir: &Path) -> std::io::Result<()> { | 127 | fn probe_dir(dir: &Path) -> std::io::Result<()> { |
| 108 | std::fs::create_dir_all(dir)?; | 128 | std::fs::create_dir_all(dir)?; |
| 109 | let probe = dir.join(".doctor-probe"); | 129 | 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 @@ | |||
| 1 | use std::io::{BufRead, IsTerminal, Write}; | 1 | use std::io::{BufRead, IsTerminal, Write}; |
| 2 | use serde_json::json; | ||
| 3 | use std::time::UNIX_EPOCH; | ||
| 2 | use std::path::PathBuf; | 4 | use std::path::PathBuf; |
| 3 | use std::time::SystemTime; | 5 | use std::time::SystemTime; |
| 4 | 6 | ||
| @@ -60,6 +62,7 @@ struct Args { | |||
| 60 | show: Option<Option<String>>, | 62 | show: Option<Option<String>>, |
| 61 | doctor: bool, | 63 | doctor: bool, |
| 62 | yolo: bool, | 64 | yolo: bool, |
| 65 | json: bool, | ||
| 63 | } | 66 | } |
| 64 | 67 | ||
| 65 | fn main() { | 68 | fn main() { |
| @@ -84,6 +87,7 @@ fn parse_args() -> Result<Args, String> { | |||
| 84 | show: None, | 87 | show: None, |
| 85 | doctor: false, | 88 | doctor: false, |
| 86 | yolo: false, | 89 | yolo: false, |
| 90 | json: false, | ||
| 87 | }; | 91 | }; |
| 88 | let mut words: Vec<String> = Vec::new(); | 92 | let mut words: Vec<String> = Vec::new(); |
| 89 | let mut iter = std::env::args().skip(1).peekable(); | 93 | let mut iter = std::env::args().skip(1).peekable(); |
| @@ -137,6 +141,7 @@ fn parse_args() -> Result<Args, String> { | |||
| 137 | } | 141 | } |
| 138 | "--doctor" => args.doctor = true, | 142 | "--doctor" => args.doctor = true, |
| 139 | "--yolo" => args.yolo = true, | 143 | "--yolo" => args.yolo = true, |
| 144 | "--json" => args.json = true, | ||
| 140 | "-V" | "--version" => { | 145 | "-V" | "--version" => { |
| 141 | println!("agent686 {}", env!("CARGO_PKG_VERSION")); | 146 | println!("agent686 {}", env!("CARGO_PKG_VERSION")); |
| 142 | std::process::exit(0); | 147 | std::process::exit(0); |
| @@ -201,12 +206,12 @@ fn run(args: Args) { | |||
| 201 | signal::install(); | 206 | signal::install(); |
| 202 | 207 | ||
| 203 | if let Some(id) = args.show { | 208 | if let Some(id) = args.show { |
| 204 | show_session(id); | 209 | show_session(id, args.json); |
| 205 | return; | 210 | return; |
| 206 | } | 211 | } |
| 207 | 212 | ||
| 208 | if args.list { | 213 | if args.list { |
| 209 | print_sessions(); | 214 | print_sessions(args.json); |
| 210 | return; | 215 | return; |
| 211 | } | 216 | } |
| 212 | 217 | ||
| @@ -214,7 +219,7 @@ fn run(args: Args) { | |||
| 214 | let mut config = Config::resolve_lenient(args.model, args.base_url, args.yolo); | 219 | let mut config = Config::resolve_lenient(args.model, args.base_url, args.yolo); |
| 215 | // `/models` needs the session header too, even though this is not a turn. | 220 | // `/models` needs the session header too, even though this is not a turn. |
| 216 | config.session = session::new_id(); | 221 | config.session = session::new_id(); |
| 217 | std::process::exit(doctor::run(&config)); | 222 | std::process::exit(doctor::run(&config, args.json)); |
| 218 | } | 223 | } |
| 219 | 224 | ||
| 220 | let mut cfg = match Config::resolve(args.model, args.base_url, args.yolo) { | 225 | let mut cfg = match Config::resolve(args.model, args.base_url, args.yolo) { |
| @@ -249,7 +254,7 @@ fn run(args: Args) { | |||
| 249 | if !session.model.is_empty() && session.model != cfg.model { | 254 | if !session.model.is_empty() && session.model != cfg.model { |
| 250 | let _ = session.record_model(&cfg.model); | 255 | let _ = session.record_model(&cfg.model); |
| 251 | } | 256 | } |
| 252 | refuse_yolo_at_home(&cfg); | 257 | refuse_yolo(&cfg); |
| 253 | 258 | ||
| 254 | let mut approver = Approver::new(cfg.yolo); | 259 | let mut approver = Approver::new(cfg.yolo); |
| 255 | let watched = agent::agents_md(); | 260 | let watched = agent::agents_md(); |
| @@ -313,6 +318,19 @@ fn run(args: Args) { | |||
| 313 | continue; | 318 | continue; |
| 314 | } | 319 | } |
| 315 | 320 | ||
| 321 | if text == "/models" { | ||
| 322 | list_models(&cfg); | ||
| 323 | continue; | ||
| 324 | } | ||
| 325 | if let Some(model) = text.strip_prefix("/model ") { | ||
| 326 | switch_model(&mut cfg, &mut session, model.trim()); | ||
| 327 | continue; | ||
| 328 | } | ||
| 329 | if text == "/forget" || text.starts_with("/forget ") { | ||
| 330 | forget_sessions(&text, &session); | ||
| 331 | continue; | ||
| 332 | } | ||
| 333 | |||
| 316 | match text.as_str() { | 334 | match text.as_str() { |
| 317 | "/exit" | "/quit" => break, | 335 | "/exit" | "/quit" => break, |
| 318 | "/help" => { | 336 | "/help" => { |
| @@ -421,6 +439,82 @@ fn open_session( | |||
| 421 | 439 | ||
| 422 | /// The system prompt is frozen with the directory the session started in. If the | 440 | /// The system prompt is frozen with the directory the session started in. If the |
| 423 | /// user resumes from somewhere else, tools and prompt disagree. | 441 | /// user resumes from somewhere else, tools and prompt disagree. |
| 442 | fn list_models(cfg: &Config) { | ||
| 443 | match agent686::provider::models(cfg) { | ||
| 444 | Ok(models) => { | ||
| 445 | for model in models { | ||
| 446 | if model == cfg.model { | ||
| 447 | println!("* {model}"); | ||
| 448 | } else { | ||
| 449 | println!(" {model}"); | ||
| 450 | } | ||
| 451 | } | ||
| 452 | } | ||
| 453 | Err(error) => eprintln!("agent686: {error}"), | ||
| 454 | } | ||
| 455 | } | ||
| 456 | |||
| 457 | fn switch_model(cfg: &mut Config, session: &mut Session, model: &str) { | ||
| 458 | if model.is_empty() { | ||
| 459 | eprintln!("agent686: /model needs a model id"); | ||
| 460 | return; | ||
| 461 | } | ||
| 462 | if model == cfg.model { | ||
| 463 | eprintln!("agent686: already using {model}"); | ||
| 464 | return; | ||
| 465 | } | ||
| 466 | cfg.model = model.to_string(); | ||
| 467 | // The prompt and tool schemas are unchanged, but the model differs, so the | ||
| 468 | // provider's prefix cache restarts. | ||
| 469 | match session.record_model(model) { | ||
| 470 | Ok(()) => eprintln!("agent686: switched to {model}"), | ||
| 471 | Err(error) => eprintln!("agent686: {error}"), | ||
| 472 | } | ||
| 473 | } | ||
| 474 | |||
| 475 | fn forget_sessions(text: &str, current: &Session) { | ||
| 476 | let dir = session::sessions_dir(); | ||
| 477 | let target = text.trim_start_matches("/forget").trim(); | ||
| 478 | if target == "--all" { | ||
| 479 | let removed = remove_all_except(&dir, ¤t.id); | ||
| 480 | eprintln!("agent686: removed {removed} session(s)"); | ||
| 481 | return; | ||
| 482 | } | ||
| 483 | if target.is_empty() { | ||
| 484 | eprintln!("agent686: /forget <id> or /forget --all"); | ||
| 485 | return; | ||
| 486 | } | ||
| 487 | if target == current.id { | ||
| 488 | eprintln!("agent686: that is the current session; /forget it from elsewhere"); | ||
| 489 | return; | ||
| 490 | } | ||
| 491 | let path = dir.join(format!("{target}.jsonl")); | ||
| 492 | match std::fs::remove_file(&path) { | ||
| 493 | Ok(()) => eprintln!("agent686: removed {target}"), | ||
| 494 | Err(error) => eprintln!("agent686: {target}: {error}"), | ||
| 495 | } | ||
| 496 | } | ||
| 497 | |||
| 498 | fn remove_all_except(dir: &std::path::Path, keep: &str) -> usize { | ||
| 499 | let mut removed = 0; | ||
| 500 | let Ok(entries) = std::fs::read_dir(dir) else { | ||
| 501 | return 0; | ||
| 502 | }; | ||
| 503 | for entry in entries.flatten() { | ||
| 504 | let path = entry.path(); | ||
| 505 | if path.extension().and_then(|e| e.to_str()) != Some("jsonl") { | ||
| 506 | continue; | ||
| 507 | } | ||
| 508 | if path.file_stem().and_then(|s| s.to_str()) == Some(keep) { | ||
| 509 | continue; | ||
| 510 | } | ||
| 511 | if std::fs::remove_file(&path).is_ok() { | ||
| 512 | removed += 1; | ||
| 513 | } | ||
| 514 | } | ||
| 515 | removed | ||
| 516 | } | ||
| 517 | |||
| 424 | fn warn_if_moved(session: &Session) { | 518 | fn warn_if_moved(session: &Session) { |
| 425 | if session.cwd.is_empty() { | 519 | if session.cwd.is_empty() { |
| 426 | return; | 520 | return; |
| @@ -456,7 +550,7 @@ fn warn_if_changed(watched: &Option<(PathBuf, SystemTime)>, warned: &mut bool) { | |||
| 456 | } | 550 | } |
| 457 | } | 551 | } |
| 458 | 552 | ||
| 459 | fn print_sessions() { | 553 | fn print_sessions(json: bool) { |
| 460 | let sessions = match session::list() { | 554 | let sessions = match session::list() { |
| 461 | Ok(sessions) => sessions, | 555 | Ok(sessions) => sessions, |
| 462 | Err(error) => { | 556 | Err(error) => { |
| @@ -464,6 +558,23 @@ fn print_sessions() { | |||
| 464 | return; | 558 | return; |
| 465 | } | 559 | } |
| 466 | }; | 560 | }; |
| 561 | if json { | ||
| 562 | let rows: Vec<Value> = sessions | ||
| 563 | .iter() | ||
| 564 | .map(|info| { | ||
| 565 | json!({ | ||
| 566 | "id": info.id, | ||
| 567 | "model": info.model, | ||
| 568 | "messages": info.messages, | ||
| 569 | "modified_ms": info.modified.duration_since(UNIX_EPOCH) | ||
| 570 | .map(|d| d.as_millis() as u64).unwrap_or(0), | ||
| 571 | "path": info.path.display().to_string(), | ||
| 572 | }) | ||
| 573 | }) | ||
| 574 | .collect(); | ||
| 575 | println!("{}", serde_json::to_string(&rows).unwrap_or_else(|_| "[]".into())); | ||
| 576 | return; | ||
| 577 | } | ||
| 467 | if sessions.is_empty() { | 578 | if sessions.is_empty() { |
| 468 | println!("no sessions"); | 579 | println!("no sessions"); |
| 469 | return; | 580 | return; |
| @@ -496,29 +607,49 @@ fn ago(modified: SystemTime) -> String { | |||
| 496 | } | 607 | } |
| 497 | } | 608 | } |
| 498 | 609 | ||
| 499 | /// `--yolo` with no approval at all in `$HOME` or `/` is how a transcript ends up | 610 | /// `--yolo` with no approval and no undo is how a transcript ends up deleting a |
| 500 | /// overwriting `.bashrc` or deleting a checkout. Refuse it unless asked twice. | 611 | /// checkout. Git is the documented undo, so `--yolo` needs a repository unless |
| 501 | fn refuse_yolo_at_home(cfg: &Config) { | 612 | /// asked twice. `$HOME` and `/` are refused outright. |
| 613 | fn refuse_yolo(cfg: &Config) { | ||
| 502 | if !cfg.yolo { | 614 | if !cfg.yolo { |
| 503 | return; | 615 | return; |
| 504 | } | 616 | } |
| 505 | if std::env::var_os("AGENT686_ALLOW_HOME").is_some() { | ||
| 506 | return; | ||
| 507 | } | ||
| 508 | let Ok(cwd) = std::env::current_dir() else { | 617 | let Ok(cwd) = std::env::current_dir() else { |
| 509 | return; | 618 | return; |
| 510 | }; | 619 | }; |
| 620 | |||
| 511 | let home = std::env::var_os("HOME").map(PathBuf::from); | 621 | let home = std::env::var_os("HOME").map(PathBuf::from); |
| 512 | let at_home = home.as_deref() == Some(cwd.as_path()); | 622 | let at_home = home.as_deref() == Some(cwd.as_path()); |
| 513 | let at_root = cwd.parent().is_none(); | 623 | let at_root = cwd.parent().is_none(); |
| 514 | if at_home || at_root { | 624 | if (at_home || at_root) && std::env::var_os("AGENT686_ALLOW_HOME").is_none() { |
| 515 | eprintln!( | 625 | eprintln!( |
| 516 | "agent686: refusing --yolo in {} — the model can overwrite anything here. \ | 626 | "agent686: refusing --yolo in {} — the model can overwrite anything here. \ |
| 517 | Run inside a project directory, or set AGENT686_ALLOW_HOME=1.", | 627 | Run inside a project, or set AGENT686_ALLOW_HOME=1.", |
| 518 | cwd.display() | 628 | cwd.display() |
| 519 | ); | 629 | ); |
| 520 | std::process::exit(2); | 630 | std::process::exit(2); |
| 521 | } | 631 | } |
| 632 | |||
| 633 | if !in_git_repo(&cwd) && std::env::var_os("AGENT686_ALLOW_NOGIT").is_none() { | ||
| 634 | eprintln!( | ||
| 635 | "agent686: refusing --yolo outside a git repository ({} has no .git), so \ | ||
| 636 | there is no undo. Run git init, or set AGENT686_ALLOW_NOGIT=1.", | ||
| 637 | cwd.display() | ||
| 638 | ); | ||
| 639 | std::process::exit(2); | ||
| 640 | } | ||
| 641 | } | ||
| 642 | |||
| 643 | fn in_git_repo(dir: &std::path::Path) -> bool { | ||
| 644 | let mut current = dir.to_path_buf(); | ||
| 645 | loop { | ||
| 646 | if current.join(".git").exists() { | ||
| 647 | return true; | ||
| 648 | } | ||
| 649 | if !current.pop() { | ||
| 650 | return false; | ||
| 651 | } | ||
| 652 | } | ||
| 522 | } | 653 | } |
| 523 | 654 | ||
| 524 | fn style(code: &str, text: &str, color: bool) -> String { | 655 | fn style(code: &str, text: &str, color: bool) -> String { |
| @@ -548,7 +679,7 @@ fn truncate_line(line: &str, max: usize) -> String { | |||
| 548 | 679 | ||
| 549 | /// Renders a transcript: what was said, what was asked, what came back. Reads | 680 | /// Renders a transcript: what was said, what was asked, what came back. Reads |
| 550 | /// the file without locking so it works while a session is open elsewhere. | 681 | /// the file without locking so it works while a session is open elsewhere. |
| 551 | fn show_session(id: Option<String>) { | 682 | fn show_session(id: Option<String>, json: bool) { |
| 552 | let id = match id.or_else(|| session::latest().ok().flatten()) { | 683 | let id = match id.or_else(|| session::latest().ok().flatten()) { |
| 553 | Some(id) => id, | 684 | Some(id) => id, |
| 554 | None => { | 685 | None => { |
| @@ -571,8 +702,9 @@ fn show_session(id: Option<String>) { | |||
| 571 | 702 | ||
| 572 | let mut model = String::from("?"); | 703 | let mut model = String::from("?"); |
| 573 | let mut cwd = String::new(); | 704 | let mut cwd = String::new(); |
| 574 | let mut messages = 0usize; | 705 | let mut count = 0usize; |
| 575 | let mut rendered = Vec::new(); | 706 | let mut rendered = Vec::new(); |
| 707 | let mut messages_json: Vec<Value> = Vec::new(); | ||
| 576 | 708 | ||
| 577 | for line in text.lines() { | 709 | for line in text.lines() { |
| 578 | let value: Value = match serde_json::from_str(line) { | 710 | let value: Value = match serde_json::from_str(line) { |
| @@ -598,18 +730,34 @@ fn show_session(id: Option<String>) { | |||
| 598 | } | 730 | } |
| 599 | } | 731 | } |
| 600 | Some("msg") => { | 732 | Some("msg") => { |
| 601 | messages += 1; | 733 | count += 1; |
| 734 | let mut message = value.clone(); | ||
| 735 | if let Some(object) = message.as_object_mut() { | ||
| 736 | object.remove("t"); | ||
| 737 | } | ||
| 738 | messages_json.push(message.clone()); | ||
| 602 | rendered.push(render_message(&value, color)); | 739 | rendered.push(render_message(&value, color)); |
| 603 | } | 740 | } |
| 604 | _ => {} | 741 | _ => {} |
| 605 | } | 742 | } |
| 606 | } | 743 | } |
| 607 | 744 | ||
| 745 | if json { | ||
| 746 | let doc = json!({ | ||
| 747 | "id": id, | ||
| 748 | "model": model, | ||
| 749 | "cwd": cwd, | ||
| 750 | "messages": messages_json, | ||
| 751 | }); | ||
| 752 | println!("{}", serde_json::to_string(&doc).unwrap_or_default()); | ||
| 753 | return; | ||
| 754 | } | ||
| 755 | |||
| 608 | println!( | 756 | println!( |
| 609 | "{}", | 757 | "{}", |
| 610 | style( | 758 | style( |
| 611 | "1", | 759 | "1", |
| 612 | &format!("session {id} · {model} · {messages} messages"), | 760 | &format!("session {id} · {model} · {count} messages"), |
| 613 | color | 761 | color |
| 614 | ) | 762 | ) |
| 615 | ); | 763 | ); |
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() { | |||
| 103 | .env("HOME", &home) | 103 | .env("HOME", &home) |
| 104 | .env("OPENCODE_API_KEY", "test") | 104 | .env("OPENCODE_API_KEY", "test") |
| 105 | .env("AGENT686_ALLOW_HOME", "1") | 105 | .env("AGENT686_ALLOW_HOME", "1") |
| 106 | .env("AGENT686_ALLOW_NOGIT", "1") | ||
| 106 | .args(["--yolo", "--session", "forced"]) | 107 | .args(["--yolo", "--session", "forced"]) |
| 107 | .stdin(std::process::Stdio::null()) | 108 | .stdin(std::process::Stdio::null()) |
| 108 | .output() | 109 | .output() |
| @@ -170,3 +171,101 @@ fn a_flag_shaped_value_is_rejected_unless_attached() { | |||
| 170 | .join(".local/share/agent686/sessions/-abc.jsonl") | 171 | .join(".local/share/agent686/sessions/-abc.jsonl") |
| 171 | .exists()); | 172 | .exists()); |
| 172 | } | 173 | } |
| 174 | |||
| 175 | #[test] | ||
| 176 | fn yolo_is_refused_outside_a_git_repo() { | ||
| 177 | let home = temp_home("nogit"); | ||
| 178 | let dir = home.join("proj"); | ||
| 179 | fs::create_dir_all(&dir).unwrap(); | ||
| 180 | |||
| 181 | let output = agent() | ||
| 182 | .current_dir(&dir) | ||
| 183 | .env("HOME", &home) | ||
| 184 | .env("OPENCODE_API_KEY", "test") | ||
| 185 | .arg("--yolo") | ||
| 186 | .stdin(std::process::Stdio::null()) | ||
| 187 | .output() | ||
| 188 | .unwrap(); | ||
| 189 | assert_eq!(output.status.code(), Some(2), "{output:?}"); | ||
| 190 | assert!( | ||
| 191 | String::from_utf8_lossy(&output.stderr).contains("git repository"), | ||
| 192 | "{:?}", | ||
| 193 | String::from_utf8_lossy(&output.stderr) | ||
| 194 | ); | ||
| 195 | |||
| 196 | let output = agent() | ||
| 197 | .current_dir(&dir) | ||
| 198 | .env("HOME", &home) | ||
| 199 | .env("OPENCODE_API_KEY", "test") | ||
| 200 | .env("AGENT686_ALLOW_NOGIT", "1") | ||
| 201 | .args(["--yolo", "--session", "ok"]) | ||
| 202 | .stdin(std::process::Stdio::null()) | ||
| 203 | .output() | ||
| 204 | .unwrap(); | ||
| 205 | assert_eq!(output.status.code(), Some(0), "{output:?}"); | ||
| 206 | } | ||
| 207 | |||
| 208 | #[test] | ||
| 209 | fn yolo_is_allowed_inside_a_git_repo() { | ||
| 210 | let home = temp_home("git-repo"); | ||
| 211 | let dir = home.join("repo"); | ||
| 212 | fs::create_dir_all(dir.join(".git")).unwrap(); | ||
| 213 | |||
| 214 | let output = agent() | ||
| 215 | .current_dir(&dir) | ||
| 216 | .env("HOME", &home) | ||
| 217 | .env("OPENCODE_API_KEY", "test") | ||
| 218 | .args(["--yolo", "--session", "inside"]) | ||
| 219 | .stdin(std::process::Stdio::null()) | ||
| 220 | .output() | ||
| 221 | .unwrap(); | ||
| 222 | assert_eq!(output.status.code(), Some(0), "{output:?}"); | ||
| 223 | } | ||
| 224 | |||
| 225 | #[test] | ||
| 226 | fn list_and_show_and_doctor_support_json() { | ||
| 227 | use serde_json::json; | ||
| 228 | |||
| 229 | let home = temp_home("json"); | ||
| 230 | let sessions = home.join(".local/share/agent686/sessions"); | ||
| 231 | fs::create_dir_all(&sessions).unwrap(); | ||
| 232 | let lines = [ | ||
| 233 | json!({"t":"header","session":"demo","model":"m","cwd":"/tmp","version":"0.0.0", | ||
| 234 | "system":{"role":"system","content":"s"}}), | ||
| 235 | json!({"t":"msg","role":"user","content":"hi"}), | ||
| 236 | json!({"t":"msg","role":"assistant","content":"yo","_reasoning":"r"}), | ||
| 237 | ]; | ||
| 238 | let body: String = lines.iter().map(|line| format!("{line}\n")).collect(); | ||
| 239 | fs::write(sessions.join("demo.jsonl"), body).unwrap(); | ||
| 240 | |||
| 241 | let list = agent().env("HOME", &home).args(["--list", "--json"]).output().unwrap(); | ||
| 242 | assert!(list.status.success(), "{list:?}"); | ||
| 243 | let list_json: serde_json::Value = serde_json::from_slice(&list.stdout).unwrap(); | ||
| 244 | assert!(list_json.is_array()); | ||
| 245 | assert_eq!(list_json[0]["id"], "demo"); | ||
| 246 | |||
| 247 | let show = agent() | ||
| 248 | .env("HOME", &home) | ||
| 249 | .args(["--show", "demo", "--json"]) | ||
| 250 | .output() | ||
| 251 | .unwrap(); | ||
| 252 | assert!(show.status.success(), "{show:?}"); | ||
| 253 | let show_json: serde_json::Value = serde_json::from_slice(&show.stdout).unwrap(); | ||
| 254 | assert_eq!(show_json["id"], "demo"); | ||
| 255 | assert_eq!(show_json["messages"].as_array().unwrap().len(), 2); | ||
| 256 | assert_eq!(show_json["messages"][1]["_reasoning"], "r"); | ||
| 257 | |||
| 258 | let doctor = agent() | ||
| 259 | .env("HOME", &home) | ||
| 260 | .env_remove("OPENCODE_API_KEY") | ||
| 261 | .args(["--doctor", "--json"]) | ||
| 262 | .output() | ||
| 263 | .unwrap(); | ||
| 264 | assert_eq!(doctor.status.code(), Some(1), "{doctor:?}"); | ||
| 265 | let doctor_json: serde_json::Value = serde_json::from_slice(&doctor.stdout).unwrap(); | ||
| 266 | assert_eq!(doctor_json["ok"], false); | ||
| 267 | assert!(doctor_json["checks"]["key"]["detail"] | ||
| 268 | .as_str() | ||
| 269 | .unwrap() | ||
| 270 | .contains("missing")); | ||
| 271 | } | ||
