diff options
| author | salmonik <salmonik@tuta.io> | 2026-11-15 15:41:46 +0100 |
|---|---|---|
| committer | salmonik <salmonik@tuta.io> | 2026-11-15 15:41:46 +0100 |
| commit | 3b1351018d3184caa5b5ca25cc13e5da1fc02229 (patch) | |
| tree | 99bdc95ba444a5c4d2d3f09c4e5c04ff16108f8f | |
| parent | 0.4.4: file-tool correctness (diff) | |
| download | agent686-3b1351018d3184caa5b5ca25cc13e5da1fc02229.tar.gz agent686-3b1351018d3184caa5b5ca25cc13e5da1fc02229.zip | |
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
| -rw-r--r-- | CHANGELOG.md | 23 | ||||
| -rw-r--r-- | Cargo.lock | 2 | ||||
| -rw-r--r-- | Cargo.toml | 2 | ||||
| -rw-r--r-- | src/agent.rs | 46 | ||||
| -rw-r--r-- | src/main.rs | 177 | ||||
| -rw-r--r-- | src/session.rs | 12 | ||||
| -rw-r--r-- | src/ui.rs | 18 | ||||
| -rw-r--r-- | tests/cli.rs | 78 | ||||
| -rw-r--r-- | tests/doctor.rs | 26 | ||||
| -rw-r--r-- | tests/prompt.rs | 41 |
10 files changed, 369 insertions, 56 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index 213f5f1..9c00ccb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md | |||
| @@ -7,6 +7,29 @@ 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.4.5 | ||
| 11 | |||
| 12 | ### Fixed | ||
| 13 | - `--session ../escape` wrote outside the sessions directory; ids are now | ||
| 14 | validated as 1-64 characters of `A-Za-z0-9._-`. | ||
| 15 | - A flag with no value was silently ignored, and `--session` with an empty value | ||
| 16 | quietly created a new session. Both are usage errors (exit 2) now. | ||
| 17 | - `--` ends option parsing, so a prompt can start with `-`. | ||
| 18 | - `--continue` with `--session`, and `--list` with `--doctor`, are rejected | ||
| 19 | instead of one silently winning. | ||
| 20 | - Unknown-flag output went to stdout; usage now goes to stderr. | ||
| 21 | - `--doctor` sent an empty `x-opencode-session`, which the gateway rejects, so a | ||
| 22 | healthy key could look broken. It now sends a throwaway id. | ||
| 23 | - Resuming a session from a different directory gave the model the old `cwd` and | ||
| 24 | branch without saying so; the session records its starting directory and now | ||
| 25 | warns when it does not match. | ||
| 26 | - `AGENTS.md` was read all the way to `/`, so a stray file in a shared parent | ||
| 27 | would be injected into every project. Reading now stops at the git root, and | ||
| 28 | outside a repository only the working directory itself is read. | ||
| 29 | - Typeahead typed during streaming could answer the following approval prompt. | ||
| 30 | - Colour is now disabled by `NO_COLOR` and `TERM=dumb`. | ||
| 31 | - Ctrl-C during an approval prompt now denies instead of appearing to hang. | ||
| 32 | |||
| 10 | ## 0.4.4 | 33 | ## 0.4.4 |
| 11 | 34 | ||
| 12 | ### Fixed | 35 | ### Fixed |
| @@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" | |||
| 10 | 10 | ||
| 11 | [[package]] | 11 | [[package]] |
| 12 | name = "agent686" | 12 | name = "agent686" |
| 13 | version = "0.4.3" | 13 | version = "0.4.4" |
| 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.4.4" | 3 | version = "0.4.5" |
| 4 | edition = "2021" | 4 | edition = "2021" |
| 5 | description = "A small coding agent for a 32-bit Debian box" | 5 | description = "A small coding agent for a 32-bit Debian box" |
| 6 | publish = false | 6 | publish = false |
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}; | |||
| 14 | /// Frozen for the life of the session. Anything session-varying added here | 14 | /// Frozen for the life of the session. Anything session-varying added here |
| 15 | /// invalidates the provider's prompt cache, so keep it boring. | 15 | /// invalidates the provider's prompt cache, so keep it boring. |
| 16 | pub fn system_prompt() -> Value { | 16 | pub fn system_prompt() -> Value { |
| 17 | let cwd = std::env::current_dir().unwrap_or_default(); | ||
| 18 | system_prompt_for(&cwd) | ||
| 19 | } | ||
| 20 | |||
| 21 | pub fn system_prompt_for(cwd_path: &std::path::Path) -> Value { | ||
| 22 | let cwd = cwd_path.display().to_string(); | ||
| 17 | let mut text = String::from( | 23 | let mut text = String::from( |
| 18 | "You are agent686, a coding agent in a Unix terminal.\n\n\ | 24 | "You are agent686, a coding agent in a Unix terminal.\n\n\ |
| 19 | Tools: read, write, edit, bash, grep, glob. Paths are relative to the working \ | 25 | Tools: read, write, edit, bash, grep, glob. Paths are relative to the working \ |
| @@ -27,9 +33,6 @@ pub fn system_prompt() -> Value { | |||
| 27 | - Do not explain what you are about to do. Act, then report briefly.\n\n", | 33 | - Do not explain what you are about to do. Act, then report briefly.\n\n", |
| 28 | ); | 34 | ); |
| 29 | 35 | ||
| 30 | let cwd = std::env::current_dir() | ||
| 31 | .map(|p| p.display().to_string()) | ||
| 32 | .unwrap_or_default(); | ||
| 33 | text.push_str(&format!( | 36 | text.push_str(&format!( |
| 34 | "Environment: cwd={cwd} · {} · {}", | 37 | "Environment: cwd={cwd} · {} · {}", |
| 35 | std::env::consts::OS, | 38 | std::env::consts::OS, |
| @@ -40,7 +43,7 @@ pub fn system_prompt() -> Value { | |||
| 40 | } | 43 | } |
| 41 | text.push('\n'); | 44 | text.push('\n'); |
| 42 | 45 | ||
| 43 | if let Some((path, content)) = project_instructions() { | 46 | if let Some((path, content)) = project_instructions(cwd_path) { |
| 44 | if !content.trim().is_empty() { | 47 | if !content.trim().is_empty() { |
| 45 | text.push_str(&format!( | 48 | text.push_str(&format!( |
| 46 | "\n<project-instructions source=\"{}\">\n{}\n</project-instructions>\n", | 49 | "\n<project-instructions source=\"{}\">\n{}\n</project-instructions>\n", |
| @@ -54,18 +57,43 @@ pub fn system_prompt() -> Value { | |||
| 54 | } | 57 | } |
| 55 | 58 | ||
| 56 | pub fn agents_md() -> Option<(PathBuf, SystemTime)> { | 59 | pub fn agents_md() -> Option<(PathBuf, SystemTime)> { |
| 57 | let path = project_instructions().map(|(path, _)| path)?; | 60 | let cwd = std::env::current_dir().ok()?; |
| 61 | let path = project_instructions(&cwd).map(|(path, _)| path)?; | ||
| 58 | let modified = std::fs::metadata(&path).ok()?.modified().ok()?; | 62 | let modified = std::fs::metadata(&path).ok()?.modified().ok()?; |
| 59 | Some((path, modified)) | 63 | Some((path, modified)) |
| 60 | } | 64 | } |
| 61 | 65 | ||
| 62 | fn project_instructions() -> Option<(PathBuf, String)> { | 66 | /// Instructions from the project only: stop at the git root, and do not walk |
| 63 | let mut dir = std::env::current_dir().ok()?; | 67 | /// above it. A stray `AGENTS.md` in a shared parent is an instruction-injection |
| 68 | /// surface, not a convenience. | ||
| 69 | fn project_instructions(start: &std::path::Path) -> Option<(PathBuf, String)> { | ||
| 70 | let root = git_root(start); | ||
| 71 | let mut dir = start.to_path_buf(); | ||
| 64 | loop { | 72 | loop { |
| 65 | let candidate = dir.join("AGENTS.md"); | 73 | let candidate = dir.join("AGENTS.md"); |
| 66 | if candidate.is_file() { | 74 | if candidate.is_file() { |
| 67 | let content = std::fs::read_to_string(&candidate).ok()?; | 75 | if let Ok(content) = std::fs::read_to_string(&candidate) { |
| 68 | return Some((candidate, content)); | 76 | return Some((candidate, content)); |
| 77 | } | ||
| 78 | // Unreadable or not UTF-8: keep looking upwards, do not give up. | ||
| 79 | } | ||
| 80 | // Outside a repository, only the working directory itself counts: | ||
| 81 | // walking up would pick files from unrelated parents. | ||
| 82 | let stop = match &root { | ||
| 83 | Some(root) => dir == *root, | ||
| 84 | None => true, | ||
| 85 | }; | ||
| 86 | if stop || !dir.pop() { | ||
| 87 | return None; | ||
| 88 | } | ||
| 89 | } | ||
| 90 | } | ||
| 91 | |||
| 92 | fn git_root(start: &std::path::Path) -> Option<PathBuf> { | ||
| 93 | let mut dir = start.to_path_buf(); | ||
| 94 | loop { | ||
| 95 | if dir.join(".git").exists() { | ||
| 96 | return Some(dir); | ||
| 69 | } | 97 | } |
| 70 | if !dir.pop() { | 98 | if !dir.pop() { |
| 71 | return None; | 99 | 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; | |||
| 8 | use agent686::line::Editor; | 8 | use agent686::line::Editor; |
| 9 | use agent686::session::{self, Session}; | 9 | use agent686::session::{self, Session}; |
| 10 | use agent686::ui::Approver; | 10 | use agent686::ui::Approver; |
| 11 | use agent686::{agent, signal}; | 11 | use agent686::{agent, doctor, signal}; |
| 12 | 12 | ||
| 13 | const HELP: &str = "\ | 13 | const HELP: &str = "\ |
| 14 | agent686 — a small coding agent | 14 | agent686 — a small coding agent |
| 15 | 15 | ||
| 16 | USAGE: | 16 | USAGE: |
| 17 | agent686 [OPTIONS] [PROMPT...] | 17 | agent686 [OPTIONS] [--] [PROMPT...] |
| 18 | 18 | ||
| 19 | With a prompt it runs one turn and exits. Without one it reads prompts from | 19 | With a prompt it runs one turn and exits. Without one it reads prompts from |
| 20 | stdin. In a terminal: up/down for history, ctrl-a/e/u/w/k to edit, ctrl-d to | 20 | stdin. In a terminal: up/down for history, ctrl-a/e/u/w/k to edit, ctrl-d to |
| 21 | exit, ctrl-c to abandon the line. Commands: /paste, /exit, /help. | 21 | exit, ctrl-c to abandon the line. |
| 22 | 22 | ||
| 23 | /cmd | 23 | COMMANDS (at the prompt): |
| 24 | /paste read a block of lines until a lone `.` | 24 | /paste read a block of lines until a lone `.` |
| 25 | /exit quit | 25 | /exit quit |
| 26 | /help this text | ||
| 26 | 27 | ||
| 27 | OPTIONS: | 28 | OPTIONS: |
| 28 | -m, --model <ID> model id (default: deepseek-v4.1-flash) | 29 | -m, --model <ID> model id (default: deepseek-v4.1-flash) |
| @@ -31,67 +32,142 @@ OPTIONS: | |||
| 31 | -c, --continue resume the most recent session | 32 | -c, --continue resume the most recent session |
| 32 | --list list sessions and exit | 33 | --list list sessions and exit |
| 33 | --doctor check key, directories, provider and model, then exit | 34 | --doctor check key, directories, provider and model, then exit |
| 34 | -V, --version print the version and exit | ||
| 35 | --yolo approve every tool call without asking | 35 | --yolo approve every tool call without asking |
| 36 | -V, --version print the version and exit | ||
| 36 | -h, --help this text | 37 | -h, --help this text |
| 37 | 38 | ||
| 39 | EXIT CODES: | ||
| 40 | 0 success · 1 error · 2 usage · 3 a tool call was denied · 130 aborted | ||
| 41 | |||
| 38 | ENVIRONMENT: | 42 | ENVIRONMENT: |
| 39 | OPENCODE_API_KEY credential (falls back to ~/.config/agent686/key) | 43 | OPENCODE_API_KEY credential (falls back to ~/.config/agent686/key) |
| 40 | AGENT686_MODEL default model id | 44 | AGENT686_MODEL default model id |
| 41 | AGENT686_BASE_URL default provider base URL | 45 | AGENT686_BASE_URL default provider base URL |
| 42 | AGENT686_DATA where sessions live (default ~/.local/share/agent686) | 46 | AGENT686_DATA where sessions live (default ~/.local/share/agent686) |
| 47 | NO_COLOR disable colour | ||
| 43 | "; | 48 | "; |
| 44 | 49 | ||
| 50 | struct Args { | ||
| 51 | prompt: Option<String>, | ||
| 52 | model: Option<String>, | ||
| 53 | base_url: Option<String>, | ||
| 54 | session: Option<String>, | ||
| 55 | continue_last: bool, | ||
| 56 | list: bool, | ||
| 57 | doctor: bool, | ||
| 58 | yolo: bool, | ||
| 59 | } | ||
| 60 | |||
| 45 | fn main() { | 61 | fn main() { |
| 46 | let mut prompt_words: Vec<String> = Vec::new(); | 62 | let args = match parse_args() { |
| 47 | let mut model = None; | 63 | Ok(args) => args, |
| 48 | let mut base_url = None; | 64 | Err(message) => { |
| 49 | let mut resume = None; | 65 | eprintln!("agent686: {message}"); |
| 50 | let mut continue_last = false; | 66 | std::process::exit(2); |
| 51 | let mut list = false; | 67 | } |
| 52 | let mut doctor = false; | 68 | }; |
| 53 | let mut yolo = false; | 69 | run(args); |
| 54 | 70 | } | |
| 55 | let mut args = std::env::args().skip(1); | 71 | |
| 56 | while let Some(arg) = args.next() { | 72 | fn parse_args() -> Result<Args, String> { |
| 73 | let mut args = Args { | ||
| 74 | prompt: None, | ||
| 75 | model: None, | ||
| 76 | base_url: None, | ||
| 77 | session: None, | ||
| 78 | continue_last: false, | ||
| 79 | list: false, | ||
| 80 | doctor: false, | ||
| 81 | yolo: false, | ||
| 82 | }; | ||
| 83 | let mut words: Vec<String> = Vec::new(); | ||
| 84 | let mut iter = std::env::args().skip(1); | ||
| 85 | let mut literal = false; | ||
| 86 | |||
| 87 | while let Some(arg) = iter.next() { | ||
| 88 | if literal { | ||
| 89 | words.push(arg); | ||
| 90 | continue; | ||
| 91 | } | ||
| 57 | match arg.as_str() { | 92 | match arg.as_str() { |
| 58 | "-m" | "--model" => model = args.next(), | 93 | "--" => literal = true, |
| 59 | "--base-url" => base_url = args.next(), | 94 | "-m" | "--model" => args.model = Some(take_value(&mut iter, "--model")?), |
| 60 | "--session" | "--resume" => resume = args.next(), | 95 | "--base-url" => args.base_url = Some(take_value(&mut iter, "--base-url")?), |
| 61 | "-c" | "--continue" => continue_last = true, | 96 | "--session" | "--resume" => { |
| 62 | "--list" => list = true, | 97 | args.session = Some(take_value(&mut iter, "--session")?) |
| 63 | "--doctor" => doctor = true, | 98 | } |
| 99 | "-c" | "--continue" => args.continue_last = true, | ||
| 100 | "--list" => args.list = true, | ||
| 101 | "--doctor" => args.doctor = true, | ||
| 102 | "--yolo" => args.yolo = true, | ||
| 64 | "-V" | "--version" => { | 103 | "-V" | "--version" => { |
| 65 | println!("agent686 {}", env!("CARGO_PKG_VERSION")); | 104 | println!("agent686 {}", env!("CARGO_PKG_VERSION")); |
| 66 | return; | 105 | std::process::exit(0); |
| 67 | } | 106 | } |
| 68 | "--yolo" => yolo = true, | ||
| 69 | "-h" | "--help" => { | 107 | "-h" | "--help" => { |
| 70 | print!("{HELP}"); | 108 | print!("{HELP}"); |
| 71 | return; | 109 | std::process::exit(0); |
| 72 | } | 110 | } |
| 73 | flag if flag.starts_with('-') && flag.len() > 1 => { | 111 | flag if flag.starts_with('-') && flag.len() > 1 => { |
| 74 | eprintln!("agent686: unknown flag {flag}\n"); | 112 | return Err(format!("unknown flag {flag}\n\n{HELP}")) |
| 75 | print!("{HELP}"); | ||
| 76 | std::process::exit(2); | ||
| 77 | } | 113 | } |
| 78 | word => prompt_words.push(word.to_string()), | 114 | word => words.push(word.to_string()), |
| 79 | } | 115 | } |
| 80 | } | 116 | } |
| 81 | 117 | ||
| 118 | if !words.is_empty() { | ||
| 119 | args.prompt = Some(words.join(" ")); | ||
| 120 | } | ||
| 121 | if args.continue_last && args.session.is_some() { | ||
| 122 | return Err("--continue and --session cannot be combined".into()); | ||
| 123 | } | ||
| 124 | if args.list && args.doctor { | ||
| 125 | return Err("--list and --doctor cannot be combined".into()); | ||
| 126 | } | ||
| 127 | if let Some(id) = &args.session { | ||
| 128 | validate_session_id(id)?; | ||
| 129 | } | ||
| 130 | Ok(args) | ||
| 131 | } | ||
| 132 | |||
| 133 | fn take_value(iter: &mut impl Iterator<Item = String>, flag: &str) -> Result<String, String> { | ||
| 134 | match iter.next() { | ||
| 135 | Some(value) if !value.trim().is_empty() => Ok(value), | ||
| 136 | _ => Err(format!("{flag} needs a value")), | ||
| 137 | } | ||
| 138 | } | ||
| 139 | |||
| 140 | fn validate_session_id(id: &str) -> Result<(), String> { | ||
| 141 | let valid = !id.is_empty() | ||
| 142 | && id.len() <= 64 | ||
| 143 | && id | ||
| 144 | .chars() | ||
| 145 | .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')); | ||
| 146 | if valid { | ||
| 147 | Ok(()) | ||
| 148 | } else { | ||
| 149 | Err(format!( | ||
| 150 | "invalid session id `{id}`: use 1-64 characters of A-Z a-z 0-9 . _ -" | ||
| 151 | )) | ||
| 152 | } | ||
| 153 | } | ||
| 154 | |||
| 155 | fn run(args: Args) { | ||
| 82 | signal::install(); | 156 | signal::install(); |
| 83 | 157 | ||
| 84 | if list { | 158 | if args.list { |
| 85 | print_sessions(); | 159 | print_sessions(); |
| 86 | return; | 160 | return; |
| 87 | } | 161 | } |
| 88 | 162 | ||
| 89 | if doctor { | 163 | if args.doctor { |
| 90 | let config = Config::resolve_lenient(model, base_url, yolo); | 164 | let mut config = Config::resolve_lenient(args.model, args.base_url, args.yolo); |
| 91 | std::process::exit(agent686::doctor::run(&config)); | 165 | // `/models` needs the session header too, even though this is not a turn. |
| 166 | config.session = session::new_id(); | ||
| 167 | std::process::exit(doctor::run(&config)); | ||
| 92 | } | 168 | } |
| 93 | 169 | ||
| 94 | let mut cfg = match Config::resolve(model, base_url, yolo) { | 170 | let mut cfg = match Config::resolve(args.model, args.base_url, args.yolo) { |
| 95 | Ok(cfg) => cfg, | 171 | Ok(cfg) => cfg, |
| 96 | Err(message) => { | 172 | Err(message) => { |
| 97 | eprintln!("agent686: {message}"); | 173 | eprintln!("agent686: {message}"); |
| @@ -99,7 +175,7 @@ fn main() { | |||
| 99 | } | 175 | } |
| 100 | }; | 176 | }; |
| 101 | 177 | ||
| 102 | let (mut session, mut history) = match open_session(&cfg, resume, continue_last) { | 178 | let (mut session, mut history) = match open_session(&cfg, args.session, args.continue_last) { |
| 103 | Ok(pair) => pair, | 179 | Ok(pair) => pair, |
| 104 | Err(message) => { | 180 | Err(message) => { |
| 105 | eprintln!("agent686: {message}"); | 181 | eprintln!("agent686: {message}"); |
| @@ -108,12 +184,13 @@ fn main() { | |||
| 108 | }; | 184 | }; |
| 109 | cfg.session = session.id.clone(); | 185 | cfg.session = session.id.clone(); |
| 110 | 186 | ||
| 187 | warn_if_moved(&session); | ||
| 188 | |||
| 111 | let mut approver = Approver::new(cfg.yolo); | 189 | let mut approver = Approver::new(cfg.yolo); |
| 112 | let watched = agent::agents_md(); | 190 | let watched = agent::agents_md(); |
| 113 | let mut warned = false; | 191 | let mut warned = false; |
| 114 | 192 | ||
| 115 | if !prompt_words.is_empty() { | 193 | if let Some(prompt) = args.prompt { |
| 116 | let prompt = prompt_words.join(" "); | ||
| 117 | match agent::run_turn( | 194 | match agent::run_turn( |
| 118 | &cfg, | 195 | &cfg, |
| 119 | &mut session, | 196 | &mut session, |
| @@ -246,7 +323,8 @@ fn open_session( | |||
| 246 | let (session, system, messages) = Session::open(&id)?; | 323 | let (session, system, messages) = Session::open(&id)?; |
| 247 | if !session.model.is_empty() && session.model != cfg.model { | 324 | if !session.model.is_empty() && session.model != cfg.model { |
| 248 | eprintln!( | 325 | eprintln!( |
| 249 | "agent686: session used {}; continuing with {}", | 326 | "agent686: session used {}; continuing with {} (this invalidates the \ |
| 327 | provider's prompt cache for the whole history)", | ||
| 250 | session.model, cfg.model | 328 | session.model, cfg.model |
| 251 | ); | 329 | ); |
| 252 | } | 330 | } |
| @@ -276,6 +354,24 @@ fn open_session( | |||
| 276 | } | 354 | } |
| 277 | } | 355 | } |
| 278 | 356 | ||
| 357 | /// The system prompt is frozen with the directory the session started in. If the | ||
| 358 | /// user resumes from somewhere else, tools and prompt disagree. | ||
| 359 | fn warn_if_moved(session: &Session) { | ||
| 360 | if session.cwd.is_empty() { | ||
| 361 | return; | ||
| 362 | } | ||
| 363 | if let Ok(now) = std::env::current_dir() { | ||
| 364 | let now = now.display().to_string(); | ||
| 365 | if now != session.cwd { | ||
| 366 | eprintln!( | ||
| 367 | "agent686: this session started in {}, but you are in {now}; tools use the \ | ||
| 368 | current directory, and the prompt still describes the old one", | ||
| 369 | session.cwd | ||
| 370 | ); | ||
| 371 | } | ||
| 372 | } | ||
| 373 | } | ||
| 374 | |||
| 279 | fn warn_if_changed(watched: &Option<(PathBuf, SystemTime)>, warned: &mut bool) { | 375 | fn warn_if_changed(watched: &Option<(PathBuf, SystemTime)>, warned: &mut bool) { |
| 280 | let (path, seen) = match watched { | 376 | let (path, seen) = match watched { |
| 281 | Some(watched) => watched, | 377 | Some(watched) => watched, |
| @@ -307,7 +403,10 @@ fn print_sessions() { | |||
| 307 | println!("no sessions"); | 403 | println!("no sessions"); |
| 308 | return; | 404 | return; |
| 309 | } | 405 | } |
| 310 | println!("{:<34} {:<22} {:>5} {:>4}", "SESSION", "MODEL", "MSGS", "AGE"); | 406 | println!( |
| 407 | "{:<34} {:<22} {:>5} {:>4}", | ||
| 408 | "SESSION", "MODEL", "MSGS", "AGE" | ||
| 409 | ); | ||
| 311 | for info in sessions { | 410 | for info in sessions { |
| 312 | println!( | 411 | println!( |
| 313 | "{:<34} {:<22} {:>5} {:>4}", | 412 | "{:<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) { | |||
| 51 | pub struct Session { | 51 | pub struct Session { |
| 52 | pub id: String, | 52 | pub id: String, |
| 53 | pub model: String, | 53 | pub model: String, |
| 54 | /// Directory the session was started in; the system prompt is frozen with it. | ||
| 55 | pub cwd: String, | ||
| 54 | path: PathBuf, | 56 | path: PathBuf, |
| 55 | file: File, | 57 | file: File, |
| 56 | } | 58 | } |
| @@ -83,10 +85,14 @@ impl Session { | |||
| 83 | .map_err(|e| format!("{}: {e}", path.display()))?; | 85 | .map_err(|e| format!("{}: {e}", path.display()))?; |
| 84 | restrict(&path, 0o600); | 86 | restrict(&path, 0o600); |
| 85 | 87 | ||
| 88 | let cwd = std::env::current_dir() | ||
| 89 | .map(|path| path.display().to_string()) | ||
| 90 | .unwrap_or_default(); | ||
| 86 | let header = json!({ | 91 | let header = json!({ |
| 87 | "t": "header", | 92 | "t": "header", |
| 88 | "session": id, | 93 | "session": id, |
| 89 | "model": model, | 94 | "model": model, |
| 95 | "cwd": cwd, | ||
| 90 | "created": now_ms(), | 96 | "created": now_ms(), |
| 91 | "system": system, | 97 | "system": system, |
| 92 | }); | 98 | }); |
| @@ -96,6 +102,7 @@ impl Session { | |||
| 96 | Ok(Session { | 102 | Ok(Session { |
| 97 | id, | 103 | id, |
| 98 | model: model.to_string(), | 104 | model: model.to_string(), |
| 105 | cwd, | ||
| 99 | path, | 106 | path, |
| 100 | file, | 107 | file, |
| 101 | }) | 108 | }) |
| @@ -111,6 +118,7 @@ impl Session { | |||
| 111 | let mut model = String::new(); | 118 | let mut model = String::new(); |
| 112 | let mut system = Value::Null; | 119 | let mut system = Value::Null; |
| 113 | let mut session_id = id.to_string(); | 120 | let mut session_id = id.to_string(); |
| 121 | let mut cwd = String::new(); | ||
| 114 | let mut messages = Vec::new(); | 122 | let mut messages = Vec::new(); |
| 115 | 123 | ||
| 116 | for line in reader.lines() { | 124 | for line in reader.lines() { |
| @@ -134,6 +142,9 @@ impl Session { | |||
| 134 | if let Some(s) = value.get("session").and_then(|s| s.as_str()) { | 142 | if let Some(s) = value.get("session").and_then(|s| s.as_str()) { |
| 135 | session_id = s.to_string(); | 143 | session_id = s.to_string(); |
| 136 | } | 144 | } |
| 145 | if let Some(c) = value.get("cwd").and_then(|c| c.as_str()) { | ||
| 146 | cwd = c.to_string(); | ||
| 147 | } | ||
| 137 | } | 148 | } |
| 138 | Some("msg") => { | 149 | Some("msg") => { |
| 139 | let mut message = value.clone(); | 150 | let mut message = value.clone(); |
| @@ -158,6 +169,7 @@ impl Session { | |||
| 158 | Session { | 169 | Session { |
| 159 | id: session_id, | 170 | id: session_id, |
| 160 | model, | 171 | model, |
| 172 | cwd, | ||
| 161 | path, | 173 | path, |
| 162 | file, | 174 | file, |
| 163 | }, | 175 | }, |
| @@ -14,7 +14,13 @@ pub fn stdin_is_tty() -> bool { | |||
| 14 | 14 | ||
| 15 | fn color() -> bool { | 15 | fn color() -> bool { |
| 16 | static COLOR: OnceLock<bool> = OnceLock::new(); | 16 | static COLOR: OnceLock<bool> = OnceLock::new(); |
| 17 | *COLOR.get_or_init(stdout_is_tty) | 17 | *COLOR.get_or_init(|| { |
| 18 | stdout_is_tty() | ||
| 19 | && std::env::var_os("NO_COLOR").is_none() | ||
| 20 | && std::env::var("TERM") | ||
| 21 | .map(|term| term != "dumb") | ||
| 22 | .unwrap_or(true) | ||
| 23 | }) | ||
| 18 | } | 24 | } |
| 19 | 25 | ||
| 20 | fn paint(code: &str, text: &str) -> String { | 26 | fn paint(code: &str, text: &str) -> String { |
| @@ -177,10 +183,20 @@ impl Approver { | |||
| 177 | print!("\n{} {} ", question, paint("2", hint)); | 183 | print!("\n{} {} ", question, paint("2", hint)); |
| 178 | let _ = std::io::stdout().flush(); | 184 | let _ = std::io::stdout().flush(); |
| 179 | 185 | ||
| 186 | // Typeahead from before the prompt appeared must not answer it: a "y" | ||
| 187 | // typed during streaming would otherwise approve a command unseen. | ||
| 188 | unsafe { | ||
| 189 | libc::tcflush(libc::STDIN_FILENO, libc::TCIFLUSH); | ||
| 190 | } | ||
| 191 | |||
| 180 | let mut line = String::new(); | 192 | let mut line = String::new(); |
| 181 | if std::io::stdin().read_line(&mut line).unwrap_or(0) == 0 { | 193 | if std::io::stdin().read_line(&mut line).unwrap_or(0) == 0 { |
| 182 | return Answer::No; | 194 | return Answer::No; |
| 183 | } | 195 | } |
| 196 | // Ctrl-C during the prompt arrives as a signal, not a keystroke. | ||
| 197 | if crate::signal::CANCEL.load(std::sync::atomic::Ordering::Relaxed) { | ||
| 198 | return Answer::No; | ||
| 199 | } | ||
| 184 | match line.trim().to_ascii_lowercase().as_str() { | 200 | match line.trim().to_ascii_lowercase().as_str() { |
| 185 | "y" | "yes" => Answer::Yes, | 201 | "y" | "yes" => Answer::Yes, |
| 186 | "a" | "always" if allow_always => Answer::Always, | 202 | "a" | "always" if allow_always => Answer::Always, |
diff --git a/tests/cli.rs b/tests/cli.rs new file mode 100644 index 0000000..04fd637 --- /dev/null +++ b/tests/cli.rs | |||
| @@ -0,0 +1,78 @@ | |||
| 1 | use std::fs; | ||
| 2 | use std::path::PathBuf; | ||
| 3 | use std::process::Command; | ||
| 4 | |||
| 5 | fn agent() -> Command { | ||
| 6 | Command::new(env!("CARGO_BIN_EXE_agent686")) | ||
| 7 | } | ||
| 8 | |||
| 9 | fn temp_home(tag: &str) -> PathBuf { | ||
| 10 | let dir = std::env::temp_dir().join(format!("agent686-cli-{tag}-{}", std::process::id())); | ||
| 11 | let _ = fs::remove_dir_all(&dir); | ||
| 12 | fs::create_dir_all(&dir).unwrap(); | ||
| 13 | dir | ||
| 14 | } | ||
| 15 | |||
| 16 | #[test] | ||
| 17 | fn a_flag_without_a_value_is_a_usage_error() { | ||
| 18 | for flag in ["--session", "-m", "--base-url"] { | ||
| 19 | let output = agent().arg(flag).output().unwrap(); | ||
| 20 | assert_eq!(output.status.code(), Some(2), "{flag}"); | ||
| 21 | let stderr = String::from_utf8_lossy(&output.stderr); | ||
| 22 | assert!(stderr.contains("needs a value"), "{flag}: {stderr}"); | ||
| 23 | } | ||
| 24 | } | ||
| 25 | |||
| 26 | #[test] | ||
| 27 | fn double_dash_makes_everything_a_prompt() { | ||
| 28 | let home = temp_home("ddash"); | ||
| 29 | // Without `--` this would print the version and exit 0. | ||
| 30 | let output = agent() | ||
| 31 | .env("HOME", &home) | ||
| 32 | .env_remove("OPENCODE_API_KEY") | ||
| 33 | .args(["--", "--version"]) | ||
| 34 | .output() | ||
| 35 | .unwrap(); | ||
| 36 | |||
| 37 | assert_eq!(output.status.code(), Some(2)); | ||
| 38 | let stderr = String::from_utf8_lossy(&output.stderr); | ||
| 39 | assert!(stderr.contains("no API key"), "{stderr}"); | ||
| 40 | assert!(!String::from_utf8_lossy(&output.stdout).contains("agent686 0")); | ||
| 41 | } | ||
| 42 | |||
| 43 | #[test] | ||
| 44 | fn session_ids_cannot_escape_the_sessions_directory() { | ||
| 45 | for id in ["../escape", "a/b", "x".repeat(65).as_str()] { | ||
| 46 | let output = agent().args(["--session", id]).output().unwrap(); | ||
| 47 | assert_eq!(output.status.code(), Some(2), "{id:?}"); | ||
| 48 | let stderr = String::from_utf8_lossy(&output.stderr); | ||
| 49 | assert!(stderr.contains("invalid session id"), "{id:?}: {stderr}"); | ||
| 50 | } | ||
| 51 | } | ||
| 52 | |||
| 53 | #[test] | ||
| 54 | fn conflicting_flags_are_rejected() { | ||
| 55 | let output = agent() | ||
| 56 | .args(["-c", "--session", "abc"]) | ||
| 57 | .output() | ||
| 58 | .unwrap(); | ||
| 59 | assert_eq!(output.status.code(), Some(2)); | ||
| 60 | assert!(String::from_utf8_lossy(&output.stderr).contains("cannot be combined")); | ||
| 61 | |||
| 62 | let output = agent().args(["--list", "--doctor"]).output().unwrap(); | ||
| 63 | assert_eq!(output.status.code(), Some(2)); | ||
| 64 | assert!(String::from_utf8_lossy(&output.stderr).contains("cannot be combined")); | ||
| 65 | } | ||
| 66 | |||
| 67 | #[test] | ||
| 68 | fn unknown_flags_go_to_stderr_with_usage() { | ||
| 69 | let output = agent().arg("--nope").output().unwrap(); | ||
| 70 | assert_eq!(output.status.code(), Some(2)); | ||
| 71 | assert!( | ||
| 72 | String::from_utf8_lossy(&output.stdout).is_empty(), | ||
| 73 | "usage must not pollute stdout" | ||
| 74 | ); | ||
| 75 | let stderr = String::from_utf8_lossy(&output.stderr); | ||
| 76 | assert!(stderr.contains("unknown flag"), "{stderr}"); | ||
| 77 | assert!(stderr.contains("USAGE"), "{stderr}"); | ||
| 78 | } | ||
diff --git a/tests/doctor.rs b/tests/doctor.rs index 8a4f3f7..d42773f 100644 --- a/tests/doctor.rs +++ b/tests/doctor.rs | |||
| @@ -3,6 +3,7 @@ use std::io::{BufRead, BufReader, Write}; | |||
| 3 | use std::net::TcpListener; | 3 | use std::net::TcpListener; |
| 4 | use std::path::PathBuf; | 4 | use std::path::PathBuf; |
| 5 | use std::process::{Command, Output}; | 5 | use std::process::{Command, Output}; |
| 6 | use std::sync::mpsc; | ||
| 6 | use std::thread; | 7 | use std::thread; |
| 7 | 8 | ||
| 8 | fn temp_home(tag: &str) -> PathBuf { | 9 | fn temp_home(tag: &str) -> PathBuf { |
| @@ -12,8 +13,8 @@ fn temp_home(tag: &str) -> PathBuf { | |||
| 12 | dir | 13 | dir |
| 13 | } | 14 | } |
| 14 | 15 | ||
| 15 | /// Serves one `GET /models` response on a random port. | 16 | /// Serves one `GET /models` response on a random port, and returns the request. |
| 16 | fn serve_models(ids: &[&str]) -> String { | 17 | fn serve_models(ids: &[&str]) -> (String, mpsc::Receiver<String>) { |
| 17 | let listener = TcpListener::bind("127.0.0.1:0").unwrap(); | 18 | let listener = TcpListener::bind("127.0.0.1:0").unwrap(); |
| 18 | let addr = listener.local_addr().unwrap(); | 19 | let addr = listener.local_addr().unwrap(); |
| 19 | let body = format!( | 20 | let body = format!( |
| @@ -23,15 +24,19 @@ fn serve_models(ids: &[&str]) -> String { | |||
| 23 | .collect::<Vec<_>>() | 24 | .collect::<Vec<_>>() |
| 24 | .join(",") | 25 | .join(",") |
| 25 | ); | 26 | ); |
| 27 | let (tx, rx) = mpsc::channel(); | ||
| 26 | thread::spawn(move || { | 28 | thread::spawn(move || { |
| 27 | let (mut stream, _) = listener.accept().unwrap(); | 29 | let (mut stream, _) = listener.accept().unwrap(); |
| 28 | let mut reader = BufReader::new(stream.try_clone().unwrap()); | 30 | let mut reader = BufReader::new(stream.try_clone().unwrap()); |
| 31 | let mut request = String::new(); | ||
| 29 | loop { | 32 | loop { |
| 30 | let mut line = String::new(); | 33 | let mut line = String::new(); |
| 31 | if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" { | 34 | if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" { |
| 32 | break; | 35 | break; |
| 33 | } | 36 | } |
| 37 | request.push_str(&line); | ||
| 34 | } | 38 | } |
| 39 | let _ = tx.send(request); | ||
| 35 | let response = format!( | 40 | let response = format!( |
| 36 | "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", | 41 | "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", |
| 37 | body.len() | 42 | body.len() |
| @@ -39,7 +44,7 @@ fn serve_models(ids: &[&str]) -> String { | |||
| 39 | let _ = stream.write_all(response.as_bytes()); | 44 | let _ = stream.write_all(response.as_bytes()); |
| 40 | let _ = stream.flush(); | 45 | let _ = stream.flush(); |
| 41 | }); | 46 | }); |
| 42 | format!("http://{addr}") | 47 | (format!("http://{addr}"), rx) |
| 43 | } | 48 | } |
| 44 | 49 | ||
| 45 | fn run(home: &PathBuf, args: &[&str], key: Option<&str>) -> Output { | 50 | fn run(home: &PathBuf, args: &[&str], key: Option<&str>) -> Output { |
| @@ -78,18 +83,29 @@ fn doctor_fails_without_a_key() { | |||
| 78 | #[test] | 83 | #[test] |
| 79 | fn doctor_passes_against_a_reachable_provider() { | 84 | fn doctor_passes_against_a_reachable_provider() { |
| 80 | let home = temp_home("ok"); | 85 | let home = temp_home("ok"); |
| 81 | let base = serve_models(&["deepseek-v4.1-flash", "other-model"]); | 86 | let (base, requests) = serve_models(&["deepseek-v4.1-flash", "other-model"]); |
| 82 | let output = run(&home, &["--doctor", "--base-url", &base], Some("test")); | 87 | let output = run(&home, &["--doctor", "--base-url", &base], Some("test")); |
| 83 | let stdout = String::from_utf8_lossy(&output.stdout); | 88 | let stdout = String::from_utf8_lossy(&output.stdout); |
| 84 | assert_eq!(output.status.code(), Some(0), "{stdout}"); | 89 | assert_eq!(output.status.code(), Some(0), "{stdout}"); |
| 85 | assert!(stdout.contains("2 models visible"), "{stdout}"); | 90 | assert!(stdout.contains("2 models visible"), "{stdout}"); |
| 86 | assert!(stdout.contains("all checks passed"), "{stdout}"); | 91 | assert!(stdout.contains("all checks passed"), "{stdout}"); |
| 92 | |||
| 93 | // The gateway rejects requests without a session header, including /models. | ||
| 94 | let request = requests.recv().unwrap().to_ascii_lowercase(); | ||
| 95 | let header = request | ||
| 96 | .lines() | ||
| 97 | .find(|line| line.starts_with("x-opencode-session:")) | ||
| 98 | .unwrap_or(""); | ||
| 99 | assert!( | ||
| 100 | header.len() > "x-opencode-session:".len() + 1, | ||
| 101 | "empty session header: {header:?}" | ||
| 102 | ); | ||
| 87 | } | 103 | } |
| 88 | 104 | ||
| 89 | #[test] | 105 | #[test] |
| 90 | fn doctor_flags_a_model_the_provider_does_not_list() { | 106 | fn doctor_flags_a_model_the_provider_does_not_list() { |
| 91 | let home = temp_home("unknown-model"); | 107 | let home = temp_home("unknown-model"); |
| 92 | let base = serve_models(&["some-other-model"]); | 108 | let (base, _requests) = serve_models(&["some-other-model"]); |
| 93 | let output = run(&home, &["--doctor", "--base-url", &base], Some("test")); | 109 | let output = run(&home, &["--doctor", "--base-url", &base], Some("test")); |
| 94 | let stdout = String::from_utf8_lossy(&output.stdout); | 110 | let stdout = String::from_utf8_lossy(&output.stdout); |
| 95 | assert_eq!(output.status.code(), Some(1), "{stdout}"); | 111 | assert_eq!(output.status.code(), Some(1), "{stdout}"); |
diff --git a/tests/prompt.rs b/tests/prompt.rs new file mode 100644 index 0000000..38fbe40 --- /dev/null +++ b/tests/prompt.rs | |||
| @@ -0,0 +1,41 @@ | |||
| 1 | use std::fs; | ||
| 2 | use std::path::PathBuf; | ||
| 3 | |||
| 4 | use agent686::agent; | ||
| 5 | |||
| 6 | fn temp_dir(tag: &str) -> PathBuf { | ||
| 7 | let dir = std::env::temp_dir().join(format!("agent686-prompt-{tag}-{}", std::process::id())); | ||
| 8 | let _ = fs::remove_dir_all(&dir); | ||
| 9 | fs::create_dir_all(&dir).unwrap(); | ||
| 10 | dir | ||
| 11 | } | ||
| 12 | |||
| 13 | #[test] | ||
| 14 | fn project_instructions_stop_at_the_git_root() { | ||
| 15 | let dir = temp_dir("scope"); | ||
| 16 | let repo = dir.join("repo"); | ||
| 17 | fs::create_dir_all(repo.join("src")).unwrap(); | ||
| 18 | fs::create_dir_all(repo.join(".git")).unwrap(); | ||
| 19 | fs::write(dir.join("AGENTS.md"), "OUTSIDE THE REPO").unwrap(); | ||
| 20 | fs::write(repo.join("AGENTS.md"), "INSIDE THE REPO").unwrap(); | ||
| 21 | |||
| 22 | let prompt = agent::system_prompt_for(&repo.join("src")); | ||
| 23 | let text = prompt["content"].as_str().unwrap(); | ||
| 24 | |||
| 25 | assert!(text.contains("INSIDE THE REPO"), "{text}"); | ||
| 26 | assert!( | ||
| 27 | !text.contains("OUTSIDE THE REPO"), | ||
| 28 | "a parent AGENTS.md above the git root must not be injected" | ||
| 29 | ); | ||
| 30 | } | ||
| 31 | |||
| 32 | #[test] | ||
| 33 | fn outside_a_repository_only_the_current_directory_is_read() { | ||
| 34 | let dir = temp_dir("norepo"); | ||
| 35 | fs::create_dir_all(dir.join("work")).unwrap(); | ||
| 36 | fs::write(dir.join("AGENTS.md"), "PARENT INSTRUCTIONS").unwrap(); | ||
| 37 | |||
| 38 | let prompt = agent::system_prompt_for(&dir.join("work")); | ||
| 39 | let text = prompt["content"].as_str().unwrap(); | ||
| 40 | assert!(!text.contains("PARENT INSTRUCTIONS"), "{text}"); | ||
| 41 | } | ||
