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/agent.rs | 46 ++++++++++++--- src/main.rs | 177 ++++++++++++++++++++++++++++++++++++++++++++------------- src/session.rs | 12 ++++ src/ui.rs | 18 +++++- 4 files changed, 204 insertions(+), 49 deletions(-) (limited to 'src') diff --git a/src/agent.rs b/src/agent.rs index 77807ae..a8ad717 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -14,6 +14,12 @@ use crate::ui::{self, Approver, Renderer}; /// Frozen for the life of the session. Anything session-varying added here /// invalidates the provider's prompt cache, so keep it boring. pub fn system_prompt() -> Value { + let cwd = std::env::current_dir().unwrap_or_default(); + system_prompt_for(&cwd) +} + +pub fn system_prompt_for(cwd_path: &std::path::Path) -> Value { + let cwd = cwd_path.display().to_string(); let mut text = String::from( "You are agent686, a coding agent in a Unix terminal.\n\n\ Tools: read, write, edit, bash, grep, glob. Paths are relative to the working \ @@ -27,9 +33,6 @@ pub fn system_prompt() -> Value { - Do not explain what you are about to do. Act, then report briefly.\n\n", ); - let cwd = std::env::current_dir() - .map(|p| p.display().to_string()) - .unwrap_or_default(); text.push_str(&format!( "Environment: cwd={cwd} · {} · {}", std::env::consts::OS, @@ -40,7 +43,7 @@ pub fn system_prompt() -> Value { } text.push('\n'); - if let Some((path, content)) = project_instructions() { + if let Some((path, content)) = project_instructions(cwd_path) { if !content.trim().is_empty() { text.push_str(&format!( "\n\n{}\n\n", @@ -54,18 +57,43 @@ pub fn system_prompt() -> Value { } pub fn agents_md() -> Option<(PathBuf, SystemTime)> { - let path = project_instructions().map(|(path, _)| path)?; + let cwd = std::env::current_dir().ok()?; + let path = project_instructions(&cwd).map(|(path, _)| path)?; let modified = std::fs::metadata(&path).ok()?.modified().ok()?; Some((path, modified)) } -fn project_instructions() -> Option<(PathBuf, String)> { - let mut dir = std::env::current_dir().ok()?; +/// Instructions from the project only: stop at the git root, and do not walk +/// above it. A stray `AGENTS.md` in a shared parent is an instruction-injection +/// surface, not a convenience. +fn project_instructions(start: &std::path::Path) -> Option<(PathBuf, String)> { + let root = git_root(start); + let mut dir = start.to_path_buf(); loop { let candidate = dir.join("AGENTS.md"); if candidate.is_file() { - let content = std::fs::read_to_string(&candidate).ok()?; - return Some((candidate, content)); + if let Ok(content) = std::fs::read_to_string(&candidate) { + return Some((candidate, content)); + } + // Unreadable or not UTF-8: keep looking upwards, do not give up. + } + // Outside a repository, only the working directory itself counts: + // walking up would pick files from unrelated parents. + let stop = match &root { + Some(root) => dir == *root, + None => true, + }; + if stop || !dir.pop() { + return None; + } + } +} + +fn git_root(start: &std::path::Path) -> Option { + let mut dir = start.to_path_buf(); + loop { + if dir.join(".git").exists() { + return Some(dir); } if !dir.pop() { return None; 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}", diff --git a/src/session.rs b/src/session.rs index f27a188..6e3c1c1 100644 --- a/src/session.rs +++ b/src/session.rs @@ -51,6 +51,8 @@ fn restrict(path: &Path, mode: u32) { pub struct Session { pub id: String, pub model: String, + /// Directory the session was started in; the system prompt is frozen with it. + pub cwd: String, path: PathBuf, file: File, } @@ -83,10 +85,14 @@ impl Session { .map_err(|e| format!("{}: {e}", path.display()))?; restrict(&path, 0o600); + let cwd = std::env::current_dir() + .map(|path| path.display().to_string()) + .unwrap_or_default(); let header = json!({ "t": "header", "session": id, "model": model, + "cwd": cwd, "created": now_ms(), "system": system, }); @@ -96,6 +102,7 @@ impl Session { Ok(Session { id, model: model.to_string(), + cwd, path, file, }) @@ -111,6 +118,7 @@ impl Session { let mut model = String::new(); let mut system = Value::Null; let mut session_id = id.to_string(); + let mut cwd = String::new(); let mut messages = Vec::new(); for line in reader.lines() { @@ -134,6 +142,9 @@ impl Session { if let Some(s) = value.get("session").and_then(|s| s.as_str()) { session_id = s.to_string(); } + if let Some(c) = value.get("cwd").and_then(|c| c.as_str()) { + cwd = c.to_string(); + } } Some("msg") => { let mut message = value.clone(); @@ -158,6 +169,7 @@ impl Session { Session { id: session_id, model, + cwd, path, file, }, diff --git a/src/ui.rs b/src/ui.rs index 38546ab..d7716a9 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -14,7 +14,13 @@ pub fn stdin_is_tty() -> bool { fn color() -> bool { static COLOR: OnceLock = OnceLock::new(); - *COLOR.get_or_init(stdout_is_tty) + *COLOR.get_or_init(|| { + stdout_is_tty() + && std::env::var_os("NO_COLOR").is_none() + && std::env::var("TERM") + .map(|term| term != "dumb") + .unwrap_or(true) + }) } fn paint(code: &str, text: &str) -> String { @@ -177,10 +183,20 @@ impl Approver { print!("\n{} {} ", question, paint("2", hint)); let _ = std::io::stdout().flush(); + // Typeahead from before the prompt appeared must not answer it: a "y" + // typed during streaming would otherwise approve a command unseen. + unsafe { + libc::tcflush(libc::STDIN_FILENO, libc::TCIFLUSH); + } + let mut line = String::new(); if std::io::stdin().read_line(&mut line).unwrap_or(0) == 0 { return Answer::No; } + // Ctrl-C during the prompt arrives as a signal, not a keystroke. + if crate::signal::CANCEL.load(std::sync::atomic::Ordering::Relaxed) { + return Answer::No; + } match line.trim().to_ascii_lowercase().as_str() { "y" | "yes" => Answer::Yes, "a" | "always" if allow_always => Answer::Always, -- cgit v1.2.3