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 /src/main.rs | |
| 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 'src/main.rs')
| -rw-r--r-- | src/main.rs | 182 |
1 files changed, 165 insertions, 17 deletions
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 | ); |
