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