diff --git a/services/common/src/agent_log.rs b/services/common/src/agent_log.rs index 7e7a1904b..50dba01d3 100644 --- a/services/common/src/agent_log.rs +++ b/services/common/src/agent_log.rs @@ -608,9 +608,32 @@ pub fn redact_entry(entry: &mut Value) { } } +/// Characters of a refused or failed call's message kept on its live event. +pub const MAX_LIVE_MESSAGE: usize = 2000; + +/// What a live event says of a call that did not go through (refused, +/// soft fail, error): the message the agent got, redacted and cut to +/// [`MAX_LIVE_MESSAGE`], so the run page shows the reason while the step +/// runs, not only once its log is saved. `None` for a call that went +/// through: its result can be long, and the saved log has it. +pub fn live_message(outcome: &ToolOutcome, result: &str) -> Option { + if outcome.status == OutcomeStatus::Ok { + return None; + } + // A JSON string result (`"Not run: ..."`) is shown as its text. + let text = serde_json::from_str::(result).unwrap_or_else(|_| result.to_string()); + let text = text.trim(); + if text.is_empty() { + return None; + } + let cut = crate::truncate_str(text, MAX_LIVE_MESSAGE); + let more = if cut.len() < text.len() { "…" } else { "" }; + Some(format!("{}{more}", redact_text(cut))) +} + /// One live tool event as the API returns it, from its stored `payload` and /// `timestamp` (when the call ended). Old events have no `pass`, -/// `tool_use_id` or `started_at`: those come back null. +/// `tool_use_id`, `started_at` or `message`: those come back null. pub fn live_event(payload: &Value, timestamp: &str) -> Value { let s = |k: &str| { payload @@ -628,6 +651,7 @@ pub fn live_event(payload: &Value, timestamp: &str) -> Value { "tool_use_id": s("tool_use_id"), "started_at": s("started_at"), "outcome": payload.get("outcome").filter(|o| o.is_object()).cloned(), + "message": s("message"), }) } @@ -966,5 +990,31 @@ mod tests { assert_eq!(new["started_at"], "2026-11-10T09:59:59.960Z"); assert_eq!(new["outcome"]["status"], "soft_fail"); assert_eq!(new["duration_ms"], 40); + assert_eq!(new["message"], Value::Null); + } + + #[test] + fn a_refused_live_event_carries_its_reason() { + let refused = ToolOutcome::refused("not run: writes files"); + let why = "\"Commands don't change files here: use edit_file.\""; + let m = live_message(&refused, why).expect("a message"); + assert_eq!(m, "Commands don't change files here: use edit_file."); + let ev = live_event( + &json!({"tool": "bash", "input_summary": "command: rm -rf dist", "duration_ms": 3, + "is_error": false, "outcome": refused.to_value(), "message": m}), + "2026-11-10T10:00:00Z", + ); + assert_eq!( + ev["message"], + "Commands don't change files here: use edit_file." + ); + // A call that went through keeps its result for the saved log. + assert_eq!(live_message(&ToolOutcome::ok("exit 0"), "\"done\""), None); + // Secrets never reach the event; long messages are cut. + let tok = format!("ghp_{}", "a".repeat(36)); + let m = live_message(&ToolOutcome::error("failed"), &format!("token {tok} bad")).unwrap(); + assert!(!m.contains(&tok), "{m}"); + let long = live_message(&ToolOutcome::soft_fail("x"), &"y".repeat(5000)).unwrap(); + assert!(long.chars().count() <= MAX_LIVE_MESSAGE + 1 && long.ends_with('…')); } } diff --git a/services/common/src/coder_shell.rs b/services/common/src/coder_shell.rs index 0be9467c0..0a6af1009 100644 --- a/services/common/src/coder_shell.rs +++ b/services/common/src/coder_shell.rs @@ -24,13 +24,27 @@ pub enum Shell { Tree, /// `git diff`, `git status`: the change on this branch. Diff, + /// `git show :`: a file as it is at another ref. + ReadAt { path: String, git_ref: String }, + /// `git log`, `git show `, `git blame`: the repository's history, + /// as the input of `github_history`. + History(serde_json::Value), + /// `curl` or `wget` GET or HEAD: a read-only request for a page, run + /// by the page tool (`check_url`) with its safety checks. + Fetch(Fetch), + /// Several of the above chained with `;`, `&&` or `||`: each runs as + /// its tool, in order. + Steps(Vec), /// A command for the sandbox: `dir` is a folder to run it in (from a /// leading `cd &&`), `dropped` a filter after a pipe that was - /// left off (the output comes back cut to its end anyway). + /// left off (the output comes back cut to its end anyway). `command` + /// may chain several commands; `parts` holds each plain command in it, + /// which the team's agent permissions are asked about one by one. Run { command: String, dir: Option, dropped: Option, + parts: Vec, }, /// Never runs here; the text says what to do instead. Refuse(String), @@ -38,6 +52,20 @@ pub enum Shell { Empty, } +/// A read-only HTTP request read from `curl` or `wget`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Fetch { + pub urls: Vec, + /// HEAD (`-I`, `--spider`, `-X HEAD`), else GET. + pub head: bool, + /// Redirects followed (`-L`; wget always). + pub follow: bool, + /// Request headers sent (never credentials or `Host`). + pub headers: Vec<(String, String)>, + /// The body is wanted (not `-o /dev/null`, not HEAD). + pub body: bool, +} + /// Words a shell treats as operators between commands. const CHAIN: &[&str] = &["&&", "||", ";", "|", "&"]; @@ -251,11 +279,17 @@ pub const GIT: &str = "git doesn't run here: every write_file, edit_file and bat branch's change with get_diff; put a file back as it was on the base branch with \ restore_file; the repository's history is read with github_history when it is offered."; -/// The message for network commands. -pub const NETWORK: &str = "Network commands (curl, wget, ssh and the like) don't run here. A \ - public page of the team's is read with check_url when it is offered; the sandbox reaches \ - only the hosts on the team's network allowlist, for the repository's own install, build \ - and tests."; +/// The message for network commands other than a read-only curl or wget. +pub const NETWORK: &str = "Network commands other than a read-only curl or wget (ssh, nc, \ + telnet, ftp, rsync, ping, dig and the like) don't run here. Read a public https page with \ + `curl -sS URL` for its body or `curl -sI URL` for its headers (they run as check_url), or \ + call check_url; the sandbox reaches only the hosts on the team's network allowlist, for \ + the repository's own install, build and tests."; + +/// What a refused HTTP request can be sent as instead. +const FETCH_INSTEAD: &str = "A read-only request runs: `curl -sS URL` for the status, headers \ + and body, `curl -sI URL` for the status and headers (GET or HEAD, no data, no credentials, \ + no file written). It runs as check_url, on public https pages."; /// The message for commands that read secrets or reach cloud accounts. pub const SECRETS: &str = "This command reads credentials or a cloud account, and the coding \ @@ -302,9 +336,11 @@ const FILE_WRITERS: &[&str] = &[ "patch", "unzip", "tar", ]; +/// Network programs with no read-only form here (`curl` and `wget` are +/// read as page fetches: [`fetch_of`]). const NETWORKERS: &[&str] = &[ - "curl", "wget", "ssh", "scp", "sftp", "nc", "ncat", "telnet", "ftp", "rsync", "http", "https", - "ping", "dig", "nslookup", + "ssh", "scp", "sftp", "nc", "ncat", "telnet", "ftp", "rsync", "http", "https", "ping", "dig", + "nslookup", ]; const SECRET_READERS: &[&str] = &[ @@ -556,7 +592,15 @@ fn as_read(prog: &str, args: &[String], dir: Option<&str>) -> Option { }) } "ls-files" => Some(Shell::Tree), - "log" | "show" | "blame" => Some(Shell::Refuse(GIT.to_string())), + "log" | "show" | "blame" => { + let rest: Vec = args + .iter() + .skip_while(|a| *a != sub) + .skip(1) + .cloned() + .collect(); + Some(git_history(sub, &rest, dir)) + } _ => None, } } @@ -583,6 +627,596 @@ pub fn quote(word: &str) -> String { } } +/// `git log`, `git show`, `git blame` as the history tool reads them (or a +/// file at a ref, for `git show :`). +fn git_history(sub: &str, args: &[String], dir: Option<&str>) -> Shell { + let mut map = serde_json::Map::new(); + let mut operands: Vec<&String> = Vec::new(); + let mut paths: Vec = Vec::new(); + let mut after_dashes = false; + let mut it = args.iter(); + while let Some(a) = it.next() { + if after_dashes { + paths.push(repo_path(dir, a)); + continue; + } + if a == "--" { + after_dashes = true; + continue; + } + if a == "-n" || a == "--max-count" { + if let Some(n) = it.next().and_then(|v| v.parse::().ok()) { + map.insert("limit".into(), n.into()); + } + continue; + } + if let Some(n) = a + .strip_prefix("--max-count=") + .and_then(|v| v.parse::().ok()) + { + map.insert("limit".into(), n.into()); + continue; + } + if a == "-L" { + if let Some(range) = it.next() { + if let Some((s, e)) = range.split_once(',') { + if let (Ok(s), Ok(e)) = (s.parse::(), e.parse::()) { + map.insert("start_line".into(), s.into()); + map.insert("end_line".into(), e.into()); + } + } + } + continue; + } + if let Some(n) = a + .strip_prefix('-') + .filter(|v| !v.is_empty() && v.chars().all(|c| c.is_ascii_digit())) + .and_then(|v| v.parse::().ok()) + { + map.insert("limit".into(), n.into()); + continue; + } + if a.starts_with('-') { + continue; + } + operands.push(a); + } + let strip_remote = |r: &str| r.strip_prefix("origin/").unwrap_or(r).to_string(); + match sub { + "show" => { + if let Some((rev, path)) = operands.first().and_then(|o| o.split_once(':')) { + let path = repo_path(dir, path); + if rev.is_empty() || rev == "HEAD" { + return Shell::Read { path, lines: None }; + } + return Shell::ReadAt { + path, + git_ref: strip_remote(rev), + }; + } + map.insert("kind".into(), "commits".into()); + map.insert("limit".into(), 1.into()); + if let Some(rev) = operands.first().filter(|r| r.as_str() != "HEAD") { + map.insert("ref".into(), strip_remote(rev).into()); + } + } + "blame" => { + map.insert("kind".into(), "blame".into()); + map.remove("limit"); + if let Some(p) = paths.first().cloned().or_else(|| { + operands + .iter() + .rev() + .find(|o| o.contains('.') || o.contains('/')) + .map(|o| repo_path(dir, o)) + }) { + map.insert("path".into(), p.into()); + } + return Shell::History(serde_json::Value::Object(map)); + } + _ => { + map.insert("kind".into(), "commits".into()); + for o in operands { + let looks_like_path = !o.starts_with("origin/") + && (o.contains('/') || o.rsplit_once('.').is_some_and(|(_, e)| !e.is_empty())); + if looks_like_path && paths.is_empty() { + paths.push(repo_path(dir, o)); + } else if !map.contains_key("ref") && !o.contains("..") { + map.insert("ref".into(), strip_remote(o).into()); + } + } + } + } + if let Some(p) = paths.first() { + map.insert("path".into(), p.clone().into()); + } + Shell::History(serde_json::Value::Object(map)) +} + +/// Request headers that carry credentials or a session. +fn secret_header(name: &str) -> bool { + let n = name.to_ascii_lowercase(); + [ + "auth", + "token", + "secret", + "key", + "session", + "password", + "cookie", + "signature", + "credential", + ] + .iter() + .any(|w| n.contains(w)) +} + +/// One `-H 'Name: value'`: kept, dropped (hop-by-hop) or refused. +fn fetch_header(h: &str, f: &mut Fetch) -> Result<(), String> { + let Some((name, value)) = h.split_once(':') else { + return Err(format!("has a header without a value (`{h}`)")); + }; + let name = name.trim(); + if secret_header(name) { + return Err(format!( + "sends credentials in its `{name}` header, and requests carry none" + )); + } + match name.to_ascii_lowercase().as_str() { + "host" => Err("sets the Host header, which only the URL may name".into()), + "connection" | "content-length" | "transfer-encoding" | "te" | "upgrade" => Ok(()), + _ => { + f.headers.push((name.to_string(), value.trim().to_string())); + Ok(()) + } + } +} + +fn fetch_method(m: &str, f: &mut Fetch) -> Result<(), String> { + match m.to_ascii_uppercase().as_str() { + "GET" => Ok(()), + "HEAD" => { + f.head = true; + f.body = false; + Ok(()) + } + other => Err(format!("sends a {other} request, which can change data")), + } +} + +/// `curl` with the options a read-only request uses, or why it isn't one. +fn curl_fetch(args: &[String]) -> Result { + let mut f = Fetch { + urls: Vec::new(), + head: false, + follow: false, + headers: Vec::new(), + body: true, + }; + // Options that take a value, by their short letter. + const VALUED: &str = "mHoDXAwrdFTubcxKeECyYz"; + let mut i = 0; + while i < args.len() { + let a = &args[i]; + i += 1; + let next = |i: &mut usize| { + let v = args.get(*i).cloned(); + *i += 1; + v + }; + let (opt, value): (String, Option) = if let Some(long) = a.strip_prefix("--") { + match long.split_once('=') { + Some((k, v)) => (format!("--{k}"), Some(v.to_string())), + None => (a.clone(), None), + } + } else if a.starts_with('-') && a.len() > 1 { + // A cluster of short options: `-sSL`, `-XPOST`, `-m20`. + let chars: Vec = a[1..].chars().collect(); + let mut handled = None; + for (k, c) in chars.iter().enumerate() { + if VALUED.contains(*c) { + let rest: String = chars[k + 1..].iter().collect(); + let v = if rest.is_empty() { + next(&mut i) + } else { + Some(rest) + }; + handled = Some((format!("-{c}"), v)); + break; + } + match c { + 's' | 'S' | 'f' | 'k' | 'g' | 'N' | '4' | '6' | 'v' | 'i' | '#' => {} + 'L' => f.follow = true, + 'I' => { + f.head = true; + f.body = false; + } + 'O' => return Err("writes the response to a file (-O)".into()), + 'n' => return Err("sends credentials (-n), and requests carry none".into()), + 'G' => {} + other => { + return Err(format!( + "uses `-{other}`, an option CoderHelm doesn't read for a page request" + )) + } + } + } + match handled { + Some(h) => h, + None => continue, + } + } else { + let u = if a.contains("://") { + a.clone() + } else { + format!("https://{a}") + }; + f.urls.push(u); + continue; + }; + let mut value = value; + let mut val = |i: &mut usize| -> String { + value + .take() + .or_else(|| { + let v = args.get(*i).cloned(); + *i += 1; + v + }) + .unwrap_or_default() + }; + match opt.as_str() { + "--silent" + | "--show-error" + | "--fail" + | "--fail-with-body" + | "--insecure" + | "--compressed" + | "--globoff" + | "--no-buffer" + | "--verbose" + | "--include" + | "--progress-bar" + | "--http1.1" + | "--http2" + | "--get" + | "--no-progress-meter" + | "--ipv4" + | "--ipv6" => {} + "--location" | "--location-trusted" => f.follow = true, + "--head" => { + f.head = true; + f.body = false; + } + "-m" | "--max-time" | "--connect-timeout" | "--retry" | "--retry-delay" + | "--retry-max-time" | "-A" | "--user-agent" | "-w" | "--write-out" | "-r" + | "--range" | "-e" | "--referer" | "--max-redirs" | "-C" | "--continue-at" | "-y" + | "--speed-time" | "-Y" | "--speed-limit" | "-z" | "--time-cond" => { + val(&mut i); + } + "--url" => f.urls.push(val(&mut i)), + "-H" | "--header" => fetch_header(&val(&mut i), &mut f)?, + "-X" | "--request" => fetch_method(&val(&mut i), &mut f)?, + "-o" | "--output" => match val(&mut i).as_str() { + "/dev/null" => f.body = false, + "-" => {} + other => return Err(format!("writes the response to a file ({other})")), + }, + "-D" | "--dump-header" => match val(&mut i).as_str() { + "-" | "/dev/null" => {} + other => return Err(format!("writes the headers to a file ({other})")), + }, + "--remote-name" | "--remote-name-all" | "-O" => { + return Err("writes the response to a file (-O)".into()) + } + "-d" | "--data" | "--data-raw" | "--data-binary" | "--data-urlencode" + | "--data-ascii" | "-F" | "--form" | "--form-string" | "--json" => { + return Err(format!("sends data ({opt}), which can change data")) + } + "-T" | "--upload-file" => return Err("uploads a file (-T)".into()), + "-u" | "--user" | "--oauth2-bearer" | "-E" | "--cert" | "--key" | "-n" | "--netrc" + | "--netrc-file" | "--netrc-optional" | "--aws-sigv4" | "--negotiate" | "--ntlm" + | "--digest" | "--basic" | "--anyauth" => { + return Err(format!( + "sends credentials ({opt}), and requests carry none" + )) + } + "-b" | "--cookie" | "-c" | "--cookie-jar" => { + return Err(format!( + "sends or saves a cookie ({opt}), and requests carry no session" + )) + } + "-x" | "--proxy" | "--socks5" | "--socks5-hostname" | "--unix-socket" | "-K" + | "--config" | "--resolve" | "--connect-to" => { + return Err(format!( + "uses {opt}, which routes the request around CoderHelm's checks" + )) + } + other => { + return Err(format!( + "uses `{other}`, an option CoderHelm doesn't read for a page request" + )) + } + } + } + if f.urls.is_empty() { + return Err("has no URL".into()); + } + Ok(f) +} + +/// `wget` with the options a read-only request uses, or why it isn't one. +/// Nothing is written: the body is shown instead of saved. +fn wget_fetch(args: &[String]) -> Result { + let mut f = Fetch { + urls: Vec::new(), + head: false, + follow: true, + headers: Vec::new(), + body: true, + }; + let mut i = 0; + while i < args.len() { + let a = &args[i]; + i += 1; + if a == "-nv" { + continue; + } + let (opt, mut value): (String, Option) = if a.starts_with("--") { + match a.split_once('=') { + Some((k, v)) => (k.to_string(), Some(v.to_string())), + None => (a.clone(), None), + } + } else if a.starts_with('-') && a.len() > 1 { + // `-qO-`, `-q`, `-S`, `-O file`, `-T 10`. + let chars: Vec = a[1..].chars().collect(); + let mut handled = None; + for (k, c) in chars.iter().enumerate() { + if "OTtUo".contains(*c) { + let rest: String = chars[k + 1..].iter().collect(); + handled = Some((format!("-{c}"), (!rest.is_empty()).then_some(rest))); + break; + } + match c { + 'q' | 'S' | 'v' | 'k' => {} + other => { + return Err(format!( + "uses `-{other}`, an option CoderHelm doesn't read for a page request" + )) + } + } + } + match handled { + Some(h) => h, + None => continue, + } + } else { + let u = if a.contains("://") { + a.clone() + } else { + format!("https://{a}") + }; + f.urls.push(u); + continue; + }; + let mut val = |i: &mut usize| -> String { + value + .take() + .or_else(|| { + let v = args.get(*i).cloned(); + *i += 1; + v + }) + .unwrap_or_default() + }; + match opt.as_str() { + "--quiet" + | "--server-response" + | "--no-verbose" + | "--verbose" + | "--no-check-certificate" + | "--content-on-error" + | "-nv" => {} + "--spider" => { + f.head = true; + f.body = false; + } + "-O" | "--output-document" => match val(&mut i).as_str() { + "-" => {} + "/dev/null" => f.body = false, + other => return Err(format!("writes the response to a file ({other})")), + }, + "-o" | "--output-file" | "-a" | "--append-output" => { + return Err("writes a log file".into()) + } + "-T" | "--timeout" | "-t" | "--tries" | "-U" | "--user-agent" | "--max-redirect" + | "--wait" | "--read-timeout" | "--connect-timeout" | "--dns-timeout" => { + val(&mut i); + } + "--header" => fetch_header(&val(&mut i), &mut f)?, + "--method" => fetch_method(&val(&mut i), &mut f)?, + "--post-data" | "--post-file" | "--body-data" | "--body-file" => { + return Err(format!("sends data ({opt}), which can change data")) + } + "--user" | "--password" | "--http-user" | "--http-password" | "--ask-password" + | "--use-askpass" => { + return Err(format!( + "sends credentials ({opt}), and requests carry none" + )) + } + "--load-cookies" | "--save-cookies" | "--keep-session-cookies" => { + return Err(format!( + "sends or saves a cookie ({opt}), and requests carry no session" + )) + } + other => { + return Err(format!( + "uses `{other}`, an option CoderHelm doesn't read for a page request" + )) + } + } + } + if f.urls.is_empty() { + return Err("has no URL".into()); + } + Ok(f) +} + +/// `curl` or `wget` as a page fetch, or why it never runs. `None` for any +/// other program. +fn fetch_of(prog: &str, args: &[String]) -> Option> { + match prog { + "curl" => Some(curl_fetch(args)), + "wget" => Some(wget_fetch(args)), + _ => None, + } +} + +fn fetch_refusal(prog: &str, why: &str) -> String { + format!("This `{prog}` {why}, so it doesn't run here. {FETCH_INSTEAD}") +} + +/// A folder a `cd` names: under the repository's root, plain characters. +fn safe_dir(d: &str) -> bool { + !d.is_empty() + && !d.starts_with('/') + && !d.starts_with('~') + && !d.split('/').any(|seg| seg == "..") + && d.chars() + .all(|c| c.is_ascii_alphanumeric() || "-_./@".contains(c)) +} + +/// True for a command that installs a repository's dependencies (or makes +/// its package manager available): `corepack enable`, `pnpm install`, +/// `npm ci`, `yarn install`, `npx pnpm@9 install`, `pip install -r ...`. +/// `npm install ` adds a package, and isn't one. +pub fn installs(cmd: &str) -> bool { + let w: Vec = cmd.split_whitespace().map(str::to_string).collect(); + let (mut prog, mut args) = program(&w); + if prog == "corepack" && args.first().map(String::as_str) == Some("enable") { + return true; + } + // `corepack pnpm install`, `npx --yes pnpm@10 install`. + while matches!(prog.as_str(), "corepack" | "npx" | "pnpx") { + let Some(k) = args.iter().position(|a| !a.starts_with('-')) else { + return false; + }; + prog = args[k].split('@').next().unwrap_or("").to_string(); + args = args[k + 1..].to_vec(); + } + let ops: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect(); + let sub = ops.first().map(|s| s.as_str()); + match prog.as_str() { + "npm" | "pnpm" | "yarn" | "bun" => match sub { + None => prog == "yarn", + Some("ci") | Some("install-clean") => true, + // Without package names: the manifest's dependencies. + Some("install") | Some("i") => ops.len() == 1, + _ => false, + }, + "pip" | "pip3" => sub == Some("install") && args.iter().any(|a| a == "-r" || a == "-e"), + "poetry" | "bundle" => sub == Some("install"), + "uv" => sub == Some("sync"), + "go" => sub == Some("mod") && ops.get(1).map(|s| s.as_str()) == Some("download"), + _ => false, + } +} + +/// The install at the head of a repository's check command +/// (`corepack enable && pnpm install --frozen-lockfile && ...`): what makes +/// its tools available before any command runs. +pub fn install_prefix(checks_cmd: &str) -> Option { + let parts: Vec<&str> = checks_cmd + .split("&&") + .map(str::trim) + .take_while(|p| installs(p)) + .collect(); + (!parts.is_empty()).then(|| parts.join(" && ")) +} + +/// The program a shell said it couldn't find (`bash: line 1: pnpm: command +/// not found`, `sh: 1: vitest: not found`). +pub fn missing_program(output: &str) -> Option { + for line in output.lines() { + let l = line.trim_end(); + let Some(rest) = l + .strip_suffix(": command not found") + .or_else(|| l.strip_suffix(": not found")) + else { + continue; + }; + if let Some(name) = rest.rsplit(": ").next() { + let name = name.trim(); + if !name.is_empty() && !name.contains(' ') { + return Some(name.to_string()); + } + } + } + None +} + +/// One command of a line: its words, the pipes after it, and the operator +/// that came before it. +struct Cmd { + op: Option, + first: Vec, + pipes: Vec>, +} + +impl Cmd { + fn words(&self) -> Vec { + words(&self.first) + } + + /// The command as the sandbox's shell reads it, pipes included. + fn text(&self, with_pipes: bool) -> String { + let mut out = self + .words() + .iter() + .map(|x| quote(x)) + .collect::>() + .join(" "); + if with_pipes { + for p in &self.pipes { + out.push_str(" | "); + out.push_str( + &words(p) + .iter() + .map(|x| quote(x)) + .collect::>() + .join(" "), + ); + } + } + out + } + + fn only_filters(&self) -> bool { + self.pipes + .iter() + .all(|p| FILTERS.contains(&program(&words(p)).0.as_str())) + } + + fn is_cd(&self) -> bool { + self.words().first().map(String::as_str) == Some("cd") + } +} + +fn commands(segs: Vec<(Option, Vec)>) -> Vec { + let mut out: Vec = Vec::new(); + for (op, seg) in segs { + match (op.as_deref(), out.last_mut()) { + (Some("|"), Some(last)) => last.pipes.push(seg), + _ => out.push(Cmd { + op, + first: seg, + pipes: Vec::new(), + }), + } + } + out +} + /// What one command line is on CoderHelm. pub fn classify(line: &str) -> Shell { let line = line.trim(); @@ -593,80 +1227,218 @@ pub fn classify(line: &str) -> Shell { Ok(t) => t, Err(why) => { return Shell::Refuse(format!( - "The command couldn't be read: {why}. Send one plain command." + "The command couldn't be read: {why}. Run the inner command on its own call \ + first and write its result into this one, or send one plain command." )) } }; - let segs = segments(toks); - // Any part that never runs here refuses the whole line. - for (_, seg) in &segs { - let w = words(seg); - let (prog, args) = program(&w); - let redirects = seg - .iter() - .any(|t| matches!(t, Tok::Redirect(r) if r.starts_with('>'))); - if let Some(why) = refusal(&prog, &args, redirects) { - return Shell::Refuse(why.to_string()); + let cmds = commands(segments(toks)); + let several = cmds.iter().filter(|c| !c.is_cd()).count() > 1; + // Any part that never runs here refuses the whole line, naming it. + for (k, c) in cmds.iter().enumerate() { + let why = part_refusal(c); + if let Some(why) = why { + if !several { + return Shell::Refuse(why); + } + let others: Vec = cmds + .iter() + .enumerate() + .filter(|(j, o)| *j != k && !o.is_cd()) + .map(|(_, o)| format!("`{}`", o.text(true))) + .collect(); + return Shell::Refuse(format!( + "`{}` doesn't run here: {why} The rest of the line ({}) can run: send it \ + without that part.", + c.text(true), + others.join(", ") + )); } } + if let Some(c) = cmds.iter().find(|c| c.op.as_deref() == Some("&")) { + return Shell::Refuse(format!( + "Background commands (`&` before `{}`) don't run here: every command runs to its \ + end and returns its output. Send each on its own call, without `&`.", + c.text(false) + )); + } // A leading `cd &&` sets the folder. let mut dir: Option = None; - let mut rest: &[(Option, Vec)] = &segs; - while let Some(((_, seg), tail)) = rest.split_first() { - let w = words(seg); - if w.first().map(String::as_str) == Some("cd") - && tail - .first() - .is_some_and(|(op, _)| op.as_deref() == Some("&&")) - { - let to = w.get(1).cloned().unwrap_or_default(); + let mut rest: &[Cmd] = &cmds; + while let Some((c, tail)) = rest.split_first() { + if c.is_cd() && tail.first().is_some_and(|n| n.op.as_deref() == Some("&&")) { + let to = c.words().get(1).cloned().unwrap_or_default(); + if !safe_dir(&to) { + return Shell::Refuse(format!( + "`cd {to}` isn't a folder of the repository: every path is relative to \ + its root. Name a folder under the root (list_directory with path \"\" \ + lists it)." + )); + } dir = Some(repo_path(dir.as_deref(), &to)).filter(|d| !d.is_empty()); rest = tail; continue; } break; } - let Some(((_, first), tail)) = rest.split_first() else { + if rest.is_empty() { return Shell::Empty; - }; - // Only filters after a pipe: the first command is what matters. - let only_filters = tail.iter().all(|(op, seg)| { - op.as_deref() == Some("|") && FILTERS.contains(&program(&words(seg)).0.as_str()) - }); - let w = words(first); - let (prog, args) = program(&w); - if only_filters { - if let Some(read) = as_read(&prog, &args, dir.as_deref()) { - return read; + } + // Each command as a tool, where one does it. + let mut tooled: Vec = Vec::new(); + let mut read_dir = dir.clone(); + let mut all_tools = true; + for c in rest { + if c.is_cd() { + let to = c.words().get(1).cloned().unwrap_or_default(); + if !safe_dir(&to) { + return Shell::Refuse(format!( + "`cd {to}` isn't a folder of the repository: every path is relative to \ + its root. Name a folder under the root." + )); + } + read_dir = Some(repo_path(read_dir.as_deref(), &to)).filter(|d| !d.is_empty()); + continue; + } + let w = c.words(); + let (prog, args) = program(&w); + let as_tool = if !c.only_filters() { + None + } else if let Some(Ok(f)) = fetch_of(&prog, &args) { + Some(Shell::Fetch(f)) + } else { + as_read(&prog, &args, read_dir.as_deref()) + }; + match as_tool { + Some(t) => tooled.push(t), + None => { + all_tools = false; + break; + } } } - if !tail.is_empty() && !only_filters { - return Shell::Refuse( - "Send one command at a time: chained commands (&&, ;, ||) and pipes into other \ - programs don't run here. Run each with its own call." - .into(), - ); + if all_tools { + if let Some(r) = tooled.iter().find(|t| matches!(t, Shell::Refuse(_))) { + return r.clone(); + } + return match tooled.len() { + 0 => Shell::Empty, + 1 => tooled.pop().expect("one"), + _ => Shell::Steps(tooled), + }; + } + // Commands for the sandbox. Ones only a tool does run on their own. + for c in rest { + let w = c.words(); + let (prog, args) = program(&w); + if prog == "curl" || prog == "wget" { + return Shell::Refuse(format!( + "`{}` reaches the network, and the sandbox reaches only the team's allowlist. \ + Send it on its own call: a read-only `curl -sS URL` runs as check_url.", + c.text(true) + )); + } + if prog == "git" && as_read(&prog, &args, None).is_some() { + return Shell::Refuse(format!( + "`{}` reads the repository's history, which the sandbox's copy doesn't have. \ + Send it on its own call: it runs as github_history or read_file.", + c.text(true) + )); + } + if c.is_cd() && !safe_dir(w.get(1).map(String::as_str).unwrap_or("")) { + return Shell::Refuse(format!( + "`{}` isn't a folder of the repository: every path is relative to its root. \ + Name a folder under the root.", + c.text(false) + )); + } + if c.first.iter().any(|t| matches!(t, Tok::Redirect(_))) { + return Shell::Refuse(format!( + "Input redirects (`{}`) don't run here. Pass the file to the command as an \ + argument.", + c.text(false) + )); + } } - let dropped = (!tail.is_empty()).then(|| { - tail.iter() - .map(|(op, seg)| format!("{} {}", op.as_deref().unwrap_or(""), words(seg).join(" "))) + // Filters at the very end are dropped: the output comes back cut to + // its end anyway. + let last = rest.last().expect("not empty"); + let dropped = (!last.pipes.is_empty() && last.only_filters()).then(|| { + last.pipes + .iter() + .map(|p| format!("| {}", words(p).join(" "))) .collect::>() .join(" ") - .trim() - .to_string() }); - if first.iter().any(|t| matches!(t, Tok::Redirect(_))) { - return Shell::Refuse( - "Input redirects don't run here. Pass the file to the command as an argument.".into(), - ); + let mut command = String::new(); + let mut parts: Vec = Vec::new(); + for (k, c) in rest.iter().enumerate() { + let keep_pipes = !(k + 1 == rest.len() && dropped.is_some()); + if k > 0 { + command.push(' '); + command.push_str(c.op.as_deref().unwrap_or(";")); + command.push(' '); + } + command.push_str(&c.text(keep_pipes)); + if !c.is_cd() { + parts.push(c.text(false)); + if keep_pipes { + parts.extend(c.pipes.iter().map(|p| { + words(p) + .iter() + .map(|x| quote(x)) + .collect::>() + .join(" ") + })); + } + } } Shell::Run { - command: w.iter().map(|x| quote(x)).collect::>().join(" "), + command, dir, dropped, + parts, } } +/// Why one command of a line never runs here, or `None`. +fn part_refusal(c: &Cmd) -> Option { + let w = c.words(); + let (prog, args) = program(&w); + let redirects = |seg: &[Tok]| { + seg.iter() + .any(|t| matches!(t, Tok::Redirect(r) if r.starts_with('>'))) + }; + if let Some(Err(why)) = fetch_of(&prog, &args) { + return Some(fetch_refusal(&prog, &why)); + } + if fetch_of(&prog, &args).is_some() && !c.only_filters() { + let into = c + .pipes + .iter() + .map(|p| program(&words(p)).0) + .find(|p| !FILTERS.contains(&p.as_str())) + .unwrap_or_default(); + return Some(format!( + "A pipe into `{into}` doesn't run here: a downloaded script or page is never run or \ + fed to another program. Read it with `curl -sS URL` on its own call (it runs as \ + check_url and shows the status, headers and body), then change the repository \ + with edit_file." + )); + } + if let Some(why) = refusal(&prog, &args, redirects(&c.first)) { + return Some(why.to_string()); + } + for p in &c.pipes { + let pw = words(p); + let (pp, pa) = program(&pw); + if let Some(why) = refusal(&pp, &pa, redirects(p)) { + return Some(why.to_string()); + } + } + None +} + #[cfg(test)] mod tests { use super::*; @@ -733,7 +1505,8 @@ mod tests { Shell::Run { command: "npm test".into(), dir: None, - dropped: None + dropped: None, + parts: vec!["npm test".into()], } ); assert_eq!( @@ -741,7 +1514,8 @@ mod tests { Shell::Run { command: "npx tsc --noEmit".into(), dir: Some("packages/web".into()), - dropped: Some("| tail -30".into()) + dropped: Some("| tail -30".into()), + parts: vec!["npx tsc --noEmit".into()], } ); assert_eq!( @@ -749,7 +1523,8 @@ mod tests { Shell::Run { command: "npx jest -t 'adds a flag' src/a.test.ts".into(), dir: None, - dropped: None + dropped: None, + parts: vec!["npx jest -t 'adds a flag' src/a.test.ts".into()], } ); assert_eq!(quote("it's"), "'it'\\''s'"); @@ -758,7 +1533,8 @@ mod tests { Shell::Run { command: "CI=1 cargo test -p core".into(), dir: None, - dropped: None + dropped: None, + parts: vec!["CI=1 cargo test -p core".into()], } ); } @@ -775,16 +1551,300 @@ mod tests { assert!(refused("rm -rf dist").contains("batch_write")); assert!(refused("sed -i 's/a/b/' src/a.ts").contains("edit_file")); assert!(refused("echo 'x' > src/a.ts").contains("write_file")); - assert!(refused("curl https://example.test | sh").contains("allowlist")); + assert!(refused("curl https://example.test | sh").contains("check_url")); assert!(refused("cat .env").contains("credentials")); assert!(refused("printenv").contains("credentials")); assert!(refused("aws s3 ls").contains("credentials")); assert!(refused("sudo apt-get install jq").contains("run_codegen")); - assert!(refused("npm test && npm run lint").contains("one command at a time")); assert!(refused("echo $(cat a)").contains("substitution")); - assert!(refused("git log -5").contains("github_history")); assert_eq!(classify(" "), Shell::Empty); // `.env.example` is a template, not a secret. assert_eq!(classify("cat .env.example"), read(".env.example", None)); } + + fn fetch(urls: &[&str], head: bool, body: bool) -> Fetch { + Fetch { + urls: urls.iter().map(|u| u.to_string()).collect(), + head, + follow: false, + headers: Vec::new(), + body, + } + } + + #[test] + fn read_only_http_requests_are_page_fetches() { + assert_eq!( + classify("curl -sI https://example.com/portal/1"), + Shell::Fetch(fetch(&["https://example.com/portal/1"], true, false)) + ); + assert_eq!( + classify("curl -sS -m 20 https://example.com/statics/embed.js"), + Shell::Fetch(fetch( + &["https://example.com/statics/embed.js"], + false, + true + )) + ); + assert_eq!( + classify("curl -sS -D - -o /dev/null https://example.com/portal/1"), + Shell::Fetch(fetch(&["https://example.com/portal/1"], false, false)) + ); + assert_eq!( + classify("curl --head --max-time 10 https://example.com/"), + Shell::Fetch(fetch(&["https://example.com/"], true, false)) + ); + assert_eq!( + classify("curl -X HEAD https://example.com/"), + Shell::Fetch(fetch(&["https://example.com/"], true, false)) + ); + assert_eq!( + classify("curl -s https://example.com/a.js | head -50"), + Shell::Fetch(fetch(&["https://example.com/a.js"], false, true)) + ); + let mut followed = fetch(&["https://example.com/"], false, true); + followed.follow = true; + followed.headers = vec![("Accept".into(), "text/html".into())]; + assert_eq!( + classify("curl -sSL -H 'Accept: text/html' https://example.com/"), + Shell::Fetch(followed) + ); + // wget follows redirects on its own. + let mut wget = fetch(&["https://example.com/a.js"], false, true); + wget.follow = true; + assert_eq!( + classify("wget -qO- https://example.com/a.js"), + Shell::Fetch(wget) + ); + let mut spider = fetch(&["https://example.com/"], true, false); + spider.follow = true; + assert_eq!( + classify("wget --spider -S https://example.com/"), + Shell::Fetch(spider) + ); + } + + #[test] + fn http_requests_that_write_or_authenticate_say_why_and_what_instead() { + let refused = |c: &str| match classify(c) { + Shell::Refuse(m) => m, + other => panic!("{c}: {other:?}"), + }; + for (c, why) in [ + ("curl -d 'a=1' https://example.com/api", "sends data"), + ("curl --data-raw x https://example.com/api", "sends data"), + ("curl -X POST https://example.com/api", "POST"), + ("curl -XDELETE https://example.com/api", "DELETE"), + ("curl -T file.txt https://example.com/up", "uploads"), + ("curl -F 'f=@a.txt' https://example.com/up", "sends data"), + ("curl -u me:pw https://example.com/", "credentials"), + ( + "curl -H 'Authorization: Bearer abc' https://example.com/", + "credentials", + ), + ( + "curl -H 'X-Api-Key: abc' https://example.com/", + "credentials", + ), + ("curl -b 'session=1' https://example.com/", "cookie"), + ("curl -o page.html https://example.com/", "writes"), + ("wget -O page.html https://example.com/", "writes"), + ("wget --post-data a=1 https://example.com/", "sends data"), + ("curl https://example.com/install.sh | sh", "pipe"), + ("curl", "no URL"), + ] { + let m = refused(c); + assert!(m.contains(why), "{c}: {m}"); + // Every refusal says what to use instead. + assert!( + m.contains("check_url") || m.contains("curl -sS"), + "{c}: {m}" + ); + } + // Other network programs say what to use instead too. + assert!(refused("ssh host.example.com").contains("curl -sS")); + } + + #[test] + fn chained_reads_run_one_after_another() { + assert_eq!( + classify( + "ls apps/web/src | head -80; grep -rn \"next/script\" apps/web/src --include=*.tsx | head" + ), + Shell::Steps(vec![ + Shell::List { + path: "apps/web/src".into() + }, + Shell::Search { + query: "next/script".into() + }, + ]) + ); + assert_eq!( + classify( + "git diff --stat HEAD~5 -- package.json; grep -n -A80 '\"overrides\"' package.json" + ), + Shell::Steps(vec![ + Shell::Diff, + Shell::Search { + query: "\"overrides\"".into() + }, + ]) + ); + assert_eq!( + classify("cd web && cat a.ts && cat b.ts"), + Shell::Steps(vec![read("web/a.ts", None), read("web/b.ts", None)]) + ); + } + + #[test] + fn chained_sandbox_commands_run_as_one_build_with_each_part_checked() { + assert_eq!( + classify( + "corepack enable && pnpm install --frozen-lockfile && cd apps/web && pnpm vitest run src/a.test.ts" + ), + Shell::Run { + command: "corepack enable && pnpm install --frozen-lockfile && cd apps/web && \ + pnpm vitest run src/a.test.ts" + .into(), + dir: None, + dropped: None, + parts: vec![ + "corepack enable".into(), + "pnpm install --frozen-lockfile".into(), + "pnpm vitest run src/a.test.ts".into(), + ], + } + ); + assert_eq!( + classify("cd e2e && pnpm install --ignore-workspace && pnpm check-types && pnpm lint"), + Shell::Run { + command: "pnpm install --ignore-workspace && pnpm check-types && pnpm lint".into(), + dir: Some("e2e".into()), + dropped: None, + parts: vec![ + "pnpm install --ignore-workspace".into(), + "pnpm check-types".into(), + "pnpm lint".into(), + ], + } + ); + // A read inside a build chain runs in the sandbox with the rest. + match classify("npm run build; cat dist/a.js") { + Shell::Run { command, .. } => assert_eq!(command, "npm run build ; cat dist/a.js"), + other => panic!("{other:?}"), + } + // A part that never runs here refuses the line and names that part. + let m = match classify("cd apps/web && sed -i '/a/d' src/a.tsx && npx tsc --noEmit") { + Shell::Refuse(m) => m, + other => panic!("{other:?}"), + }; + assert!(m.contains("sed -i") && m.contains("edit_file"), "{m}"); + assert!(m.contains("npx tsc --noEmit"), "{m}"); + // A folder outside the repository never runs. + assert!(matches!( + classify("npm ci && cd ../other && npm test"), + Shell::Refuse(_) + )); + } + + #[test] + fn git_history_reads_run_as_history_tools() { + assert_eq!( + classify("git show origin/main:e2e/tests/a.spec.ts"), + Shell::ReadAt { + path: "e2e/tests/a.spec.ts".into(), + git_ref: "main".into() + } + ); + assert_eq!( + classify("git log --oneline -8"), + Shell::History(serde_json::json!({"kind": "commits", "limit": 8})) + ); + assert_eq!( + classify("git log -n 3 -- src/a.ts"), + Shell::History(serde_json::json!({"kind": "commits", "limit": 3, "path": "src/a.ts"})) + ); + assert_eq!( + classify("git show 8adc85b -- docs/debug/guide.md"), + Shell::History(serde_json::json!({ + "kind": "commits", "limit": 1, "ref": "8adc85b", "path": "docs/debug/guide.md" + })) + ); + assert_eq!( + classify("git blame -L 10,20 src/a.ts"), + Shell::History(serde_json::json!({ + "kind": "blame", "path": "src/a.ts", "start_line": 10, "end_line": 20 + })) + ); + } + + #[test] + fn every_refusal_names_what_to_use_instead() { + for c in [ + "git push origin HEAD", + "rm -rf dist", + "echo 'x' > src/a.ts", + "cat .env", + "aws s3 ls", + "sudo apt-get install jq", + "echo $(cat a)", + "pwd", + "sort < a.txt", + "curl -X POST https://example.com/", + "nc example.com 80", + ] { + match classify(c) { + Shell::Refuse(m) => assert!( + [ + "edit_file", + "write_file", + "restore_file", + "get_diff", + "list_directory", + "check_url", + "run_codegen", + "configuration", + "its own call", + "as an argument", + ] + .iter() + .any(|t| m.contains(t)), + "{c}: {m}" + ), + other => panic!("{c}: {other:?}"), + } + } + } + + #[test] + fn the_repository_install_is_read_from_its_check_command() { + assert_eq!( + install_prefix("corepack enable && pnpm install --frozen-lockfile && pnpm --filter web check-types"), + Some("corepack enable && pnpm install --frozen-lockfile".into()) + ); + assert_eq!( + install_prefix("npm ci --no-audit --no-fund && npm run build"), + Some("npm ci --no-audit --no-fund".into()) + ); + assert_eq!(install_prefix("cargo test --workspace"), None); + assert!(installs("pnpm install --ignore-workspace")); + assert!(installs("corepack pnpm install --frozen-lockfile")); + assert!(installs("npx --yes pnpm@10 install")); + assert!(!installs("npm install left-pad")); + assert!(!installs("pnpm vitest run")); + } + + #[test] + fn a_missing_program_is_read_from_the_output() { + assert_eq!( + missing_program("v24.1.0\nbash: line 1: pnpm: command not found\n"), + Some("pnpm".into()) + ); + assert_eq!( + missing_program("sh: 1: vitest: not found\n"), + Some("vitest".into()) + ); + assert_eq!(missing_program("1 test failed\n"), None); + } } diff --git a/services/common/src/tool_aliases.rs b/services/common/src/tool_aliases.rs index 4b292042f..a687b8e2b 100644 --- a/services/common/src/tool_aliases.rs +++ b/services/common/src/tool_aliases.rs @@ -182,6 +182,20 @@ fn shell_call(line: &str, offered: &dyn Fn(&str) -> bool) -> Resolution { Shell::Tree => run("read_tree", json!({}), offered) .or_else(|| run("list_directory", json!({"path": ""}), offered)), Shell::Diff => run("get_diff", json!({}), offered), + Shell::ReadAt { path, git_ref } => { + return Resolution::Answer(format!( + "{path} as it is at {git_ref} isn't readable in this step: read_file reads it as \ + it is on the branch, and github_history (kind commits, path {path}) lists the \ + commits that changed it." + )) + } + Shell::History(input) => run("github_history", input, offered), + Shell::Fetch(f) => run("check_url", json!({"urls": f.urls}), offered), + Shell::Steps(_) => { + return Resolution::Answer( + "Send one command per call here: each read runs as its own tool call.".into(), + ) + } Shell::Refuse(why) => return Resolution::Answer(why), Shell::Empty => return Resolution::Answer("The command was empty.".into()), Shell::Run { .. } => None, diff --git a/services/worker/src/agent/anthropic.rs b/services/worker/src/agent/anthropic.rs index 932843db7..17249d9f6 100644 --- a/services/worker/src/agent/anthropic.rs +++ b/services/worker/src/agent/anthropic.rs @@ -1067,6 +1067,7 @@ pub async fn converse_tool_loop( duration_ms: 0, is_error: true, outcome: &outcome, + result: &text, }); } logged.push(logged_result( @@ -1120,6 +1121,7 @@ pub async fn converse_tool_loop( duration_ms: 0, is_error: true, outcome: &outcome, + result: &message, }); } info!(tool = %tool_name, "Tool not run: the policy gate said no"); @@ -1189,6 +1191,7 @@ pub async fn converse_tool_loop( duration_ms, is_error, outcome: &outcome, + result: &content, }); } let mut entry = logged_result( diff --git a/services/worker/src/agent/llm.rs b/services/worker/src/agent/llm.rs index e17c1ebd7..ccb785240 100644 --- a/services/worker/src/agent/llm.rs +++ b/services/worker/src/agent/llm.rs @@ -39,6 +39,8 @@ pub struct ToolEnded<'a> { /// It failed or was refused. pub is_error: bool, pub outcome: &'a common::agent_log::ToolOutcome, + /// What the agent got back (the refusal's reason for a refused call). + pub result: &'a str, } /// A tool call as a [`ToolCallFn`] gets it: the input as a short summary @@ -51,6 +53,9 @@ pub struct ToolEvent<'a> { pub duration_ms: u64, pub is_error: bool, pub outcome: &'a common::agent_log::ToolOutcome, + /// For a call that didn't go through: the message the agent got, + /// redacted and cut ([`common::agent_log::live_message`]). + pub message: Option<&'a str>, } /// Observer invoked after each tool call. @@ -87,10 +92,12 @@ impl LoopObserver for ToolCallFn { duration_ms, is_error, outcome: &outcome, + result: "", }); } fn on_tool_ended(&self, call: &ToolEnded<'_>) { let summary = input_summary(call.input); + let message = common::agent_log::live_message(call.outcome, call.result); (self.0)(&ToolEvent { tool: call.name, input_summary: &summary, @@ -99,6 +106,7 @@ impl LoopObserver for ToolCallFn { duration_ms: call.duration_ms, is_error: call.is_error, outcome: call.outcome, + message: message.as_deref(), }); } } diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index ac6edb113..1beced54c 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -842,6 +842,7 @@ pub async fn run( time_told: std::sync::atomic::AtomicBool::new(false), locks_written_at: std::sync::Mutex::new(None), gen_edit_rejects: std::sync::Mutex::new(std::collections::HashMap::new()), + missing: std::sync::Mutex::new(std::collections::HashMap::new()), deadline, policy: Some(crate::agent::policy::gate( state, @@ -911,6 +912,8 @@ pub async fn run( let tool_use_id = ev.tool_use_id.to_string(); let started_at = ev.started_at.to_string(); let outcome = ev.outcome.to_value(); + // A refused or failed call's reason, shown while the step runs. + let message = ev.message.map(str::to_string); let tool_name = ev.tool; // The same redaction as the agent log. let input_summary = common::agent_log::redact_text(ev.input_summary); @@ -959,6 +962,7 @@ pub async fn run( "tool_use_id": tool_use_id, "started_at": started_at, "outcome": outcome, + "message": message, }); let _ = common::run_events::put(&dynamo, &events_table, &team, &rid, &sk) .item( @@ -1521,17 +1525,103 @@ fn run_checks_tool() -> ToolDefinition { /// The script the sandbox runs for one `bash` command: in its folder, /// stopped after [`COMMAND_SECS`]. +#[cfg(test)] pub(crate) fn command_script(command: &str, dir: Option<&str>) -> String { - let inner = match dir { - Some(d) => format!("cd {} && {command}", common::coder_shell::quote(d)), - None => command.to_string(), - }; + command_script_with(None, command, dir) +} + +/// [`command_script`] after `setup`, the repository's install (what makes +/// its package manager and tools available), run quietly first: its output +/// is shown only when it fails. +pub(crate) fn command_script_with(setup: Option<&str>, command: &str, dir: Option<&str>) -> String { + let mut inner = String::new(); + if let Some(s) = setup { + inner.push_str(&format!( + "{{ {s} ; }} > /tmp/coderhelm-setup.log 2>&1 || {{ echo \"CoderHelm could not \ + install the repository before this command ({s}):\"; tail -n 40 \ + /tmp/coderhelm-setup.log; exit 1; }}; " + )); + } + if let Some(d) = dir { + inner.push_str(&format!("cd {} && ", common::coder_shell::quote(d))); + } + inner.push_str(command); format!( "timeout {COMMAND_SECS} bash -c {}", common::coder_shell::quote(&inner) ) } +/// The install a command runs after: the repository's whole install, or +/// only the part that makes its package manager available (`corepack +/// enable`) when the command installs on its own (`cd e2e && pnpm install +/// --ignore-workspace && ...`). `None` when the repository's checks have +/// no install. +pub(crate) fn setup_for(checks_cmd: Option<&str>, parts: &[String]) -> Option { + let full = checks_cmd.and_then(common::coder_shell::install_prefix)?; + if !parts.iter().any(|p| common::coder_shell::installs(p)) { + return Some(full); + } + let enable: Vec<&str> = full + .split("&&") + .map(str::trim) + .filter(|p| p.starts_with("corepack ")) + .collect(); + (!enable.is_empty()).then(|| enable.join(" && ")) +} + +/// The program a command part runs (`pnpm` of `CI=1 pnpm test`). +pub(crate) fn part_program(part: &str) -> String { + part.split_whitespace() + .find(|w| { + !(w.contains('=') + && w.split('=').next().is_some_and(|k| { + !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + })) + }) + .map(|w| w.rsplit('/').next().unwrap_or(w).to_string()) + .unwrap_or_default() +} + +/// What the coder is told once a program wasn't found in the sandbox: +/// what is missing, why, and the routes that work, so it switches route +/// instead of sending the same command again. +pub(crate) fn missing_note(prog: &str, setup: Option<&str>) -> String { + let why = match setup { + Some(s) => format!( + "The repository's install ran first (`{s}`), so `{prog}` is not one of the tools it \ + makes available. Run it through the repository's own scripts (`npm run