Skip to main content

blyte_agent/
tools.rs

1//! The tool surface, and the one rule that shapes it: **everything executes synchronously**.
2//!
3//! There is no `run_in_background`, no job registry and no `job_output`. That is the single
4//! most expensive measured failure mode in this project's history: EXP-081 spent 47.6% of all
5//! input tokens on turns whose entire response was a variant of "the task is running in the
6//! background, please wait", and the most costly turn ever recorded -- 1,384,188 input tokens
7//! against 15,327,627 cached -- said exactly that and nothing else (FINDINGS 13.29).
8//!
9//! A slow test suite should cost wall-clock, which is free, instead of turns, which are not.
10//! Blocking makes the failure unrepresentable rather than merely discouraged.
11
12use std::path::{Path, PathBuf};
13use std::sync::Arc;
14use std::time::Duration;
15
16use blyte_provider::ToolSpec;
17use serde_json::{json, Value};
18
19use crate::approval::{matching_rule, Approval, ApprovalConfig};
20use crate::fs::Fs;
21use crate::shell::{poll_backoff, Shell, POLL_START};
22
23pub trait PeerTools: Send + Sync {
24    /// The running surfaces on this machine, as text for the model.
25    fn surfaces(&self) -> Result<String, String>;
26    /// Sends `message` to the surface named `name`; the text says delivered or held.
27    fn tell(&self, name: &str, message: &str) -> Result<String, String>;
28}
29
30pub trait PublishTool: Send + Sync {
31    fn publish(&self, request: &str, title: &str, body: &str) -> Result<String, String>;
32}
33
34pub trait LandTool: Send + Sync {
35    fn land(&self, request: &str) -> Result<String, String>;
36}
37
38pub const PUBLISH_TITLE_MAX_CHARS: usize = 200;
39pub const PUBLISH_BODY_MAX_BYTES: usize = 20_000;
40
41static READ_ROOTS: std::sync::RwLock<Vec<PathBuf>> = std::sync::RwLock::new(Vec::new());
42static DISPATCH_CMD: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);
43static BLYTE_TOOL: std::sync::RwLock<Option<PathBuf>> = std::sync::RwLock::new(None);
44static BACKGROUND_STARTUP_WAIT_OVERRIDE: std::sync::RwLock<Option<Duration>> =
45    std::sync::RwLock::new(None);
46static BLYTE_TASKS_DIR: std::sync::RwLock<Option<PathBuf>> = std::sync::RwLock::new(None);
47static BLYTE_RUN_STORE: std::sync::RwLock<Option<PathBuf>> = std::sync::RwLock::new(None);
48static IN_PLACE_LOCK_PATH: std::sync::RwLock<Option<PathBuf>> = std::sync::RwLock::new(None);
49static BLYTE_SURFACE: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);
50static APPROVAL: std::sync::RwLock<Option<ApprovalConfig>> = std::sync::RwLock::new(None);
51static PEER_TOOLS: std::sync::RwLock<Option<Arc<dyn PeerTools>>> = std::sync::RwLock::new(None);
52static PUBLISH_TOOL: std::sync::RwLock<Option<Arc<dyn PublishTool>>> = std::sync::RwLock::new(None);
53static LAND_TOOL: std::sync::RwLock<Option<Arc<dyn LandTool>>> = std::sync::RwLock::new(None);
54static WRITE_SCOPE: std::sync::RwLock<Option<WriteScope>> = std::sync::RwLock::new(None);
55thread_local! {
56    static BLYTE_REQUEST: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
57    static BLYTE_STARTED_BY: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
58}
59
60/// Absolute, canonical directories where `write` and `edit` may write without user approval.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct WriteScope {
63    pub allowed: Vec<PathBuf>,
64    pub edit_worktrees: Option<PathBuf>,
65}
66
67fn refused_blyte_tool_command(args: &[String]) -> Option<&'static str> {
68    let first = args.first().map(|s| s.as_str())?;
69    if first == "combine" {
70        return Some("combine");
71    }
72    if first == "review" {
73        let mut iter = args[1..].iter();
74        while let Some(arg) = iter.next() {
75            if arg == "--" {
76                break;
77            }
78            if arg == "--model-review" {
79                return Some("review --model-review");
80            }
81            let verdict_val = if arg == "--verdict" {
82                iter.next().map(|s| s.as_str())
83            } else {
84                arg.strip_prefix("--verdict=")
85            };
86            if let Some(val) = verdict_val {
87                if val.eq_ignore_ascii_case("accepted") {
88                    return Some("review --verdict accepted");
89                }
90                if val.eq_ignore_ascii_case("fixed") {
91                    return Some("review --verdict fixed");
92                }
93            }
94        }
95    }
96    None
97}
98
99pub const BLYTE_TOOL_COMMANDS: [&str; 9] = [
100    "dispatch",
101    "wait",
102    "status",
103    "review",
104    "plan",
105    "init",
106    "clean",
107    "edit-start",
108    "edit-finish",
109];
110
111pub const BLYTE_TOOL_NO_REPO_COMMANDS: [&str; 4] = ["dispatch", "wait", "status", "review"];
112
113const NO_REPO_REFUSED_COMMANDS: [&str; 6] =
114    ["plan", "init", "clean", "edit-start", "edit-finish", "undo"];
115
116const DISPATCH_VALUE_FLAGS: [&str; 20] = [
117    "-g",
118    "--gate",
119    "--tag",
120    "--plan",
121    "--plan-task",
122    "--request",
123    "--surface",
124    "--started-by",
125    "--base",
126    "--report-to",
127    "-m",
128    "--model",
129    "--max-seconds",
130    "--max-turns",
131    "--max-cost",
132    "--fold-budget",
133    "--sandbox",
134    "--network",
135    "--allow-read",
136    "--pass-env",
137];
138
139pub const REFUSED_DISPATCH_OPTIONS: [&str; 6] = [
140    "--sandbox",
141    "--network",
142    "--allow-read",
143    "--pass-env",
144    "--gate",
145    "--no-path-check",
146];
147
148pub fn refused_dispatch_option_message(option: &str) -> String {
149    format!("do not pass {option}; only the user can loosen a run's sandbox or replace its checks")
150}
151
152fn refused_dispatch_option(args: &[String]) -> Option<&'static str> {
153    for arg in args.iter().skip(1) {
154        for &opt in &REFUSED_DISPATCH_OPTIONS {
155            if arg == opt
156                || arg
157                    .strip_prefix(opt)
158                    .is_some_and(|rest| rest.starts_with('='))
159            {
160                return Some(opt);
161            }
162        }
163        if arg.starts_with("-g") {
164            return Some("-g");
165        }
166    }
167    None
168}
169
170pub fn set_blyte_request(request: Option<String>) {
171    BLYTE_REQUEST.with(|slot| {
172        *slot.borrow_mut() = request;
173    });
174}
175
176pub fn blyte_request() -> Option<String> {
177    BLYTE_REQUEST.with(|slot| slot.borrow().clone())
178}
179
180pub fn set_blyte_started_by(name: Option<String>) {
181    BLYTE_STARTED_BY.with(|slot| {
182        *slot.borrow_mut() = name;
183    });
184}
185
186pub fn blyte_started_by() -> Option<String> {
187    BLYTE_STARTED_BY.with(|slot| slot.borrow().clone())
188}
189
190pub fn set_blyte_tool(exe: Option<std::path::PathBuf>) {
191    match BLYTE_TOOL.write() {
192        Ok(mut lock) => *lock = exe,
193        Err(poisoned) => *poisoned.into_inner() = exe,
194    }
195}
196
197pub fn set_background_startup_wait(wait: Option<Duration>) {
198    match BACKGROUND_STARTUP_WAIT_OVERRIDE.write() {
199        Ok(mut lock) => *lock = wait,
200        Err(poisoned) => *poisoned.into_inner() = wait,
201    }
202}
203
204fn read_background_startup_wait(
205    lock: &std::sync::RwLock<Option<Duration>>,
206) -> Result<Duration, String> {
207    lock.read()
208        .map(|r| r.unwrap_or(BACKGROUND_STARTUP_WAIT))
209        .map_err(|e| format!("background startup wait lock is poisoned: {e}"))
210}
211
212fn background_startup_wait() -> Result<Duration, String> {
213    read_background_startup_wait(&BACKGROUND_STARTUP_WAIT_OVERRIDE)
214}
215
216pub fn blyte_tool() -> Option<PathBuf> {
217    BLYTE_TOOL
218        .read()
219        .map(|r| r.clone())
220        .unwrap_or_else(|e| e.into_inner().clone())
221}
222
223pub fn set_blyte_tasks_dir(dir: Option<PathBuf>) {
224    match BLYTE_TASKS_DIR.write() {
225        Ok(mut lock) => *lock = dir,
226        Err(poisoned) => *poisoned.into_inner() = dir,
227    }
228}
229
230pub fn blyte_tasks_dir() -> Option<PathBuf> {
231    BLYTE_TASKS_DIR
232        .read()
233        .map(|r| r.clone())
234        .unwrap_or_else(|e| e.into_inner().clone())
235}
236
237pub fn set_blyte_run_store(dir: Option<PathBuf>) {
238    match BLYTE_RUN_STORE.write() {
239        Ok(mut lock) => *lock = dir,
240        Err(poisoned) => *poisoned.into_inner() = dir,
241    }
242}
243
244pub fn blyte_run_store() -> Option<PathBuf> {
245    BLYTE_RUN_STORE
246        .read()
247        .map(|r| r.clone())
248        .unwrap_or_else(|e| e.into_inner().clone())
249}
250
251pub fn set_in_place_lock_path(path: Option<PathBuf>) {
252    match IN_PLACE_LOCK_PATH.write() {
253        Ok(mut lock) => *lock = path,
254        Err(poisoned) => *poisoned.into_inner() = path,
255    }
256}
257
258pub fn in_place_lock_path() -> Option<PathBuf> {
259    IN_PLACE_LOCK_PATH
260        .read()
261        .map(|r| r.clone())
262        .unwrap_or_else(|e| e.into_inner().clone())
263}
264
265pub fn set_blyte_surface(surface: Option<String>) {
266    match BLYTE_SURFACE.write() {
267        Ok(mut lock) => *lock = surface,
268        Err(poisoned) => *poisoned.into_inner() = surface,
269    }
270}
271
272pub fn blyte_surface() -> Option<String> {
273    BLYTE_SURFACE
274        .read()
275        .map(|r| r.clone())
276        .unwrap_or_else(|e| e.into_inner().clone())
277}
278
279pub fn set_approval(config: Option<ApprovalConfig>) {
280    match APPROVAL.write() {
281        Ok(mut lock) => *lock = config,
282        Err(poisoned) => *poisoned.into_inner() = config,
283    }
284}
285
286pub fn approval() -> Option<ApprovalConfig> {
287    APPROVAL
288        .read()
289        .map(|r| r.clone())
290        .unwrap_or_else(|e| e.into_inner().clone())
291}
292
293pub fn set_peer_tools(tools: Option<Arc<dyn PeerTools>>) {
294    match PEER_TOOLS.write() {
295        Ok(mut lock) => *lock = tools,
296        Err(poisoned) => *poisoned.into_inner() = tools,
297    }
298}
299
300pub fn peer_tools() -> Option<Arc<dyn PeerTools>> {
301    PEER_TOOLS
302        .read()
303        .map(|r| r.clone())
304        .unwrap_or_else(|e| e.into_inner().clone())
305}
306
307pub fn set_publish_tool(tool: Option<Arc<dyn PublishTool>>) {
308    match PUBLISH_TOOL.write() {
309        Ok(mut lock) => *lock = tool,
310        Err(poisoned) => *poisoned.into_inner() = tool,
311    }
312}
313
314pub fn publish_tool() -> Option<Arc<dyn PublishTool>> {
315    PUBLISH_TOOL
316        .read()
317        .map(|r| r.clone())
318        .unwrap_or_else(|e| e.into_inner().clone())
319}
320
321pub fn set_land_tool(tool: Option<Arc<dyn LandTool>>) {
322    match LAND_TOOL.write() {
323        Ok(mut lock) => *lock = tool,
324        Err(poisoned) => *poisoned.into_inner() = tool,
325    }
326}
327
328pub fn land_tool() -> Option<Arc<dyn LandTool>> {
329    LAND_TOOL
330        .read()
331        .map(|r| r.clone())
332        .unwrap_or_else(|e| e.into_inner().clone())
333}
334
335pub fn set_write_scope(scope: Option<WriteScope>) {
336    match WRITE_SCOPE.write() {
337        Ok(mut lock) => *lock = scope,
338        Err(poisoned) => *poisoned.into_inner() = scope,
339    }
340}
341
342pub fn write_scope() -> Option<WriteScope> {
343    WRITE_SCOPE
344        .read()
345        .map(|r| r.clone())
346        .unwrap_or_else(|e| e.into_inner().clone())
347}
348
349/// Set the host dispatch command for the conversation model's `dispatch` tool.
350pub fn set_dispatch_cmd(cmd: Option<String>) {
351    match DISPATCH_CMD.write() {
352        Ok(mut lock) => *lock = cmd,
353        Err(poisoned) => *poisoned.into_inner() = cmd,
354    }
355}
356
357/// The currently configured dispatch command, if any.
358pub fn dispatch_cmd() -> Option<String> {
359    DISPATCH_CMD
360        .read()
361        .map(|r| r.clone())
362        .unwrap_or_else(|e| e.into_inner().clone())
363}
364
365/// Extra directories allowed for reading with `read` and `grep`.
366///
367/// Later calls replace earlier ones.
368pub fn set_read_roots(roots: Vec<PathBuf>) {
369    match READ_ROOTS.write() {
370        Ok(mut lock) => *lock = roots,
371        Err(poisoned) => *poisoned.into_inner() = roots,
372    }
373}
374
375/// The directories set with `set_read_roots`.
376pub fn read_roots() -> Vec<PathBuf> {
377    READ_ROOTS
378        .read()
379        .map(|r| r.clone())
380        .unwrap_or_else(|e| e.into_inner().clone())
381}
382
383/// Output over this many lines is distilled to head and tail before entering context.
384///
385/// Sized from measurement, not intuition: across 64 recorded command outputs the median was
386/// 165-307 lines and exactly one exceeded a thousand -- at 25,105 lines, 88% of that run's
387/// entire output volume and 26x the next largest (FINDINGS 13.26). The distribution is a heavy
388/// tail, so the bound exists for the rare case; it must not clip the common one.
389pub const OUTPUT_LINE_BUDGET: usize = 400;
390
391/// Lines a `read` returns at once, within `MAX_OUTPUT_CHARS`. Larger than `OUTPUT_LINE_BUDGET`
392/// because a file the model asked for is the point, not noise: at 400 lines a dogfood run spent
393/// 15 turns paging through one 650-line file, each re-sending the whole prompt.
394pub const READ_LINE_BUDGET: usize = 2_000;
395
396/// Most matches a single search returns. The count of what was cut is always reported, so a
397/// truncated search reads as truncated rather than as a complete answer with few hits.
398pub const MAX_MATCHES: usize = 200;
399
400/// Longest line kept whole. Minified code puts megabytes on one line, which a line budget alone
401/// never catches: a single grep over node_modules overflowed a 1,048,576-token request.
402pub const MAX_LINE_CHARS: usize = 500;
403
404/// Longest line `read` keeps whole. Larger than `MAX_LINE_CHARS` because a file the model asked
405/// for is the point, not noise: a plan's 640-character contract line was clipped at 500 and the
406/// model spent three turns failing to see it. Minified files are still clipped, here and by
407/// `MAX_OUTPUT_CHARS`.
408pub const READ_LINE_CHARS: usize = 2_000;
409
410/// Most characters a single tool result may carry (about 15K tokens), after line clipping and
411/// line distillation. The final guarantee that one result cannot swamp the context.
412pub const MAX_OUTPUT_CHARS: usize = 60_000;
413
414/// `bound_output_lines` with a caller-chosen line length (`read` uses `READ_LINE_CHARS`).
415pub fn bound_output_with(text: &str, line_budget: usize, line_chars: usize) -> String {
416    let clipped: Vec<String> = text
417        .lines()
418        .map(|l| {
419            let n = l.chars().count();
420            if n > line_chars {
421                let head: String = l.chars().take(line_chars).collect();
422                format!(
423                    "{head} …[{} more chars clipped by blyte; the grep tool shows the text around a match]",
424                    n - line_chars
425                )
426            } else {
427                l.to_string()
428            }
429        })
430        .collect();
431    let mut joined = clipped.join("\n");
432    if text.ends_with('\n') {
433        joined.push('\n');
434    }
435    let distilled = distil(&joined, line_budget);
436    let total = distilled.chars().count();
437    if total <= MAX_OUTPUT_CHARS {
438        return distilled;
439    }
440    let head_n = MAX_OUTPUT_CHARS * 2 / 3;
441    let tail_n = MAX_OUTPUT_CHARS - head_n;
442    let head: String = distilled.chars().take(head_n).collect();
443    let tail: String = distilled.chars().skip(total - tail_n).collect();
444    format!(
445        "{head}\n\n[... {} chars elided by blyte ...]\n\n{tail}",
446        total - head_n - tail_n
447    )
448}
449
450/// `bound_output` with a caller-chosen line budget (`read` uses `READ_LINE_BUDGET`).
451pub fn bound_output_lines(text: &str, line_budget: usize) -> String {
452    bound_output_with(text, line_budget, MAX_LINE_CHARS)
453}
454
455/// Bound a tool's output by size: clip over-long lines, distil to `OUTPUT_LINE_BUDGET` lines,
456/// then cap the total, keeping head and tail. Ordinary output passes through unchanged.
457pub fn bound_output(text: &str) -> String {
458    bound_output_lines(text, OUTPUT_LINE_BUDGET)
459}
460
461/// Match-centred excerpt for long lines.
462///
463/// When `text` has at most `max` characters, return it unchanged. Otherwise keep the whole match
464/// (cut the match itself to `max` characters if it alone is longer) and split the rest of the
465/// `max` budget evenly before and after it, shifting any unused side to the other; prefix
466/// `…[<n> chars] ` when characters were dropped before, and suffix ` …[<n> chars]` when dropped
467/// after, `<n>` being the count dropped. Never split a UTF-8 character.
468pub fn excerpt_around(text: &str, start: usize, end: usize, max: usize) -> String {
469    let total_chars = text.chars().count();
470    if total_chars <= max {
471        return text.to_string();
472    }
473    if start > text.len()
474        || end > text.len()
475        || start > end
476        || !text.is_char_boundary(start)
477        || !text.is_char_boundary(end)
478    {
479        return text.to_string();
480    }
481
482    let before = &text[..start];
483    let matched = &text[start..end];
484    let after = &text[end..];
485
486    let before_chars = before.chars().count();
487    let match_chars = matched.chars().count();
488    let after_chars = after.chars().count();
489
490    if match_chars >= max {
491        let kept_match: String = matched.chars().take(max).collect();
492        let dropped_before = before_chars;
493        let dropped_after = after_chars + (match_chars - max);
494        let mut out = String::new();
495        if dropped_before > 0 {
496            out.push_str(&format!("…[{dropped_before} chars] "));
497        }
498        out.push_str(&kept_match);
499        if dropped_after > 0 {
500            out.push_str(&format!(" …[{dropped_after} chars]"));
501        }
502        return out;
503    }
504
505    let rem = max - match_chars;
506    let half_before = rem / 2;
507    let half_after = rem - half_before;
508
509    let (take_before, take_after) = if before_chars < half_before {
510        let tb = before_chars;
511        let ta = (rem - tb).min(after_chars);
512        (tb, ta)
513    } else if after_chars < half_after {
514        let ta = after_chars;
515        let tb = (rem - ta).min(before_chars);
516        (tb, ta)
517    } else {
518        (half_before, half_after)
519    };
520
521    let dropped_before = before_chars - take_before;
522    let dropped_after = after_chars - take_after;
523
524    let mut out = String::new();
525    if dropped_before > 0 {
526        out.push_str(&format!("…[{dropped_before} chars] "));
527    }
528    let kept_before: String = before
529        .chars()
530        .skip(dropped_before)
531        .take(take_before)
532        .collect();
533    out.push_str(&kept_before);
534    out.push_str(matched);
535    let kept_after: String = after.chars().take(take_after).collect();
536    out.push_str(&kept_after);
537    if dropped_after > 0 {
538        out.push_str(&format!(" …[{dropped_after} chars]"));
539    }
540    out
541}
542
543/// Most matches `excerpt_matches` shows from one line.
544const MAX_EXCERPTS_PER_LINE: usize = 5;
545
546/// An excerpt of a long `text` showing every match in `found` (byte ranges, in order; at most
547/// `MAX_EXCERPTS_PER_LINE`) with some context each, within about `max` characters. One match is
548/// `excerpt_around`. On sanitize-git-repo the first match in a 21,367-character line was an
549/// innocent `hf_cache_dir`; the secret was 15,000 characters later.
550pub fn excerpt_matches(text: &str, found: &[(usize, usize)], max: usize) -> String {
551    if found.len() <= 1 || text.chars().count() <= max {
552        return match found.first() {
553            Some(&(s, e)) => excerpt_around(text, s, e, max),
554            None => text.to_string(),
555        };
556    }
557    let shown = &found[..found.len().min(MAX_EXCERPTS_PER_LINE)];
558    let match_chars: usize = shown.iter().map(|&(s, e)| text[s..e].chars().count()).sum();
559    let context = max.saturating_sub(match_chars) / (2 * shown.len());
560    // Char-index windows around each match, merged where they overlap.
561    let to_char = |b: usize| text[..b].chars().count();
562    let total = text.chars().count();
563    let mut windows: Vec<(usize, usize)> = Vec::new();
564    for &(s, e) in shown {
565        let (cs, ce) = (to_char(s), to_char(e));
566        let w = (cs.saturating_sub(context), (ce + context).min(total));
567        match windows.last_mut() {
568            Some(last) if w.0 <= last.1 => last.1 = last.1.max(w.1),
569            _ => windows.push(w),
570        }
571    }
572    let chars: Vec<char> = text.chars().collect();
573    let mut out = String::new();
574    let mut pos = 0;
575    for (i, &(a, b)) in windows.iter().enumerate() {
576        if a > pos {
577            if i == 0 {
578                out.push_str(&format!("…[{} chars] ", a - pos));
579            } else {
580                out.push_str(&format!(" …[{} chars] ", a - pos));
581            }
582        }
583        out.extend(&chars[a..b]);
584        pos = b;
585    }
586    if pos < total {
587        out.push_str(&format!(" …[{} chars]", total - pos));
588    }
589    if found.len() > shown.len() {
590        out.push_str(&format!(
591            " [{} more matches in this line]",
592            found.len() - shown.len()
593        ));
594    }
595    out
596}
597
598fn split_grep_prefix(line: &str) -> (&str, &str) {
599    static PREFIX_RE: std::sync::LazyLock<regex::Regex> =
600        std::sync::LazyLock::new(|| regex::Regex::new(r"^(\d+:\d+:|\d+:|.*?:\d+:)").unwrap());
601    if let Some(m) = PREFIX_RE.find(line) {
602        (&line[..m.end()], &line[m.end()..])
603    } else {
604        ("", line)
605    }
606}
607
608/// Ceiling on a single MODEL-ISSUED command.
609///
610/// Deliberately much shorter than the gate's budget, because the two have different shapes. A
611/// verification suite legitimately runs for many minutes and gets its own longer deadline in
612/// `run::Runner`. A command the model types while exploring is almost always seconds, and when
613/// it is not it is usually wrong: the first live run opened with `find / -name pytest`, which
614/// at the previous 900s ceiling was entitled to fifteen minutes of walking the filesystem
615/// before anything intervened. Enforcing a bound is not enough on its own -- the bound has to
616/// be near the size of the work.
617///
618/// 300s still accommodates a genuine `npm install` or `cargo build`. Past that the command is
619/// killed, the model is told so, and it can re-issue something narrower.
620pub const COMMAND_TIMEOUT: Duration = Duration::from_secs(300);
621
622/// Ceiling on `blyte edit-finish`, which runs the repository's verification gate in the foreground
623/// and therefore needs a gate-sized budget rather than the 300s exploration command limit.
624pub const EDIT_FINISH_TIMEOUT: Duration = Duration::from_secs(3600);
625
626pub fn blyte_command_timeout(subcommand: &str) -> Duration {
627    if subcommand == "edit-finish" {
628        EDIT_FINISH_TIMEOUT
629    } else {
630        COMMAND_TIMEOUT
631    }
632}
633
634fn command_ceiling(name: &str, args: &Value) -> Duration {
635    if name == "blyte" {
636        if let Some(first) = args
637            .get("args")
638            .and_then(|v| v.as_array())
639            .and_then(|a| a.first())
640            .and_then(|v| v.as_str())
641        {
642            return blyte_command_timeout(first);
643        }
644    }
645    COMMAND_TIMEOUT
646}
647
648#[derive(Debug, Clone, PartialEq)]
649pub struct ToolOutcome {
650    pub content: String,
651    pub is_error: bool,
652}
653
654impl ToolOutcome {
655    fn ok(s: impl Into<String>) -> Self {
656        Self {
657            content: s.into(),
658            is_error: false,
659        }
660    }
661    fn err(s: impl Into<String>) -> Self {
662        Self {
663            content: s.into(),
664            is_error: true,
665        }
666    }
667}
668
669/// Keep head and tail, drop the middle, and say how much was dropped.
670///
671/// Truncating the tail alone would be worse than useless for the case this exists for: a test
672/// runner puts its summary at the end, so tail-clipping hides the answer and keeps the noise.
673pub fn distil(text: &str, budget: usize) -> String {
674    let lines: Vec<&str> = text.lines().collect();
675    if lines.len() <= budget {
676        return text.to_string();
677    }
678    let head = budget * 2 / 3;
679    let tail = budget - head;
680    let dropped = lines.len() - budget;
681    let mut out = lines[..head].join("\n");
682    out.push_str(&format!(
683        "\n\n[... {dropped} lines elided by blyte ...]\n\n"
684    ));
685    out.push_str(&lines[lines.len() - tail..].join("\n"));
686    out
687}
688
689/// Resolve `.` and `..` textually, without touching the filesystem.
690///
691/// Belt to `canonicalize`'s braces, and not redundant. `Path::starts_with` compares COMPONENTS,
692/// so `/ws/../../escaped.rs` lexically starts with `/ws` and passes a naive containment check.
693/// That makes the whole escape guarantee rest on canonicalize normalising `..` -- true for
694/// `std::fs` and for `readlink -f`, but a property of the implementation rather than of the
695/// check. Normalising first means a weak or failing canonicalize cannot be walked past.
696///
697/// Leading `..` that would climb above the root are dropped rather than preserved: there is no
698/// legitimate path above the workspace, so collapsing them keeps the result inside where the
699/// caller can still reject it on its merits.
700fn lexically_normalize(p: &Path) -> PathBuf {
701    use std::path::Component;
702    let mut out = PathBuf::new();
703    for c in p.components() {
704        match c {
705            Component::CurDir => {}
706            Component::ParentDir => {
707                if !out.pop() {
708                    // Nothing to pop: keep it so an escape remains visible to the check
709                    // rather than silently becoming the root itself.
710                    out.push("..");
711                }
712            }
713            other => out.push(other.as_os_str()),
714        }
715    }
716    out
717}
718
719/// Reject a path that escapes the workspace.
720///
721/// Checked against the CANONICAL path, so `../` and symlinks cannot walk out. The previous
722/// harness relied on a prompt rule -- "confine all inspections to the workspace" -- which is
723/// exactly the kind of instruction Invariant IV exists because agents ignore under pressure.
724fn resolve_in_workspace(fs: &dyn Fs, root: &Path, raw: &str) -> Result<PathBuf, String> {
725    let joined = lexically_normalize(&if Path::new(raw).is_absolute() {
726        PathBuf::from(raw)
727    } else {
728        root.join(raw)
729    });
730    let root_c = fs
731        .canonicalize(root)
732        .map_err(|e| format!("workspace root unreadable: {e}"))?;
733
734    // Canonicalise the NEAREST EXISTING ancestor, starting with the target itself. Walking
735    // straight to `.parent()` was wrong for a directory target: `Path::new("/a/b/.").parent()`
736    // is `/a`, not `/a/b`, so searching the workspace root as `.` resolved to its parent and was
737    // refused. Starting at the target and climbing only when it does not exist keeps both cases
738    // right -- an existing directory checks itself, a file about to be created checks the
739    // directory it will land in -- and neither is waved through unchecked.
740    let mut probe = joined.as_path();
741    let probe_c = loop {
742        if let Ok(c) = fs.canonicalize(probe) {
743            break c;
744        }
745        match probe.parent() {
746            Some(p) => probe = p,
747            // Nothing in the chain exists: fall back to a lexical check rather than allowing it.
748            None => break joined.clone(),
749        }
750    };
751    if !probe_c.starts_with(&root_c) {
752        return Err(format!("path escapes the workspace: {raw}"));
753    }
754    Ok(joined)
755}
756
757fn resolve_real_target(fs: &dyn Fs, path: &Path) -> Result<PathBuf, String> {
758    let mut probe = path;
759    let mut tail: Vec<std::ffi::OsString> = Vec::new();
760    loop {
761        match fs.canonicalize(probe) {
762            Ok(mut resolved) => {
763                for part in tail.into_iter().rev() {
764                    resolved.push(part);
765                }
766                return Ok(resolved);
767            }
768            Err(e) => {
769                let exists_or_unreadable = if fs.is_local() {
770                    match std::fs::symlink_metadata(probe) {
771                        Ok(_) => true,
772                        Err(meta_err) => meta_err.kind() != std::io::ErrorKind::NotFound,
773                    }
774                } else {
775                    false
776                };
777                if exists_or_unreadable {
778                    return Err(format!("cannot canonicalize {}: {e}", probe.display()));
779                }
780                let Some(name) = probe.file_name() else {
781                    return Err(format!("cannot canonicalize {}: {e}", probe.display()));
782                };
783                tail.push(name.to_os_string());
784                let Some(parent) = probe.parent() else {
785                    return Err(format!("cannot canonicalize {}: {e}", probe.display()));
786                };
787                probe = parent;
788            }
789        }
790    }
791}
792
793/// Reports whether `real_target` lies inside an open direct edit's worktree under
794/// `edit_worktrees`: `<edit_worktrees>/<id>/<rest>` where `<edit_worktrees>/<id>.edit.json`
795/// exists, `<edit_worktrees>/<id>.json` does not, `<edit_worktrees>/<id>` is a directory, and no
796/// path component below `<id>/` is `.git`.
797fn is_in_open_edit_worktree(edit_worktrees: &Path, real_target: &Path) -> Result<bool, String> {
798    use std::path::Component;
799    let Ok(rel) = real_target.strip_prefix(edit_worktrees) else {
800        return Ok(false);
801    };
802    let mut comps = rel.components();
803    let Some(Component::Normal(id)) = comps.next() else {
804        return Ok(false);
805    };
806    let mut has_child = false;
807    for comp in comps {
808        has_child = true;
809        match comp {
810            Component::Normal(name) if name == ".git" => return Ok(false),
811            Component::Normal(_) => {}
812            _ => return Ok(false),
813        }
814    }
815    if !has_child {
816        return Ok(false);
817    }
818    crate::sandbox::is_open_edit_worktree_id(edit_worktrees, id)
819}
820
821fn protected_read_refusal(verb: &str, path: &Path) -> String {
822    format!(
823        "{verb} was not made: {} is a credential path that this conversation cannot read",
824        path.display()
825    )
826}
827
828fn append_skipped_line(mut text: String, skipped: usize) -> String {
829    if skipped > 0 {
830        text.push_str(&format!("\n(credential paths skipped: {skipped})"));
831    }
832    text
833}
834
835fn resolve_host_prefix(fs: &dyn Fs, path: &Path) -> Result<PathBuf, String> {
836    let abs = if path.is_absolute() {
837        path.to_path_buf()
838    } else {
839        std::env::current_dir()
840            .map_err(|e| format!("cannot determine current directory: {e}"))?
841            .join(path)
842    };
843    let mut probe = abs.as_path();
844    let mut tail: Vec<std::ffi::OsString> = Vec::new();
845    loop {
846        match fs.canonicalize(probe) {
847            Ok(mut resolved) => {
848                for part in tail.into_iter().rev() {
849                    resolved.push(part);
850                }
851                return Ok(resolved);
852            }
853            Err(e) => {
854                let not_present = match std::fs::symlink_metadata(probe) {
855                    Ok(_) => false,
856                    Err(meta_err) => matches!(
857                        meta_err.kind(),
858                        std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
859                    ),
860                };
861                if !not_present {
862                    return Err(format!("cannot canonicalize {}: {e}", probe.display()));
863                }
864                let Some(name) = probe.file_name() else {
865                    return Err(format!("cannot canonicalize {}: {e}", probe.display()));
866                };
867                tail.push(name.to_os_string());
868                let Some(parent) = probe.parent() else {
869                    return Err(format!("cannot canonicalize {}: {e}", probe.display()));
870                };
871                probe = parent;
872            }
873        }
874    }
875}
876
877fn check_protected_write(
878    fs: &dyn Fs,
879    root: &Path,
880    tool: &str,
881    raw_path: &str,
882    path: &Path,
883) -> Result<(), String> {
884    if !fs.is_local() {
885        return Ok(());
886    }
887    let home_raw = std::env::var_os("HOME")
888        .filter(|h| !h.is_empty())
889        .ok_or_else(|| format!("{tool}: cannot check protected paths without HOME"))?;
890    let real_target = resolve_real_target(fs, path)?;
891    let real_root = resolve_host_prefix(fs, root)?;
892    let home = resolve_host_prefix(fs, Path::new(&home_raw))?;
893    let mut state_dirs: Vec<PathBuf> = Vec::new();
894    let mut push_state_dir = |raw: PathBuf| -> Result<(), String> {
895        let resolved = resolve_host_prefix(fs, &raw)?;
896        if !state_dirs.contains(&resolved) {
897            state_dirs.push(resolved);
898        }
899        Ok(())
900    };
901    if let Some(dir) = crate::sandbox::state_blyte_dir() {
902        push_state_dir(dir)?;
903    }
904    if let Some(dir) = std::env::var_os("BLYTE_STATE_DIR").filter(|d| !d.is_empty()) {
905        push_state_dir(PathBuf::from(dir))?;
906    }
907    if let Some(xdg) = std::env::var_os("XDG_STATE_HOME").filter(|d| !d.is_empty()) {
908        push_state_dir(PathBuf::from(xdg).join("blyte"))?;
909    }
910    if state_dirs.is_empty() {
911        if let Some(reason) = crate::write_guard::protected_write(&real_target, &home, None) {
912            return Err(format!(
913                "{tool}: {raw_path} is protected ({reason}); blyte does not write there"
914            ));
915        }
916    } else {
917        for dir in &state_dirs {
918            let check_dir = if crate::sandbox::is_run_scratch_workspace(&real_root, dir)
919                && real_target.starts_with(&real_root)
920            {
921                None
922            } else {
923                Some(dir.as_path())
924            };
925            if let Some(reason) =
926                crate::write_guard::protected_write(&real_target, &home, check_dir)
927            {
928                return Err(format!(
929                    "{tool}: {raw_path} is protected ({reason}); blyte does not write there"
930                ));
931            }
932        }
933    }
934    Ok(())
935}
936
937pub fn check_write_scope(fs: &dyn Fs, tool: &str, path: &Path) -> Result<(), String> {
938    let Some(scope) = write_scope() else {
939        return Ok(());
940    };
941    let real_target = resolve_real_target(fs, path)?;
942    let in_blyte_own = if fs.is_local() {
943        crate::sandbox::is_in_blyte_own_dir(&real_target)?
944    } else {
945        false
946    };
947    if !in_blyte_own && scope.allowed.iter().any(|dir| real_target.starts_with(dir)) {
948        return Ok(());
949    }
950    if let Some(edit_worktrees) = &scope.edit_worktrees {
951        if is_in_open_edit_worktree(edit_worktrees, &real_target)? {
952            return Ok(());
953        }
954    }
955    let (reason, hint) = if in_blyte_own {
956        (
957            "inside blyte's own state or configuration".to_string(),
958            "the user can approve writes to blyte's own state or configuration",
959        )
960    } else {
961        let allowed_list = scope
962            .allowed
963            .iter()
964            .map(|p| p.display().to_string())
965            .collect::<Vec<_>>()
966            .join(", ");
967        (
968            format!("outside the directories this conversation may write ({allowed_list})"),
969            "the user can approve writes outside these directories",
970        )
971    };
972    let cmd = format!("{tool} {}", real_target.display());
973    let Some(cfg) = approval() else {
974        return Err(format!(
975            "write was not made: {} is {reason}; no approver is configured ({hint}).",
976            real_target.display()
977        ));
978    };
979    match cfg.approver.ask(&cmd, &reason) {
980        Approval::Approved => Ok(()),
981        Approval::Denied => Err(format!(
982            "write was not made: {} is {reason}; the user refused ({hint}).",
983            real_target.display()
984        )),
985        Approval::Unavailable => Err(format!(
986            "write was not made: {} is {reason}; nobody can approve it in this run ({hint}).",
987            real_target.display()
988        )),
989    }
990}
991
992/// Reject a path that escapes the workspace, unless an absolute path is inside a read root.
993pub(crate) fn resolve_for_read(fs: &dyn Fs, root: &Path, raw: &str) -> Result<PathBuf, String> {
994    if let Ok(p) = resolve_in_workspace(fs, root, raw) {
995        return Ok(p);
996    }
997    let roots = READ_ROOTS
998        .read()
999        .map(|r| r.clone())
1000        .unwrap_or_else(|e| e.into_inner().clone());
1001    let p = Path::new(raw);
1002    if p.is_absolute() {
1003        let joined = lexically_normalize(p);
1004        let mut probe = joined.as_path();
1005        let probe_c = loop {
1006            if let Ok(c) = fs.canonicalize(probe) {
1007                break Some(c);
1008            }
1009            match probe.parent() {
1010                Some(p) => probe = p,
1011                None => break None,
1012            }
1013        };
1014        if let Some(probe_c) = probe_c {
1015            for r in &roots {
1016                if let Ok(rc) = fs.canonicalize(r) {
1017                    if probe_c.starts_with(&rc) {
1018                        return Ok(joined);
1019                    }
1020                }
1021            }
1022        }
1023    }
1024    let extra = if roots.is_empty() {
1025        String::new()
1026    } else {
1027        let list: Vec<String> = roots.iter().map(|r| r.display().to_string()).collect();
1028        format!(" and {}", list.join(", "))
1029    };
1030    Err(format!(
1031        "path escapes the workspace: {raw}. This run can read the workspace{extra}. Do not look for another copy: if the task needs this path, say in your answer that it was not readable."
1032    ))
1033}
1034
1035/// Single-quote for `bash -lc`, so a pattern containing spaces, `$` or `"` is passed verbatim.
1036fn shell_quote(s: &str) -> String {
1037    format!("'{}'", s.replace('\'', r"'\''"))
1038}
1039
1040/// Optional accelerators worth telling the model about, because their presence changes strategy.
1041///
1042/// POSIX-guaranteed utilities (`sed`, `awk`, `find`, `xargs`, `grep`) are deliberately absent:
1043/// they are present everywhere, so listing them is noise in every prompt for no decision.
1044/// Pretty printers (bat, eza, dust, delta) and interactive tools are deliberately absent: their
1045/// colour, icons and pagers cost a model tokens it cannot use.
1046pub const ACCELERATORS: &[&str] = &["rg", "fd", "sd", "tokei", "jq", "ast-grep"];
1047
1048/// Language toolchains. Reported against what the REPOSITORY declares, not as a bare list --
1049/// "this is a Node project and `npm` is not reachable" is actionable; "npm: absent" is not.
1050pub const TOOLCHAINS: &[&str] = &[
1051    "git", "cargo", "go", "npm", "yarn", "pnpm", "python3", "pytest", "node", "make",
1052];
1053
1054/// What is reachable in the execution environment, probed through the seam.
1055pub fn available_binaries(shell: &dyn Shell, root: &Path) -> Result<Vec<String>, String> {
1056    let mut all: Vec<&'static str> = ACCELERATORS.to_vec();
1057    all.extend_from_slice(TOOLCHAINS);
1058    shell.available_binaries(root, &all)
1059}
1060
1061fn bash_description() -> String {
1062    format!(
1063        "Run a shell command in the workspace and wait for it to finish. \
1064         Commands run to completion (up to {}s). \
1065         A background job started with its output redirected keeps running after the command \
1066         returns, and nothing reports when it exits. \
1067         Output over {} lines is elided in the middle. \
1068         To find files or search file contents use the `glob` and `grep` tools, not \
1069         `find`, `grep -r` or `rg` in the shell; they respect .gitignore, are capped \
1070         and cannot hang.",
1071        COMMAND_TIMEOUT.as_secs(),
1072        OUTPUT_LINE_BUDGET
1073    )
1074}
1075
1076pub fn specs() -> Vec<ToolSpec> {
1077    let mut tools = vec![
1078        ToolSpec {
1079            name: "read".into(),
1080            description: "Read a file. Up to 2,000 lines (60,000 characters) come back in one call, so read whole files; pass start_line/end_line only for larger ones.".into(),
1081            parameters: json!({"type":"object","properties":{
1082                "path":{"type":"string"},
1083                "start_line":{"type":"integer","description":"1-indexed, inclusive"},
1084                "end_line":{"type":"integer","description":"1-indexed, inclusive"}},
1085                "required":["path"]}),
1086        },
1087        ToolSpec {
1088            name: "write".into(),
1089            description: "Create or overwrite a file with exact content.".into(),
1090            parameters: json!({"type":"object","properties":{
1091                "path":{"type":"string"},"content":{"type":"string"}},
1092                "required":["path","content"]}),
1093        },
1094        ToolSpec {
1095            name: "edit".into(),
1096            description: "Replace an exact, unique string in a file. Fails if absent or ambiguous."
1097                .into(),
1098            parameters: json!({"type":"object","properties":{
1099                "path":{"type":"string"},"old":{"type":"string"},"new":{"type":"string"}},
1100                "required":["path","old","new"]}),
1101        },
1102        ToolSpec {
1103            name: "bash".into(),
1104            description: bash_description(),
1105            parameters: if approval().is_some() {
1106                json!({
1107                    "type": "object",
1108                    "properties": {
1109                        "command": {"type": "string"},
1110                        "unsandboxed": {
1111                            "type": "boolean",
1112                            "description": "Run this one command outside the sandbox, with the user's network and credentials. It runs only if the user approves it."
1113                        },
1114                        "reason": {
1115                            "type": "string",
1116                            "description": "One line telling the user why the command must leave the sandbox."
1117                        }
1118                    },
1119                    "required": ["command"]
1120                })
1121            } else {
1122                json!({"type":"object","properties":{
1123                    "command":{"type":"string"}},"required":["command"]})
1124            },
1125        },
1126        ToolSpec {
1127            name: "glob".into(),
1128            description: "Find files by glob pattern, e.g. `src/**/*.rs`. Respects .gitignore; \
1129                          `.git` is skipped. Fast, and the right \
1130                          first move when you do not know where something lives."
1131                .into(),
1132            parameters: json!({"type":"object","properties":{
1133                "pattern":{"type":"string","description":"glob, relative to path (or the workspace)"},
1134                "path":{"type":"string","description":"directory to search under; defaults to the workspace; may be an absolute path under a read root"}},
1135                "required":["pattern"]}),
1136        },
1137        ToolSpec {
1138            name: "grep".into(),
1139            description: format!(
1140                "Search file contents by regular expression, returning `path:line:text`. \
1141                 Respects .gitignore. Use `glob` to find files by name and `grep` to find them \
1142                 by content. Capped at {MAX_MATCHES} matches, and the total is always reported."
1143            ),
1144            parameters: json!({"type":"object","properties":{
1145                "pattern":{"type":"string","description":"regular expression"},
1146                "path":{"type":"string","description":"subtree to search; defaults to the workspace"},
1147                "glob":{"type":"string","description":"restrict to files matching this glob, e.g. `*.ts`"}},
1148                "required":["pattern"]}),
1149        },
1150    ];
1151    if dispatch_cmd().is_some() {
1152        tools.push(ToolSpec {
1153            name: "dispatch".into(),
1154            description: "Delegate work to an implementer task on the host.".into(),
1155            parameters: json!({
1156                "type": "object",
1157                "properties": {
1158                    "task": {
1159                        "type": "string",
1160                        "description": "Task instructions for the implementer"
1161                    },
1162                    "gate": {
1163                        "type": "string",
1164                        "description": "Verification command that decides completion"
1165                    },
1166                    "max_seconds": {
1167                        "type": "integer",
1168                        "description": "Optional wall-clock limit in seconds"
1169                    }
1170                },
1171                "required": ["task", "gate"]
1172            }),
1173        });
1174    }
1175    if blyte_tool().is_some() {
1176        tools.push(ToolSpec {
1177            name: "blyte".into(),
1178            description: "Run one of blyte's own commands on the host: dispatch, wait, status, review, plan, init, clean, edit-start, edit-finish.".into(),
1179            parameters: json!({
1180                "type": "object",
1181                "properties": {
1182                    "args": {
1183                        "type": "array",
1184                        "items": {"type": "string"},
1185                        "description": "The words after `blyte`"
1186                    },
1187                    "background": {
1188                        "type": "boolean",
1189                        "description": "Start a `dispatch` in the background and return at once"
1190                    },
1191                    "task": {
1192                        "type": "string",
1193                        "description": "Task text for `dispatch`; blyte writes it to the tasks directory and passes that path"
1194                    }
1195                },
1196                "required": ["args"]
1197            }),
1198        });
1199    }
1200    if peer_tools().is_some() {
1201        tools.push(ToolSpec {
1202            name: "surfaces".into(),
1203            description: "List the surfaces running on this machine: name, repository, branch and what each is doing.".into(),
1204            parameters: json!({
1205                "type": "object",
1206                "properties": {}
1207            }),
1208        });
1209        tools.push(ToolSpec {
1210            name: "tell".into(),
1211            description: "Send a message to another running surface by name. Its model reads it between turns as a message from this surface, not from its user. Returns delivered or held.".into(),
1212            parameters: json!({
1213                "type": "object",
1214                "properties": {
1215                    "name": {
1216                        "type": "string",
1217                        "description": "Name of the target surface"
1218                    },
1219                    "message": {
1220                        "type": "string",
1221                        "description": "Message to send"
1222                    }
1223                },
1224                "required": ["name", "message"]
1225            }),
1226        });
1227    }
1228    if publish_tool().is_some() {
1229        tools.push(ToolSpec {
1230            name: "publish".into(),
1231            description: "Push a combined request's branch to origin and open a pull request against the default branch. Asks the user first only when blyte.toml has [surface] publish = \"ask\". Merging is never done by the surface.".into(),
1232            parameters: json!({
1233                "type": "object",
1234                "properties": {
1235                    "request": {
1236                        "type": "string",
1237                        "description": "Request id of this surface to publish"
1238                    },
1239                    "title": {
1240                        "type": "string",
1241                        "description": "Pull request title"
1242                    },
1243                    "body": {
1244                        "type": "string",
1245                        "description": "Pull request body"
1246                    }
1247                },
1248                "required": ["request", "title", "body"]
1249            }),
1250        });
1251    }
1252    if land_tool().is_some() {
1253        tools.push(ToolSpec {
1254            name: "land".into(),
1255            description: "Merge the pull request of a request you published into the default branch. Runs the repository's landing check first, then asks the user; nothing is merged unless the check passes and the user approves.".into(),
1256            parameters: json!({
1257                "type": "object",
1258                "properties": {
1259                    "request": {
1260                        "type": "string",
1261                        "description": "Request id of this surface to land"
1262                    }
1263                },
1264                "required": ["request"]
1265            }),
1266        });
1267    }
1268    tools
1269}
1270
1271/// The search command. ripgrep honours .gitignore, which keeps dependency and build trees out of
1272/// results; the grep fallback (used when a container has no rg) excludes them explicitly, or a
1273/// search over node_modules returns megabyte-long minified lines.
1274pub fn grep_command(use_rg: bool, pattern: &str, sub: &str, glob: &str) -> String {
1275    if use_rg {
1276        let globarg = if glob.is_empty() {
1277            String::new()
1278        } else {
1279            format!("--glob {}", shell_quote(glob))
1280        };
1281        format!(
1282            "rg --line-number --no-heading --color never {globarg} -e {} {} | head -n {}",
1283            shell_quote(pattern),
1284            shell_quote(sub),
1285            MAX_MATCHES + 1
1286        )
1287    } else {
1288        let globarg = if glob.is_empty() {
1289            String::new()
1290        } else {
1291            format!("--include={}", shell_quote(glob))
1292        };
1293        let excludes = ["node_modules", ".git", "target", ".venv", "dist", "build"]
1294            .iter()
1295            .map(|d| format!("--exclude-dir={d}"))
1296            .collect::<Vec<_>>()
1297            .join(" ");
1298        format!(
1299            "grep -rnIE {excludes} {globarg} -e {} {} | head -n {}",
1300            shell_quote(pattern),
1301            shell_quote(sub),
1302            MAX_MATCHES + 1
1303        )
1304    }
1305}
1306
1307/// Execute one tool call.
1308///
1309/// `shell` decides WHERE commands land -- host, container, remote. The tools never know, which
1310/// is the point: the previous harness encoded that in a prompt instruction and the worker
1311/// edited the host whenever the instruction went missing.
1312///
1313/// `fs` decides WHERE files live. Kept separate from `shell` because the two can differ: a
1314/// container with a bind-mounted workspace shares the conversation model's files while running its
1315/// own commands, and a remote sandbox shares neither. Pairing the wrong two would have the
1316/// model editing one filesystem and verifying another.
1317pub fn execute(
1318    root: &Path,
1319    shell: &dyn Shell,
1320    fs: &dyn Fs,
1321    name: &str,
1322    args: &Value,
1323) -> ToolOutcome {
1324    execute_with_timeout(root, shell, fs, name, args, command_ceiling(name, args))
1325}
1326
1327pub fn execute_with_timeout(
1328    root: &Path,
1329    shell: &dyn Shell,
1330    fs: &dyn Fs,
1331    name: &str,
1332    args: &Value,
1333    timeout: Duration,
1334) -> ToolOutcome {
1335    let ceiling = command_ceiling(name, args);
1336    let mut outcome = execute_unbounded(root, shell, fs, name, args, ceiling.min(timeout));
1337    outcome.content = if name == "read" {
1338        bound_output_with(&outcome.content, READ_LINE_BUDGET, READ_LINE_CHARS)
1339    } else if name == "grep" {
1340        bound_output_with(&outcome.content, OUTPUT_LINE_BUDGET, READ_LINE_CHARS)
1341    } else {
1342        bound_output_lines(&outcome.content, OUTPUT_LINE_BUDGET)
1343    };
1344    match crate::redact::Redactor::for_root(root) {
1345        Ok(redactor) => {
1346            outcome.content = redactor.apply(&outcome.content);
1347            outcome
1348        }
1349        Err(e) => ToolOutcome::err(e),
1350    }
1351}
1352
1353/// The tools themselves; `execute` bounds whatever they return.
1354fn execute_unbounded(
1355    root: &Path,
1356    shell: &dyn Shell,
1357    fs: &dyn Fs,
1358    name: &str,
1359    args: &Value,
1360    command_timeout: Duration,
1361) -> ToolOutcome {
1362    let s = |k: &str| {
1363        args.get(k)
1364            .and_then(|v| v.as_str())
1365            .unwrap_or_default()
1366            .to_string()
1367    };
1368    match name {
1369        "read" => {
1370            let path = match resolve_for_read(fs, root, &s("path")) {
1371                Ok(p) => p,
1372                Err(e) => return ToolOutcome::err(e),
1373            };
1374            if fs.is_local() {
1375                match crate::sandbox::is_protected_read(&path) {
1376                    Ok(true) => return ToolOutcome::err(protected_read_refusal("read", &path)),
1377                    Ok(false) => {}
1378                    Err(e) => return ToolOutcome::err(e),
1379                }
1380            }
1381            let body = match fs.read(&path) {
1382                Ok(b) => b,
1383                Err(e) => return ToolOutcome::err(e),
1384            };
1385            let lines: Vec<&str> = body.lines().collect();
1386            let start = args
1387                .get("start_line")
1388                .and_then(|v| v.as_u64())
1389                .unwrap_or(1)
1390                .max(1) as usize;
1391            // A read from the top of a file that fits comes back whole, whatever end_line says:
1392            // models page from line 1 out of habit (a shadow run read 700 lines as six 200-line
1393            // calls). A range starting later is a deliberate re-read and is honoured.
1394            let fits = lines.len() <= READ_LINE_BUDGET && body.chars().count() <= MAX_OUTPUT_CHARS;
1395            let end = if start == 1 && fits {
1396                lines.len()
1397            } else {
1398                args.get("end_line")
1399                    .and_then(|v| v.as_u64())
1400                    .map(|e| e as usize)
1401                    .unwrap_or(lines.len())
1402                    .min(lines.len())
1403            };
1404            if start > lines.len() {
1405                return ToolOutcome::err(format!(
1406                    "{} has {} lines; start_line {start} is past the end",
1407                    s("path"),
1408                    lines.len()
1409                ));
1410            }
1411            if end < start {
1412                return ToolOutcome::err(format!(
1413                    "end_line {end} is before start_line {start} in {}",
1414                    s("path")
1415                ));
1416            }
1417            // Numbered, because an agent that cannot cite a line cannot edit precisely.
1418            let body = lines[start - 1..end]
1419                .iter()
1420                .enumerate()
1421                .map(|(i, l)| format!("{:>6}\t{l}", start + i))
1422                .collect::<Vec<_>>()
1423                .join("\n");
1424            ToolOutcome::ok(distil(&body, READ_LINE_BUDGET))
1425        }
1426        "write" => {
1427            let raw_path = s("path");
1428            let path = match resolve_in_workspace(fs, root, &raw_path) {
1429                Ok(p) => p,
1430                Err(e) => return ToolOutcome::err(e),
1431            };
1432            if let Err(e) = check_protected_write(fs, root, "write", &raw_path, &path) {
1433                return ToolOutcome::err(e);
1434            }
1435            if let Err(e) = check_in_place_lock(fs, root, &path) {
1436                return ToolOutcome::err(e);
1437            }
1438            if let Err(e) = check_write_scope(fs, "write", &path) {
1439                return ToolOutcome::err(e);
1440            }
1441            match fs.write(&path, &s("content")) {
1442                Ok(_) => ToolOutcome::ok(format!("wrote {raw_path}")),
1443                Err(e) => ToolOutcome::err(e),
1444            }
1445        }
1446        "edit" => {
1447            let raw_path = s("path");
1448            let path = match resolve_in_workspace(fs, root, &raw_path) {
1449                Ok(p) => p,
1450                Err(e) => return ToolOutcome::err(e),
1451            };
1452            if let Err(e) = check_protected_write(fs, root, "edit", &raw_path, &path) {
1453                return ToolOutcome::err(e);
1454            }
1455            if let Err(e) = check_in_place_lock(fs, root, &path) {
1456                return ToolOutcome::err(e);
1457            }
1458            if let Err(e) = check_write_scope(fs, "edit", &path) {
1459                return ToolOutcome::err(e);
1460            }
1461            let body = match fs.read(&path) {
1462                Ok(b) => b,
1463                Err(e) => return ToolOutcome::err(e),
1464            };
1465            let (old, new) = (s("old"), s("new"));
1466            match body.matches(&old).count() {
1467                0 => ToolOutcome::err(format!("`old` not found in {}. Read it first.", s("path"))),
1468                // Ambiguity is an error, never a guess: replacing the first of several matches
1469                // silently edits the wrong place and the agent cannot tell.
1470                n if n > 1 => ToolOutcome::err(format!(
1471                    "`old` appears {n} times in {}; include more context to make it unique",
1472                    s("path")
1473                )),
1474                _ => match fs.write(&path, &body.replacen(&old, &new, 1)) {
1475                    Ok(_) => ToolOutcome::ok(format!("edited {}", s("path"))),
1476                    Err(e) => ToolOutcome::err(e),
1477                },
1478            }
1479        }
1480        "bash" => {
1481            let command = s("command");
1482            let unsandboxed = args
1483                .get("unsandboxed")
1484                .and_then(|v| v.as_bool())
1485                .unwrap_or(false);
1486            if unsandboxed {
1487                let Some(cfg) = approval() else {
1488                    return ToolOutcome::err("this run cannot run commands outside the sandbox");
1489                };
1490                let reason_raw = s("reason");
1491                let reason = reason_raw.trim();
1492                if reason.is_empty() {
1493                    return ToolOutcome::err("give a one-line reason with an unsandboxed command");
1494                }
1495                let banner = if let Some(rule) = matching_rule(&command, &cfg.rules) {
1496                    format!("ran outside the sandbox (allowed by rule \"{rule}\")")
1497                } else {
1498                    match cfg.approver.ask(&command, reason) {
1499                        Approval::Approved => {
1500                            "ran outside the sandbox (approved by the user)".to_string()
1501                        }
1502                        Approval::Denied => {
1503                            return ToolOutcome::err(
1504                                "the user refused this command; it was not run. Do not try to run it another way.",
1505                            );
1506                        }
1507                        Approval::Unavailable => {
1508                            return ToolOutcome::err(
1509                                "nobody can approve a command in this run, so it was not run",
1510                            );
1511                        }
1512                    }
1513                };
1514                match shell.exec_host(&command, root, command_timeout) {
1515                    Ok(o) => {
1516                        let body = distil(o.merged().trim_end(), OUTPUT_LINE_BUDGET);
1517                        ToolOutcome {
1518                            content: format!("{banner}\nexit {}\n{body}", o.exit_code),
1519                            is_error: o.exit_code != 0,
1520                        }
1521                    }
1522                    Err(e) => ToolOutcome::err(e),
1523                }
1524            } else {
1525                match shell.exec_user(&command, root, command_timeout) {
1526                    Ok(o) => {
1527                        let body = distil(o.merged().trim_end(), OUTPUT_LINE_BUDGET);
1528                        ToolOutcome {
1529                            content: format!("exit {}\n{body}", o.exit_code),
1530                            is_error: o.exit_code != 0,
1531                        }
1532                    }
1533                    Err(e) => ToolOutcome::err(e),
1534                }
1535            }
1536        }
1537        "glob" => {
1538            let pattern = s("pattern");
1539            let raw_path = s("path");
1540            let sub = if raw_path.is_empty() { "." } else { &raw_path };
1541            let dir = match resolve_for_read(fs, root, sub) {
1542                Ok(d) => d,
1543                Err(e) => return ToolOutcome::err(e),
1544            };
1545            if fs.is_local() {
1546                match crate::sandbox::is_protected_read(&dir) {
1547                    Ok(true) => return ToolOutcome::err(protected_read_refusal("glob", &dir)),
1548                    Ok(false) => {}
1549                    Err(e) => return ToolOutcome::err(e),
1550                }
1551            }
1552            let outcome = |hits: Vec<String>, skipped: usize| {
1553                let text = if hits.is_empty() {
1554                    format!("no files match {pattern}")
1555                } else {
1556                    let shown: Vec<String> = if raw_path.is_empty() {
1557                        hits
1558                    } else {
1559                        let base = Path::new(&raw_path);
1560                        hits.into_iter()
1561                            .map(|h| base.join(h).to_string_lossy().into_owned())
1562                            .collect()
1563                    };
1564                    format!("{} file(s):\n{}", shown.len(), shown.join("\n"))
1565                };
1566                ToolOutcome::ok(append_skipped_line(text, skipped))
1567            };
1568            if fs.is_local() {
1569                match crate::search::glob_paths_checked(&dir, &pattern, MAX_MATCHES) {
1570                    Ok(Some(res)) => return outcome(res.hits, res.skipped),
1571                    Ok(None) => {}
1572                    Err(e) => return ToolOutcome::err(e),
1573                }
1574            } else if let Ok(o) = shell.exec(
1575                "if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then \
1576                 git -c core.quotePath=off -c core.fsmonitor=false ls-files -co --exclude-standard; \
1577                 else echo __BLYTE_NO_GIT__; fi",
1578                &dir,
1579                command_timeout,
1580            ) {
1581                if o.exit_code == 0 && !o.stdout.starts_with("__BLYTE_NO_GIT__") {
1582                    if let Some(hits) = crate::search::glob_filter(&o.stdout, &pattern, MAX_MATCHES)
1583                    {
1584                        return outcome(hits, 0);
1585                    }
1586                }
1587            }
1588            let cmd = format!(
1589                "if shopt -s globstar 2>/dev/null; then \
1590                     shopt -s nullglob dotglob 2>/dev/null; \
1591                     printf '%s\\n' {pattern}; \
1592                 elif command -v zsh >/dev/null 2>&1; then \
1593                     zsh -c 'setopt null_glob glob_dots 2>/dev/null; printf \"%s\\n\" {pattern}'; \
1594                 else \
1595                     shopt -s nullglob dotglob 2>/dev/null; \
1596                     printf '%s\\n' {pattern}; \
1597                 fi | head -n {MAX_MATCHES}"
1598            );
1599            match shell.exec(&cmd, &dir, command_timeout) {
1600                Ok(o) => {
1601                    let raw_hits: Vec<String> = o
1602                        .stdout
1603                        .lines()
1604                        .filter(|l| !l.trim().is_empty())
1605                        .map(String::from)
1606                        .collect();
1607                    if fs.is_local() {
1608                        let protected = match crate::sandbox::protected_read_paths() {
1609                            Ok(p) => p,
1610                            Err(e) => return ToolOutcome::err(e),
1611                        };
1612                        let mut hits = Vec::with_capacity(raw_hits.len());
1613                        let mut skipped = 0usize;
1614                        for hit in raw_hits {
1615                            let full = dir.join(&hit);
1616                            match crate::sandbox::is_protected_read_with(&full, &protected) {
1617                                Ok(true) => skipped += 1,
1618                                Ok(false) => hits.push(hit),
1619                                Err(e) => return ToolOutcome::err(e),
1620                            }
1621                        }
1622                        outcome(hits, skipped)
1623                    } else {
1624                        outcome(raw_hits, 0)
1625                    }
1626                }
1627                Err(e) => ToolOutcome::err(format!("glob failed: {e}")),
1628            }
1629        }
1630        "grep" => {
1631            let pattern = s("pattern");
1632            let sub = {
1633                let p = s("path");
1634                if p.is_empty() {
1635                    ".".to_string()
1636                } else {
1637                    p
1638                }
1639            };
1640            let search_root = match resolve_for_read(fs, root, &sub) {
1641                Ok(p) => p,
1642                Err(e) => return ToolOutcome::err(e),
1643            };
1644            if fs.is_local() {
1645                match crate::sandbox::is_protected_read(&search_root) {
1646                    Ok(true) => {
1647                        return ToolOutcome::err(protected_read_refusal("grep", &search_root))
1648                    }
1649                    Ok(false) => {}
1650                    Err(e) => return ToolOutcome::err(e),
1651                }
1652            }
1653            let glob_str = s("glob");
1654            let (lines, skipped): (Vec<String>, usize) = if fs.is_local() {
1655                match crate::search::grep_lines_checked(
1656                    root,
1657                    &sub,
1658                    &pattern,
1659                    &glob_str,
1660                    MAX_MATCHES + 1,
1661                ) {
1662                    Ok(res) => (res.hits, res.skipped),
1663                    Err(e) => return ToolOutcome::err(format!("grep failed: {e}")),
1664                }
1665            } else {
1666                let cmd = format!(
1667                    "if command -v rg >/dev/null 2>&1; then {}; else {}; fi",
1668                    grep_command(true, &pattern, &sub, &glob_str),
1669                    grep_command(false, &pattern, &sub, &glob_str)
1670                );
1671                match shell.exec(&cmd, root, command_timeout) {
1672                    Ok(o) => (
1673                        o.stdout
1674                            .lines()
1675                            .filter(|l| !l.trim().is_empty())
1676                            .map(String::from)
1677                            .collect(),
1678                        0,
1679                    ),
1680                    Err(e) => return ToolOutcome::err(format!("grep failed: {e}")),
1681                }
1682            };
1683            if lines.is_empty() {
1684                return ToolOutcome::ok(append_skipped_line(
1685                    format!("no matches for {pattern}"),
1686                    skipped,
1687                ));
1688            }
1689            let pattern_re = regex::Regex::new(&pattern).ok();
1690            let lines: Vec<String> = lines
1691                .into_iter()
1692                .map(|line| {
1693                    if line.chars().count() <= MAX_LINE_CHARS {
1694                        return line;
1695                    }
1696                    let Some(ref re) = pattern_re else {
1697                        return line;
1698                    };
1699                    let (prefix, rest) = split_grep_prefix(&line);
1700                    let found: Vec<(usize, usize)> =
1701                        re.find_iter(rest).map(|m| (m.start(), m.end())).collect();
1702                    if found.is_empty() {
1703                        line
1704                    } else {
1705                        format!("{prefix}{}", excerpt_matches(rest, &found, MAX_LINE_CHARS))
1706                    }
1707                })
1708                .collect();
1709            if lines.len() > MAX_MATCHES {
1710                ToolOutcome::ok(append_skipped_line(
1711                    format!(
1712                        "{}\n\n[capped at {MAX_MATCHES} matches; narrow the pattern or pass `glob` \
1713                         to see the rest]",
1714                        lines[..MAX_MATCHES].join("\n")
1715                    ),
1716                    skipped,
1717                ))
1718            } else {
1719                ToolOutcome::ok(append_skipped_line(
1720                    format!("{} match(es):\n{}", lines.len(), lines.join("\n")),
1721                    skipped,
1722                ))
1723            }
1724        }
1725        "dispatch" => {
1726            let Some(cmd) = dispatch_cmd() else {
1727                return ToolOutcome::err("unknown tool: dispatch");
1728            };
1729            let json_bytes = match serialize_dispatch_args(args) {
1730                Ok(bytes) => bytes,
1731                Err(msg) => return ToolOutcome::err(msg),
1732            };
1733            let parent_session = dispatch_parent_session();
1734            let mut cmd_builder = std::process::Command::new("sh");
1735            cmd_builder
1736                .arg("-c")
1737                .arg(&cmd)
1738                .env("BLYTE_DISPATCH_PARENT", &parent_session)
1739                .stdin(std::process::Stdio::piped())
1740                .stdout(std::process::Stdio::piped())
1741                .stderr(std::process::Stdio::piped());
1742            if root.is_dir() {
1743                cmd_builder.current_dir(root);
1744            }
1745            let mut child = match cmd_builder.spawn() {
1746                Ok(c) => c,
1747                Err(e) => return ToolOutcome::err(format!("dispatch failed to spawn: {e}")),
1748            };
1749
1750            let Some(mut stdin) = child.stdin.take() else {
1751                let _ = child.kill();
1752                let _ = child.wait();
1753                return ToolOutcome::err("dispatch failed: stdin pipe unavailable");
1754            };
1755            let write_err = std::io::Write::write_all(&mut stdin, &json_bytes).err();
1756            drop(stdin);
1757
1758            match (write_err, child.wait_with_output()) {
1759                (None, Ok(output)) if output.status.success() => {
1760                    let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
1761                    ToolOutcome::ok(stdout)
1762                }
1763                (None, Ok(output)) => ToolOutcome::err(format_dispatch_failure(&output)),
1764                (None, Err(e)) => ToolOutcome::err(format!("dispatch command failed: {e}")),
1765                (Some(write_err), Ok(output)) if output.status.success() => ToolOutcome::err(
1766                    format!("dispatch failed to write arguments to stdin: {write_err}"),
1767                ),
1768                (Some(write_err), Ok(output)) => ToolOutcome::err(format!(
1769                    "{}\ndispatch also failed to write arguments to stdin: {write_err}",
1770                    format_dispatch_failure(&output)
1771                )),
1772                (Some(write_err), Err(wait_err)) => ToolOutcome::err(format!(
1773                    "dispatch failed to write arguments to stdin: {write_err}; dispatch command also failed: {wait_err}"
1774                )),
1775            }
1776        }
1777        "blyte" => {
1778            let Some(exe) = blyte_tool() else {
1779                return ToolOutcome::err("unknown tool: blyte");
1780            };
1781            let cmd_args: Vec<String> = match args.get("args").and_then(|v| v.as_array()) {
1782                Some(arr) => {
1783                    let mut out = Vec::with_capacity(arr.len());
1784                    for item in arr {
1785                        match item.as_str() {
1786                            Some(s) => out.push(s.to_string()),
1787                            None => return ToolOutcome::err("args must be an array of strings"),
1788                        }
1789                    }
1790                    out
1791                }
1792                None => Vec::new(),
1793            };
1794            let Some(first) = cmd_args.first().map(|s| s.as_str()) else {
1795                return ToolOutcome::err(format!(
1796                    "the blyte tool runs only: {}",
1797                    BLYTE_TOOL_COMMANDS.join(", ")
1798                ));
1799            };
1800            if let Some(refused) = refused_blyte_tool_command(&cmd_args) {
1801                return ToolOutcome::err(crate::shell::model_shell_refusal_message(refused));
1802            }
1803            let is_repo = crate::sandbox::is_git_repository(root);
1804            if !is_repo {
1805                if NO_REPO_REFUSED_COMMANDS.contains(&first) {
1806                    return ToolOutcome::err(NO_REPO_BLYTE_COMMAND_ERROR);
1807                }
1808                if !BLYTE_TOOL_NO_REPO_COMMANDS.contains(&first) {
1809                    return ToolOutcome::err(format!(
1810                        "the blyte tool runs only: {}",
1811                        BLYTE_TOOL_NO_REPO_COMMANDS.join(", ")
1812                    ));
1813                }
1814            } else if !BLYTE_TOOL_COMMANDS.contains(&first) {
1815                return ToolOutcome::err(format!(
1816                    "the blyte tool runs only: {}",
1817                    BLYTE_TOOL_COMMANDS.join(", ")
1818                ));
1819            }
1820            let background = args
1821                .get("background")
1822                .and_then(|v| v.as_bool())
1823                .unwrap_or(false);
1824            if background && first != "dispatch" {
1825                return ToolOutcome::err("only dispatch can run in the background");
1826            }
1827            let task_text: Option<&str> = match args.get("task") {
1828                None | Some(Value::Null) => None,
1829                Some(v) => match v.as_str() {
1830                    Some(s) => Some(s),
1831                    None => return ToolOutcome::err("task must be a string"),
1832                },
1833            };
1834            if task_text.is_some() && first != "dispatch" {
1835                return ToolOutcome::err("task can only be passed with dispatch");
1836            }
1837
1838            let mut exec_args = cmd_args.clone();
1839            let mut dispatch_id: Option<String> = None;
1840            let mut background_out_dir: Option<PathBuf> = None;
1841            if matches!(first, "dispatch" | "edit-finish") {
1842                if cmd_args
1843                    .iter()
1844                    .skip(1)
1845                    .any(|a| a == "--request" || a.starts_with("--request="))
1846                {
1847                    return ToolOutcome::err("do not pass --request; blyte sets it automatically");
1848                }
1849                if cmd_args
1850                    .iter()
1851                    .skip(1)
1852                    .any(|a| a == "--surface" || a.starts_with("--surface="))
1853                {
1854                    return ToolOutcome::err("do not pass --surface; blyte sets it automatically");
1855                }
1856                if cmd_args
1857                    .iter()
1858                    .skip(1)
1859                    .any(|a| a == "--started-by" || a.starts_with("--started-by="))
1860                {
1861                    return ToolOutcome::err(
1862                        "do not pass --started-by; blyte sets it automatically",
1863                    );
1864                }
1865                if first == "dispatch" {
1866                    if let Some(opt) = refused_dispatch_option(&cmd_args) {
1867                        return ToolOutcome::err(refused_dispatch_option_message(opt));
1868                    }
1869                    let parsed = parse_dispatch_args(&cmd_args);
1870                    if background {
1871                        let out_dir = if is_repo {
1872                            root.join(".wt")
1873                        } else {
1874                            let Some(store) = blyte_run_store() else {
1875                                return ToolOutcome::err(
1876                                    "run store is not configured for background dispatch outside a git repository",
1877                                );
1878                            };
1879                            store
1880                        };
1881                        background_out_dir = Some(out_dir);
1882                    }
1883                    if let Some(text) = task_text {
1884                        if text.trim().is_empty() {
1885                            return ToolOutcome::err("task must not be empty");
1886                        }
1887                        if parsed.has_plan || parsed.has_plan_task {
1888                            return ToolOutcome::err("do not pass task with --plan or --plan-task");
1889                        }
1890                        if parsed.has_task_file {
1891                            return ToolOutcome::err("do not pass both task and a task file path");
1892                        }
1893                        let Some((id_idx, ref id)) = parsed.id else {
1894                            return ToolOutcome::err("dispatch needs an id");
1895                        };
1896                        if id.is_empty() {
1897                            return ToolOutcome::err("dispatch needs an id");
1898                        }
1899                        let tasks_dir = if is_repo {
1900                            root.join(".wt").join("tasks")
1901                        } else {
1902                            let Some(dir) = blyte_tasks_dir() else {
1903                                return ToolOutcome::err(
1904                                    "tasks directory is not configured for dispatch outside a git repository",
1905                                );
1906                            };
1907                            dir
1908                        };
1909                        let task_path = match write_inline_task(&tasks_dir, id, text) {
1910                            Ok(p) => p,
1911                            Err(e) => return ToolOutcome::err(e),
1912                        };
1913                        exec_args.insert(id_idx + 1, task_path.to_string_lossy().into_owned());
1914                    }
1915                    dispatch_id = parsed.id.map(|(_, id)| id).filter(|id| !id.is_empty());
1916                }
1917                if let Some(req_id) = blyte_request() {
1918                    if let Some(pos) = exec_args.iter().position(|a| a == "--") {
1919                        exec_args.insert(pos, req_id);
1920                        exec_args.insert(pos, "--request".to_string());
1921                    } else {
1922                        exec_args.push("--request".to_string());
1923                        exec_args.push(req_id);
1924                    }
1925                }
1926                if let Some(surface_id) = blyte_surface() {
1927                    if let Some(pos) = exec_args.iter().position(|a| a == "--") {
1928                        exec_args.insert(pos, surface_id);
1929                        exec_args.insert(pos, "--surface".to_string());
1930                    } else {
1931                        exec_args.push("--surface".to_string());
1932                        exec_args.push(surface_id);
1933                    }
1934                }
1935                if let Some(started_by) = blyte_started_by() {
1936                    if let Some(pos) = exec_args.iter().position(|a| a == "--") {
1937                        exec_args.insert(pos, started_by);
1938                        exec_args.insert(pos, "--started-by".to_string());
1939                    } else {
1940                        exec_args.push("--started-by".to_string());
1941                        exec_args.push(started_by);
1942                    }
1943                }
1944            }
1945
1946            let parent_session = dispatch_parent_session();
1947            let mut cmd_builder = std::process::Command::new(&exe);
1948            cmd_builder
1949                .args(&exec_args)
1950                .env("BLYTE_DISPATCH_PARENT", &parent_session)
1951                .env_remove(crate::shell::MODEL_SHELL_ENV)
1952                .stdin(std::process::Stdio::null());
1953            if root.is_dir() {
1954                cmd_builder.current_dir(root);
1955            }
1956
1957            if background {
1958                let Some(id) = dispatch_id else {
1959                    return ToolOutcome::err("dispatch needs an id");
1960                };
1961                if let Err(e) = validate_dispatch_id(&id) {
1962                    return ToolOutcome::err(e);
1963                }
1964                let Some(out_dir) = background_out_dir else {
1965                    return ToolOutcome::err(
1966                        "run store is not configured for background dispatch outside a git repository",
1967                    );
1968                };
1969                return run_background_dispatch(cmd_builder, &out_dir, &id);
1970            }
1971
1972            match run_command_bounded(cmd_builder, command_timeout) {
1973                Ok((0, stdout, _stderr)) => ToolOutcome::ok(stdout),
1974                Ok((2, stdout, stderr)) if first == "wait" => {
1975                    let lines: Vec<&str> = stderr.lines().collect();
1976                    let tail = if lines.len() > OUTPUT_LINE_BUDGET {
1977                        lines[lines.len() - OUTPUT_LINE_BUDGET..].join("\n")
1978                    } else {
1979                        stderr.trim_end().to_string()
1980                    };
1981                    let mut parts = vec!["still waiting".to_string()];
1982                    if !stdout.trim().is_empty() {
1983                        parts.push(stdout.trim_end().to_string());
1984                    }
1985                    if !tail.trim().is_empty() {
1986                        parts.push(tail);
1987                    }
1988                    ToolOutcome::ok(parts.join("\n"))
1989                }
1990                Ok((code, stdout, stderr)) => {
1991                    let lines: Vec<&str> = stderr.lines().collect();
1992                    let tail = if lines.len() > OUTPUT_LINE_BUDGET {
1993                        lines[lines.len() - OUTPUT_LINE_BUDGET..].join("\n")
1994                    } else {
1995                        stderr.trim_end().to_string()
1996                    };
1997                    let mut parts = vec![format!("exit {code}")];
1998                    if !stdout.trim().is_empty() {
1999                        parts.push(stdout.trim_end().to_string());
2000                    }
2001                    if !tail.trim().is_empty() {
2002                        parts.push(tail);
2003                    }
2004                    ToolOutcome::err(parts.join("\n"))
2005                }
2006                Err(e) => ToolOutcome::err(e),
2007            }
2008        }
2009        "surfaces" => {
2010            let Some(peer) = peer_tools() else {
2011                return ToolOutcome::err("the surfaces tool is not available here");
2012            };
2013            match peer.surfaces() {
2014                Ok(text) => ToolOutcome::ok(text),
2015                Err(text) => ToolOutcome::err(text),
2016            }
2017        }
2018        "tell" => {
2019            let Some(peer) = peer_tools() else {
2020                return ToolOutcome::err("the tell tool is not available here");
2021            };
2022            let Some(target) = args
2023                .get("name")
2024                .and_then(|v| v.as_str())
2025                .filter(|v| !v.trim().is_empty())
2026            else {
2027                return ToolOutcome::err("tell needs a name and a message");
2028            };
2029            let Some(message) = args
2030                .get("message")
2031                .and_then(|v| v.as_str())
2032                .filter(|v| !v.trim().is_empty())
2033            else {
2034                return ToolOutcome::err("tell needs a name and a message");
2035            };
2036            match peer.tell(target, message) {
2037                Ok(text) => ToolOutcome::ok(text),
2038                Err(text) => ToolOutcome::err(text),
2039            }
2040        }
2041        "publish" => {
2042            let Some(tool) = publish_tool() else {
2043                return ToolOutcome::err("the publish tool is not available here");
2044            };
2045            if !crate::sandbox::is_git_repository(root) {
2046                return ToolOutcome::err(NOT_A_GIT_REPOSITORY_ERROR);
2047            }
2048            if let Some(started_by) = blyte_started_by() {
2049                return ToolOutcome::err(format!(
2050                    "cannot publish during a turn started by another surface ({started_by})"
2051                ));
2052            }
2053            let Some(obj) = args.as_object() else {
2054                return ToolOutcome::err("publish arguments must be an object");
2055            };
2056            for key in obj.keys() {
2057                if !matches!(key.as_str(), "request" | "title" | "body") {
2058                    return ToolOutcome::err(format!("publish does not accept field {key}"));
2059                }
2060            }
2061            let Some(request) = obj
2062                .get("request")
2063                .and_then(|v| v.as_str())
2064                .filter(|v| !v.trim().is_empty())
2065            else {
2066                return ToolOutcome::err("publish needs a non-empty request");
2067            };
2068            let Some(title) = obj.get("title").and_then(|v| v.as_str()) else {
2069                return ToolOutcome::err("publish needs a title");
2070            };
2071            let Some(body) = obj.get("body").and_then(|v| v.as_str()) else {
2072                return ToolOutcome::err("publish needs a body");
2073            };
2074            if title.trim().is_empty() {
2075                return ToolOutcome::err("publish title must not be blank");
2076            }
2077            if title.chars().count() > PUBLISH_TITLE_MAX_CHARS {
2078                return ToolOutcome::err(format!(
2079                    "publish title must be at most {PUBLISH_TITLE_MAX_CHARS} characters"
2080                ));
2081            }
2082            if body.len() > PUBLISH_BODY_MAX_BYTES {
2083                return ToolOutcome::err(format!(
2084                    "publish body must be at most {PUBLISH_BODY_MAX_BYTES} bytes"
2085                ));
2086            }
2087            match tool.publish(request, title.trim(), body) {
2088                Ok(text) => ToolOutcome::ok(text),
2089                Err(text) => ToolOutcome::err(text),
2090            }
2091        }
2092        "land" => {
2093            let Some(tool) = land_tool() else {
2094                return ToolOutcome::err("the land tool is not available here");
2095            };
2096            if !crate::sandbox::is_git_repository(root) {
2097                return ToolOutcome::err(NOT_A_GIT_REPOSITORY_ERROR);
2098            }
2099            if let Some(started_by) = blyte_started_by() {
2100                return ToolOutcome::err(format!(
2101                    "cannot land during a turn started by another surface ({started_by})"
2102                ));
2103            }
2104            let Some(obj) = args.as_object() else {
2105                return ToolOutcome::err("land arguments must be an object");
2106            };
2107            for key in obj.keys() {
2108                if key != "request" {
2109                    return ToolOutcome::err(format!("land does not accept field {key}"));
2110                }
2111            }
2112            let Some(request) = obj
2113                .get("request")
2114                .and_then(|v| v.as_str())
2115                .filter(|v| !v.trim().is_empty())
2116            else {
2117                return ToolOutcome::err("land needs a non-empty request");
2118            };
2119            match tool.land(request) {
2120                Ok(text) => ToolOutcome::ok(text),
2121                Err(text) => ToolOutcome::err(text),
2122            }
2123        }
2124        other => ToolOutcome::err(format!("unknown tool: {other}")),
2125    }
2126}
2127
2128const NOT_A_GIT_REPOSITORY_ERROR: &str = "this folder is not a git repository, and direct edits, combining and publishing need one. If the user wants a repository here, ask to run \"git init\" and then an empty first commit (git commit --allow-empty) with the bash tool and unsandboxed: true; the user approves each command. Add only the files the user names afterwards, never \"git add -A\": the folder may hold credentials.";
2129const NO_REPO_BLYTE_COMMAND_ERROR: &str = "this folder is not a git repository; here the blyte tool runs only dispatch, wait, status and review. `blyte undo <id>` is for the user to run. Other commands need a git repository (run `git init` and an empty first commit only when the user wants one).";
2130const BACKGROUND_STARTUP_WAIT: Duration = Duration::from_secs(2);
2131const BACKGROUND_STARTUP_POLL: Duration = Duration::from_millis(50);
2132
2133struct ParsedDispatchArgs {
2134    id: Option<(usize, String)>,
2135    has_task_file: bool,
2136    has_plan: bool,
2137    has_plan_task: bool,
2138}
2139
2140fn parse_dispatch_args(cmd_args: &[String]) -> ParsedDispatchArgs {
2141    let mut i = 1;
2142    let mut after_dd = false;
2143    let mut id: Option<(usize, String)> = None;
2144    let mut has_task_file = false;
2145    let mut has_plan = false;
2146    let mut has_plan_task = false;
2147    while i < cmd_args.len() {
2148        let arg = &cmd_args[i];
2149        if !after_dd {
2150            if arg == "--" {
2151                after_dd = true;
2152                i += 1;
2153                continue;
2154            }
2155            if arg == "--plan" || arg.starts_with("--plan=") {
2156                has_plan = true;
2157            }
2158            if arg == "--plan-task" || arg.starts_with("--plan-task=") {
2159                has_plan_task = true;
2160            }
2161            if DISPATCH_VALUE_FLAGS.contains(&arg.as_str()) {
2162                i += 2;
2163                continue;
2164            }
2165            if arg.starts_with('-') && arg != "-" {
2166                i += 1;
2167                continue;
2168            }
2169        }
2170        if id.is_none() {
2171            id = Some((i, arg.clone()));
2172        } else {
2173            has_task_file = true;
2174        }
2175        i += 1;
2176    }
2177    ParsedDispatchArgs {
2178        id,
2179        has_task_file,
2180        has_plan,
2181        has_plan_task,
2182    }
2183}
2184
2185fn validate_dispatch_id(id: &str) -> Result<(), String> {
2186    if id.is_empty()
2187        || id == "."
2188        || id == ".."
2189        || id.contains('/')
2190        || id.contains('\\')
2191        || id.contains('\0')
2192    {
2193        return Err(format!("invalid dispatch id: {id}"));
2194    }
2195    Ok(())
2196}
2197
2198fn write_inline_task(tasks_dir: &Path, id: &str, text: &str) -> Result<PathBuf, String> {
2199    validate_dispatch_id(id)?;
2200    let task_path = tasks_dir.join(format!("{id}.md"));
2201    if let Err(e) = std::fs::create_dir_all(tasks_dir) {
2202        return Err(format!(
2203            "cannot create tasks directory {} for {}: {e}",
2204            tasks_dir.display(),
2205            task_path.display()
2206        ));
2207    }
2208    match std::fs::read_to_string(&task_path) {
2209        Ok(existing) => {
2210            if existing != text {
2211                return Err(format!(
2212                    "task file {} already exists with different content",
2213                    task_path.display()
2214                ));
2215            }
2216            Ok(task_path)
2217        }
2218        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
2219            std::fs::write(&task_path, text)
2220                .map_err(|we| format!("cannot write task file {}: {we}", task_path.display()))?;
2221            Ok(task_path)
2222        }
2223        Err(e) => Err(format!(
2224            "cannot read existing task file {}: {e}",
2225            task_path.display()
2226        )),
2227    }
2228}
2229
2230fn check_in_place_lock(fs: &dyn Fs, root: &Path, path: &Path) -> Result<(), String> {
2231    if !fs.is_local() || crate::sandbox::is_git_repository(root) {
2232        return Ok(());
2233    }
2234    let root_c = fs
2235        .canonicalize(root)
2236        .map_err(|e| format!("workspace root unreadable: {e}"))?;
2237    let real_target = resolve_real_target(fs, path)?;
2238    if !real_target.starts_with(&root_c) {
2239        return Ok(());
2240    }
2241    let lock_path = match in_place_lock_path() {
2242        Some(p) => p,
2243        None if blyte_tool().is_some() => {
2244            return Err(
2245                "in-place lock path is not configured for writing outside a git repository"
2246                    .to_string(),
2247            );
2248        }
2249        None => return Ok(()),
2250    };
2251    match crate::folder_lock::holder(&lock_path)? {
2252        Some(holder) => Err(format!(
2253            "run {} is editing this folder; wait for it to finish",
2254            holder.id
2255        )),
2256        None => Ok(()),
2257    }
2258}
2259
2260fn run_background_dispatch(
2261    mut cmd_builder: std::process::Command,
2262    out_dir: &Path,
2263    id: &str,
2264) -> ToolOutcome {
2265    let startup_wait = match background_startup_wait() {
2266        Ok(d) => d,
2267        Err(e) => return ToolOutcome::err(e),
2268    };
2269    let out_path = out_dir.join(format!("{id}.dispatch.out"));
2270    if let Err(e) = std::fs::create_dir_all(out_dir) {
2271        return ToolOutcome::err(format!(
2272            "cannot create {} for {}: {e}",
2273            out_dir.display(),
2274            out_path.display()
2275        ));
2276    }
2277    let out_file = match std::fs::OpenOptions::new()
2278        .create(true)
2279        .write(true)
2280        .truncate(true)
2281        .open(&out_path)
2282    {
2283        Ok(f) => f,
2284        Err(e) => {
2285            return ToolOutcome::err(format!("cannot open {}: {e}", out_path.display()));
2286        }
2287    };
2288    let err_file = match out_file.try_clone() {
2289        Ok(f) => f,
2290        Err(e) => {
2291            return ToolOutcome::err(format!(
2292                "cannot clone output file {}: {e}",
2293                out_path.display()
2294            ));
2295        }
2296    };
2297    cmd_builder
2298        .stdout(std::process::Stdio::from(out_file))
2299        .stderr(std::process::Stdio::from(err_file));
2300
2301    let mut child = match cmd_builder.spawn() {
2302        Ok(c) => c,
2303        Err(e) => return ToolOutcome::err(format!("blyte failed to spawn: {e}")),
2304    };
2305    drop(cmd_builder);
2306
2307    let deadline = std::time::Instant::now() + startup_wait;
2308    let exited = loop {
2309        match child.try_wait() {
2310            Ok(Some(status)) => break Some(status),
2311            Ok(None) => {
2312                let now = std::time::Instant::now();
2313                if now >= deadline {
2314                    break None;
2315                }
2316                std::thread::sleep(BACKGROUND_STARTUP_POLL.min(deadline - now));
2317            }
2318            Err(e) => {
2319                return ToolOutcome::err(format!("blyte wait failed for dispatch {id}: {e}"));
2320            }
2321        }
2322    };
2323
2324    match exited {
2325        Some(status) => {
2326            let raw = match std::fs::read(&out_path) {
2327                Ok(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
2328                Err(e) => {
2329                    return ToolOutcome::err(format!(
2330                        "dispatch {id} exited ({status}), and reading {} failed: {e}",
2331                        out_path.display()
2332                    ));
2333                }
2334            };
2335            let body = raw.trim_end();
2336            if status.success() {
2337                if body.is_empty() {
2338                    ToolOutcome::ok(format!("dispatch {id} finished"))
2339                } else {
2340                    ToolOutcome::ok(format!("dispatch {id} finished\n{body}"))
2341                }
2342            } else {
2343                let header = match status.code() {
2344                    Some(code) => format!("dispatch {id} failed to start (exit {code})"),
2345                    None => format!("dispatch {id} failed to start ({status})"),
2346                };
2347                if body.is_empty() {
2348                    ToolOutcome::err(header)
2349                } else {
2350                    ToolOutcome::err(format!("{header}\n{body}"))
2351                }
2352            }
2353        }
2354        None => {
2355            std::thread::spawn(move || {
2356                let _ = child.wait();
2357            });
2358            ToolOutcome::ok(format!(
2359                "started {id} in the background; use wait to learn when it ends; output: {}",
2360                out_path.display()
2361            ))
2362        }
2363    }
2364}
2365
2366fn format_dispatch_failure(output: &std::process::Output) -> String {
2367    let stderr_str = String::from_utf8_lossy(&output.stderr);
2368    let lines: Vec<&str> = stderr_str.lines().collect();
2369    let tail = if lines.len() > OUTPUT_LINE_BUDGET {
2370        lines[lines.len() - OUTPUT_LINE_BUDGET..].join("\n")
2371    } else if !stderr_str.trim().is_empty() {
2372        stderr_str.trim_end().to_string()
2373    } else {
2374        match output.status.code() {
2375            Some(code) => format!("exit {code}"),
2376            None => format!("terminated without exit code ({})", output.status),
2377        }
2378    };
2379    let stdout = String::from_utf8_lossy(&output.stdout);
2380    if stdout.trim().is_empty() {
2381        tail
2382    } else {
2383        format!("{}\n{tail}", stdout.trim_end())
2384    }
2385}
2386
2387fn serialize_dispatch_args<T: serde::Serialize>(args: &T) -> Result<Vec<u8>, String> {
2388    serde_json::to_vec(args).map_err(|e| format!("dispatch failed to serialize arguments: {e}"))
2389}
2390
2391fn dispatch_parent_session() -> String {
2392    std::env::var("BLYTE_SESSION")
2393        .ok()
2394        .filter(|s| !s.is_empty())
2395        .unwrap_or_else(|| {
2396            let now = std::time::SystemTime::now()
2397                .duration_since(std::time::UNIX_EPOCH)
2398                .map(|d| d.as_secs())
2399                .unwrap_or(0);
2400            format!("{now}-{}", std::process::id())
2401        })
2402}
2403
2404fn run_command_bounded(
2405    mut cmd: std::process::Command,
2406    timeout: Duration,
2407) -> Result<(i32, String, String), String> {
2408    use std::io::Read;
2409    use std::process::Stdio;
2410
2411    cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
2412
2413    #[cfg(unix)]
2414    {
2415        use std::os::unix::process::CommandExt;
2416        cmd.process_group(0);
2417    }
2418
2419    let mut child = cmd
2420        .spawn()
2421        .map_err(|e| format!("blyte failed to spawn: {e}"))?;
2422
2423    let mut so = child.stdout.take().ok_or("no stdout")?;
2424    let mut se = child.stderr.take().ok_or("no stderr")?;
2425    let t_out = std::thread::spawn(move || {
2426        let mut b = Vec::new();
2427        let _ = so.read_to_end(&mut b);
2428        String::from_utf8_lossy(&b).into_owned()
2429    });
2430    let t_err = std::thread::spawn(move || {
2431        let mut b = Vec::new();
2432        let _ = se.read_to_end(&mut b);
2433        String::from_utf8_lossy(&b).into_owned()
2434    });
2435
2436    let deadline = std::time::Instant::now() + timeout;
2437    let mut poll = POLL_START;
2438    let status = loop {
2439        match child
2440            .try_wait()
2441            .map_err(|e| format!("blyte wait failed: {e}"))?
2442        {
2443            Some(s) => break Some(s),
2444            None if std::time::Instant::now() >= deadline => {
2445                #[cfg(unix)]
2446                {
2447                    let pgid = child.id() as i32;
2448                    if pgid > 0 {
2449                        unsafe {
2450                            libc::kill(-pgid, libc::SIGKILL);
2451                        }
2452                    } else {
2453                        let _ = child.kill();
2454                    }
2455                }
2456                #[cfg(not(unix))]
2457                {
2458                    let _ = child.kill();
2459                }
2460                let _ = child.wait();
2461                break None;
2462            }
2463            None => {
2464                let remaining = deadline.saturating_duration_since(std::time::Instant::now());
2465                let (sleep, next) = poll_backoff(poll, remaining);
2466                std::thread::sleep(sleep);
2467                poll = next;
2468            }
2469        }
2470    };
2471
2472    let stdout = t_out
2473        .join()
2474        .map_err(|_| "blyte: reading the command's output failed".to_string())?;
2475    let stderr = t_err
2476        .join()
2477        .map_err(|_| "blyte: reading the command's errors failed".to_string())?;
2478
2479    match status {
2480        Some(s) => match s.code() {
2481            Some(code) => Ok((code, stdout, stderr)),
2482            None => Err(format!(
2483                "blyte ended without an exit code ({s}); its output so far:\n{stdout}{stderr}"
2484            )),
2485        },
2486        None => Ok((
2487            124,
2488            stdout,
2489            format!("{stderr}\n[killed by blyte after {}s]", timeout.as_secs()),
2490        )),
2491    }
2492}
2493
2494#[cfg(test)]
2495mod tests {
2496    use super::*;
2497
2498    #[test]
2499    fn bash_description_says_background_jobs_keep_running() {
2500        let all = specs();
2501        let desc = &all
2502            .iter()
2503            .find(|t| t.name == "bash")
2504            .expect("bash spec missing")
2505            .description;
2506        assert!(
2507            desc.contains(
2508                "A background job started with its output redirected keeps running after the command returns, and nothing reports when it exits."
2509            ),
2510            "got {desc:?}"
2511        );
2512        assert!(
2513            !desc.contains("there is no background mode"),
2514            "got {desc:?}"
2515        );
2516    }
2517
2518    #[test]
2519    fn serialize_dispatch_args_surfaces_serialization_error() {
2520        struct FailingSerialize;
2521
2522        impl serde::Serialize for FailingSerialize {
2523            fn serialize<S: serde::Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
2524                Err(serde::ser::Error::custom("unsupported map key"))
2525            }
2526        }
2527
2528        let err = serialize_dispatch_args(&FailingSerialize).unwrap_err();
2529        assert!(err.contains("serialize"), "got: {err}");
2530        assert!(err.contains("unsupported map key"), "got: {err}");
2531    }
2532
2533    #[test]
2534    fn check_in_place_lock_ignores_targets_outside_root() {
2535        struct LockReset;
2536        impl Drop for LockReset {
2537            fn drop(&mut self) {
2538                set_blyte_tool(None);
2539                set_in_place_lock_path(None);
2540            }
2541        }
2542        let _reset = LockReset;
2543        let root = tempfile::tempdir().unwrap();
2544        let outside = tempfile::tempdir().unwrap();
2545        let lock_dir = tempfile::tempdir().unwrap();
2546        let lock_path = lock_dir.path().join("in-place.lock");
2547        let fs = crate::fs::LocalFs;
2548
2549        set_blyte_tool(Some(lock_dir.path().join("blyte-stub")));
2550        set_in_place_lock_path(None);
2551
2552        let outside_file = outside.path().join("scratch.txt");
2553        let inside_file = root.path().join("note.txt");
2554
2555        assert!(check_in_place_lock(&fs, root.path(), &outside_file).is_ok());
2556        let missing = check_in_place_lock(&fs, root.path(), &inside_file).unwrap_err();
2557        assert!(missing.contains("lock"), "{missing}");
2558
2559        set_in_place_lock_path(Some(lock_path.clone()));
2560        let _held = crate::folder_lock::acquire(
2561            &lock_path,
2562            &crate::folder_lock::Holder {
2563                pid: std::process::id(),
2564                kind: "run".to_string(),
2565                id: "R9".to_string(),
2566            },
2567        )
2568        .unwrap();
2569
2570        assert!(check_in_place_lock(&fs, root.path(), &outside_file).is_ok());
2571        let held_err = check_in_place_lock(&fs, root.path(), &inside_file).unwrap_err();
2572        assert_eq!(
2573            held_err,
2574            "run R9 is editing this folder; wait for it to finish"
2575        );
2576    }
2577
2578    #[test]
2579    fn read_background_startup_wait_returns_error_when_lock_is_poisoned() {
2580        let lock = std::sync::RwLock::new(None);
2581        assert_eq!(
2582            read_background_startup_wait(&lock).unwrap(),
2583            BACKGROUND_STARTUP_WAIT
2584        );
2585
2586        let override_wait = Duration::from_millis(50);
2587        *lock.write().unwrap() = Some(override_wait);
2588        assert_eq!(read_background_startup_wait(&lock).unwrap(), override_wait);
2589
2590        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2591            let _guard = lock.write().unwrap();
2592            panic!("poison background startup wait lock");
2593        }));
2594
2595        let err = read_background_startup_wait(&lock).unwrap_err();
2596        assert!(
2597            err.contains("background startup wait lock"),
2598            "unexpected error: {err}"
2599        );
2600        assert!(err.contains("poisoned"), "unexpected error: {err}");
2601    }
2602}