use std::io::{BufRead, Write}; use std::path::PathBuf; use std::time::SystemTime; use serde_json::Value; use agent686::config::Config; use agent686::line::Editor; use agent686::session::{self, Session}; use agent686::ui::Approver; use agent686::{agent, doctor, signal}; const HELP: &str = "\ agent686 — a small coding agent USAGE: 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 (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) --base-url provider base URL --session resume a session, creating it if the id is new -c, --continue resume the most recent session --list list sessions and exit --doctor check key, directories, provider and model, then 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 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() { "--" => 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")); std::process::exit(0); } "-h" | "--help" => { print!("{HELP}"); std::process::exit(0); } flag if flag.starts_with('-') && flag.len() > 1 => { return Err(format!("unknown flag {flag}\n\n{HELP}")) } 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 args.list { print_sessions(); return; } 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(args.model, args.base_url, args.yolo) { Ok(cfg) => cfg, Err(message) => { eprintln!("agent686: {message}"); std::process::exit(2); } }; let (mut session, mut history) = match open_session(&cfg, args.session, args.continue_last) { Ok(pair) => pair, Err(message) => { eprintln!("agent686: {message}"); std::process::exit(1); } }; 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 let Some(prompt) = args.prompt { match agent::run_turn( &cfg, &mut session, &mut history, &prompt, &signal::CANCEL, &mut approver, ) { Ok(report) => { if report.aborted { std::process::exit(130); } if report.denied > 0 { std::process::exit(3); } } Err(error) => { eprintln!("agent686: {error}"); std::process::exit(1); } } return; } let mut editor = Editor::new(); let interactive = editor.is_interactive(); if !interactive && !cfg.yolo { eprintln!( "agent686: stdin is not a terminal, so write/edit/bash will be denied; \ pass --yolo to allow them" ); } if interactive { eprintln!( "agent686 · {} · session {}{}", cfg.model, cfg.session, if cfg.yolo { " · yolo" } else { "" } ); eprintln!("type a prompt · up/down history · ctrl-d exit · /help"); } let stdin = std::io::stdin(); let mut line = String::new(); loop { let mut text = match editor.read("> ") { Ok(Some(text)) => text, Ok(None) => break, Err(error) => { eprintln!("agent686: input: {error}"); break; } }; if text.trim().is_empty() { continue; } match text.as_str() { "/exit" | "/quit" => break, "/help" => { print!("{HELP}"); continue; } "/paste" => { let mut buffer = String::new(); loop { if interactive { print!("… "); let _ = std::io::stdout().flush(); } line.clear(); if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 { break; } let piece = line.trim_end_matches(['\n', '\r']); if piece == "." { break; } buffer.push_str(piece); buffer.push('\n'); } text = buffer.trim_end().to_string(); if text.is_empty() { continue; } } _ => {} } warn_if_changed(&watched, &mut warned); if let Err(error) = agent::run_turn( &cfg, &mut session, &mut history, &text, &signal::CANCEL, &mut approver, ) { eprintln!("agent686: {error}"); } } } fn open_session( cfg: &Config, resume: Option, continue_last: bool, ) -> Result<(Session, Vec), String> { let id = match resume { Some(id) => Some(id), None if continue_last => Some( session::latest()? .ok_or_else(|| "no sessions to continue; run without --continue".to_string())?, ), None => None, }; match id { Some(id) if !session::exists(&id) => { let system = agent::system_prompt(); let session = Session::create_as(id, &cfg.model, &system)?; eprintln!( "agent686: new session {} ({})", session.id, session.path().display() ); Ok((session, agent::new_history(system))) } Some(id) => { let (session, system, messages) = Session::open(&id)?; if !session.model.is_empty() && session.model != cfg.model { eprintln!( "agent686: session used {}; continuing with {} (this invalidates the \ provider's prompt cache for the whole history)", session.model, cfg.model ); } // The system message frozen at session start is reused verbatim, so // the request prefix stays byte-identical across restarts. let system = if system.is_null() { agent::system_prompt() } else { system }; let mut history = agent::new_history(system); let count = messages.len(); history.extend(messages); eprintln!("agent686: resumed {} ({count} messages)", session.id); Ok((session, history)) } None => { let system = agent::system_prompt(); let session = Session::create(&cfg.model, &system)?; eprintln!( "agent686: new session {} ({})", session.id, session.path().display() ); Ok((session, agent::new_history(system))) } } } /// 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, None => return, }; if *warned { return; } if let Ok(modified) = std::fs::metadata(path).and_then(|m| m.modified()) { if modified != *seen { eprintln!( "agent686: {} changed; start a new session to pick it up", path.display() ); *warned = true; } } } fn print_sessions() { let sessions = match session::list() { Ok(sessions) => sessions, Err(error) => { eprintln!("agent686: {error}"); return; } }; if sessions.is_empty() { println!("no sessions"); return; } println!( "{:<34} {:<22} {:>5} {:>4}", "SESSION", "MODEL", "MSGS", "AGE" ); for info in sessions { println!( "{:<34} {:<22} {:>5} {:>4}", info.id, info.model, info.messages, ago(info.modified) ); } } fn ago(modified: SystemTime) -> String { let seconds = SystemTime::now() .duration_since(modified) .map(|d| d.as_secs()) .unwrap_or(0); match seconds { 0..=59 => format!("{seconds}s"), 60..=3599 => format!("{}m", seconds / 60), 3600..=86_399 => format!("{}h", seconds / 3600), _ => format!("{}d", seconds / 86_400), } }