diff options
Diffstat (limited to '')
| -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 |
4 files changed, 204 insertions, 49 deletions
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, |
