From 3b1351018d3184caa5b5ca25cc13e5da1fc02229 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 15:41:46 +0100 Subject: 0.4.5: CLI validation, instruction scope, resume context, prompt hygiene - session ids validated; missing flag values and conflicting flags are usage errors - -- terminator; usage goes to stderr - doctor sends a real session header - sessions record their starting cwd and warn when resumed elsewhere - AGENTS.md stops at the git root; no parent-directory injection - typeahead flush, Ctrl-C during prompts, NO_COLOR/TERM=dumb --- src/main.rs | 177 ++++++++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 138 insertions(+), 39 deletions(-) (limited to 'src/main.rs') diff --git a/src/main.rs b/src/main.rs index 9a5012f..117973b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,21 +8,22 @@ use agent686::config::Config; use agent686::line::Editor; use agent686::session::{self, Session}; use agent686::ui::Approver; -use agent686::{agent, signal}; +use agent686::{agent, doctor, signal}; const HELP: &str = "\ agent686 — a small coding agent USAGE: - agent686 [OPTIONS] [PROMPT...] + agent686 [OPTIONS] [--] [PROMPT...] With a prompt it runs one turn and exits. Without one it reads prompts from stdin. In a terminal: up/down for history, ctrl-a/e/u/w/k to edit, ctrl-d to -exit, ctrl-c to abandon the line. Commands: /paste, /exit, /help. +exit, ctrl-c to abandon the line. -/cmd +COMMANDS (at the prompt): /paste read a block of lines until a lone `.` /exit quit + /help this text OPTIONS: -m, --model model id (default: deepseek-v4.1-flash) @@ -31,67 +32,142 @@ OPTIONS: -c, --continue resume the most recent session --list list sessions and exit --doctor check key, directories, provider and model, then exit - -V, --version print the version and exit --yolo approve every tool call without asking + -V, --version print the version and exit -h, --help this text +EXIT CODES: + 0 success · 1 error · 2 usage · 3 a tool call was denied · 130 aborted + ENVIRONMENT: OPENCODE_API_KEY credential (falls back to ~/.config/agent686/key) AGENT686_MODEL default model id AGENT686_BASE_URL default provider base URL AGENT686_DATA where sessions live (default ~/.local/share/agent686) + NO_COLOR disable colour "; +struct Args { + prompt: Option, + model: Option, + base_url: Option, + session: Option, + continue_last: bool, + list: bool, + doctor: bool, + yolo: bool, +} + fn main() { - let mut prompt_words: Vec = Vec::new(); - let mut model = None; - let mut base_url = None; - let mut resume = None; - let mut continue_last = false; - let mut list = false; - let mut doctor = false; - let mut yolo = false; - - let mut args = std::env::args().skip(1); - while let Some(arg) = args.next() { + let args = match parse_args() { + Ok(args) => args, + Err(message) => { + eprintln!("agent686: {message}"); + std::process::exit(2); + } + }; + run(args); +} + +fn parse_args() -> Result { + let mut args = Args { + prompt: None, + model: None, + base_url: None, + session: None, + continue_last: false, + list: false, + doctor: false, + yolo: false, + }; + let mut words: Vec = Vec::new(); + let mut iter = std::env::args().skip(1); + let mut literal = false; + + while let Some(arg) = iter.next() { + if literal { + words.push(arg); + continue; + } match arg.as_str() { - "-m" | "--model" => model = args.next(), - "--base-url" => base_url = args.next(), - "--session" | "--resume" => resume = args.next(), - "-c" | "--continue" => continue_last = true, - "--list" => list = true, - "--doctor" => doctor = true, + "--" => literal = true, + "-m" | "--model" => args.model = Some(take_value(&mut iter, "--model")?), + "--base-url" => args.base_url = Some(take_value(&mut iter, "--base-url")?), + "--session" | "--resume" => { + args.session = Some(take_value(&mut iter, "--session")?) + } + "-c" | "--continue" => args.continue_last = true, + "--list" => args.list = true, + "--doctor" => args.doctor = true, + "--yolo" => args.yolo = true, "-V" | "--version" => { println!("agent686 {}", env!("CARGO_PKG_VERSION")); - return; + std::process::exit(0); } - "--yolo" => yolo = true, "-h" | "--help" => { print!("{HELP}"); - return; + std::process::exit(0); } flag if flag.starts_with('-') && flag.len() > 1 => { - eprintln!("agent686: unknown flag {flag}\n"); - print!("{HELP}"); - std::process::exit(2); + return Err(format!("unknown flag {flag}\n\n{HELP}")) } - word => prompt_words.push(word.to_string()), + word => words.push(word.to_string()), } } + if !words.is_empty() { + args.prompt = Some(words.join(" ")); + } + if args.continue_last && args.session.is_some() { + return Err("--continue and --session cannot be combined".into()); + } + if args.list && args.doctor { + return Err("--list and --doctor cannot be combined".into()); + } + if let Some(id) = &args.session { + validate_session_id(id)?; + } + Ok(args) +} + +fn take_value(iter: &mut impl Iterator, flag: &str) -> Result { + match iter.next() { + Some(value) if !value.trim().is_empty() => Ok(value), + _ => Err(format!("{flag} needs a value")), + } +} + +fn validate_session_id(id: &str) -> Result<(), String> { + let valid = !id.is_empty() + && id.len() <= 64 + && id + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')); + if valid { + Ok(()) + } else { + Err(format!( + "invalid session id `{id}`: use 1-64 characters of A-Z a-z 0-9 . _ -" + )) + } +} + +fn run(args: Args) { signal::install(); - if list { + if args.list { print_sessions(); return; } - if doctor { - let config = Config::resolve_lenient(model, base_url, yolo); - std::process::exit(agent686::doctor::run(&config)); + if args.doctor { + 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)); } - let mut cfg = match Config::resolve(model, base_url, yolo) { + let mut cfg = match Config::resolve(args.model, args.base_url, args.yolo) { Ok(cfg) => cfg, Err(message) => { eprintln!("agent686: {message}"); @@ -99,7 +175,7 @@ fn main() { } }; - let (mut session, mut history) = match open_session(&cfg, resume, continue_last) { + let (mut session, mut history) = match open_session(&cfg, args.session, args.continue_last) { Ok(pair) => pair, Err(message) => { eprintln!("agent686: {message}"); @@ -108,12 +184,13 @@ fn main() { }; cfg.session = session.id.clone(); + warn_if_moved(&session); + let mut approver = Approver::new(cfg.yolo); let watched = agent::agents_md(); let mut warned = false; - if !prompt_words.is_empty() { - let prompt = prompt_words.join(" "); + if let Some(prompt) = args.prompt { match agent::run_turn( &cfg, &mut session, @@ -246,7 +323,8 @@ fn open_session( let (session, system, messages) = Session::open(&id)?; if !session.model.is_empty() && session.model != cfg.model { eprintln!( - "agent686: session used {}; continuing with {}", + "agent686: session used {}; continuing with {} (this invalidates the \ + provider's prompt cache for the whole history)", session.model, cfg.model ); } @@ -276,6 +354,24 @@ 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 warn_if_moved(session: &Session) { + if session.cwd.is_empty() { + return; + } + if let Ok(now) = std::env::current_dir() { + let now = now.display().to_string(); + if now != session.cwd { + eprintln!( + "agent686: this session started in {}, but you are in {now}; tools use the \ + current directory, and the prompt still describes the old one", + session.cwd + ); + } + } +} + fn warn_if_changed(watched: &Option<(PathBuf, SystemTime)>, warned: &mut bool) { let (path, seen) = match watched { Some(watched) => watched, @@ -307,7 +403,10 @@ fn print_sessions() { println!("no sessions"); return; } - println!("{:<34} {:<22} {:>5} {:>4}", "SESSION", "MODEL", "MSGS", "AGE"); + println!( + "{:<34} {:<22} {:>5} {:>4}", + "SESSION", "MODEL", "MSGS", "AGE" + ); for info in sessions { println!( "{:<34} {:<22} {:>5} {:>4}", -- cgit v1.2.3