use std::path::{Path, PathBuf};
use std::time::Duration;
use blyte_provider::ToolSpec;
use serde_json::{json, Value};
use crate::approval::{matching_rule, Approval, ApprovalConfig};
use crate::fs::Fs;
use crate::shell::{poll_backoff, Shell, POLL_START};
static READ_ROOTS: std::sync::RwLock<Vec<PathBuf>> = std::sync::RwLock::new(Vec::new());
static DISPATCH_CMD: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);
static BLYTE_TOOL: std::sync::RwLock<Option<PathBuf>> = std::sync::RwLock::new(None);
static BLYTE_SURFACE: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);
static APPROVAL: std::sync::RwLock<Option<ApprovalConfig>> = std::sync::RwLock::new(None);
static WRITE_SCOPE: std::sync::RwLock<Option<WriteScope>> = std::sync::RwLock::new(None);
thread_local! {
static BLYTE_REQUEST: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WriteScope {
pub allowed: Vec<PathBuf>,
pub edit_worktrees: Option<PathBuf>,
}
fn refused_blyte_tool_command(args: &[String]) -> Option<&'static str> {
let first = args.first().map(|s| s.as_str())?;
if first == "combine" {
return Some("combine");
}
if first == "review" {
let mut iter = args[1..].iter();
while let Some(arg) = iter.next() {
if arg == "--" {
break;
}
if arg == "--model-review" {
return Some("review --model-review");
}
let verdict_val = if arg == "--verdict" {
iter.next().map(|s| s.as_str())
} else {
arg.strip_prefix("--verdict=")
};
if let Some(val) = verdict_val {
if val.eq_ignore_ascii_case("accepted") {
return Some("review --verdict accepted");
}
if val.eq_ignore_ascii_case("fixed") {
return Some("review --verdict fixed");
}
}
}
}
None
}
pub const BLYTE_TOOL_COMMANDS: [&str; 9] = [
"dispatch",
"wait",
"status",
"review",
"plan",
"init",
"clean",
"edit-start",
"edit-finish",
];
pub fn set_blyte_request(request: Option<String>) {
BLYTE_REQUEST.with(|slot| {
*slot.borrow_mut() = request;
});
}
pub fn blyte_request() -> Option<String> {
BLYTE_REQUEST.with(|slot| slot.borrow().clone())
}
pub fn set_blyte_tool(exe: Option<std::path::PathBuf>) {
match BLYTE_TOOL.write() {
Ok(mut lock) => *lock = exe,
Err(poisoned) => *poisoned.into_inner() = exe,
}
}
pub fn blyte_tool() -> Option<PathBuf> {
BLYTE_TOOL
.read()
.map(|r| r.clone())
.unwrap_or_else(|e| e.into_inner().clone())
}
pub fn set_blyte_surface(surface: Option<String>) {
match BLYTE_SURFACE.write() {
Ok(mut lock) => *lock = surface,
Err(poisoned) => *poisoned.into_inner() = surface,
}
}
pub fn blyte_surface() -> Option<String> {
BLYTE_SURFACE
.read()
.map(|r| r.clone())
.unwrap_or_else(|e| e.into_inner().clone())
}
pub fn set_approval(config: Option<ApprovalConfig>) {
match APPROVAL.write() {
Ok(mut lock) => *lock = config,
Err(poisoned) => *poisoned.into_inner() = config,
}
}
pub fn approval() -> Option<ApprovalConfig> {
APPROVAL
.read()
.map(|r| r.clone())
.unwrap_or_else(|e| e.into_inner().clone())
}
pub fn set_write_scope(scope: Option<WriteScope>) {
match WRITE_SCOPE.write() {
Ok(mut lock) => *lock = scope,
Err(poisoned) => *poisoned.into_inner() = scope,
}
}
pub fn write_scope() -> Option<WriteScope> {
WRITE_SCOPE
.read()
.map(|r| r.clone())
.unwrap_or_else(|e| e.into_inner().clone())
}
pub fn set_dispatch_cmd(cmd: Option<String>) {
match DISPATCH_CMD.write() {
Ok(mut lock) => *lock = cmd,
Err(poisoned) => *poisoned.into_inner() = cmd,
}
}
pub fn dispatch_cmd() -> Option<String> {
DISPATCH_CMD
.read()
.map(|r| r.clone())
.unwrap_or_else(|e| e.into_inner().clone())
}
pub fn set_read_roots(roots: Vec<PathBuf>) {
match READ_ROOTS.write() {
Ok(mut lock) => *lock = roots,
Err(poisoned) => *poisoned.into_inner() = roots,
}
}
pub fn read_roots() -> Vec<PathBuf> {
READ_ROOTS
.read()
.map(|r| r.clone())
.unwrap_or_else(|e| e.into_inner().clone())
}
pub const OUTPUT_LINE_BUDGET: usize = 400;
pub const READ_LINE_BUDGET: usize = 2_000;
pub const MAX_MATCHES: usize = 200;
pub const MAX_LINE_CHARS: usize = 500;
pub const READ_LINE_CHARS: usize = 2_000;
pub const MAX_OUTPUT_CHARS: usize = 60_000;
pub fn bound_output_with(text: &str, line_budget: usize, line_chars: usize) -> String {
let clipped: Vec<String> = text
.lines()
.map(|l| {
let n = l.chars().count();
if n > line_chars {
let head: String = l.chars().take(line_chars).collect();
format!(
"{head} …[{} more chars clipped by blyte; the grep tool shows the text around a match]",
n - line_chars
)
} else {
l.to_string()
}
})
.collect();
let mut joined = clipped.join("\n");
if text.ends_with('\n') {
joined.push('\n');
}
let distilled = distil(&joined, line_budget);
let total = distilled.chars().count();
if total <= MAX_OUTPUT_CHARS {
return distilled;
}
let head_n = MAX_OUTPUT_CHARS * 2 / 3;
let tail_n = MAX_OUTPUT_CHARS - head_n;
let head: String = distilled.chars().take(head_n).collect();
let tail: String = distilled.chars().skip(total - tail_n).collect();
format!(
"{head}\n\n[... {} chars elided by blyte ...]\n\n{tail}",
total - head_n - tail_n
)
}
pub fn bound_output_lines(text: &str, line_budget: usize) -> String {
bound_output_with(text, line_budget, MAX_LINE_CHARS)
}
pub fn bound_output(text: &str) -> String {
bound_output_lines(text, OUTPUT_LINE_BUDGET)
}
pub fn excerpt_around(text: &str, start: usize, end: usize, max: usize) -> String {
let total_chars = text.chars().count();
if total_chars <= max {
return text.to_string();
}
if start > text.len()
|| end > text.len()
|| start > end
|| !text.is_char_boundary(start)
|| !text.is_char_boundary(end)
{
return text.to_string();
}
let before = &text[..start];
let matched = &text[start..end];
let after = &text[end..];
let before_chars = before.chars().count();
let match_chars = matched.chars().count();
let after_chars = after.chars().count();
if match_chars >= max {
let kept_match: String = matched.chars().take(max).collect();
let dropped_before = before_chars;
let dropped_after = after_chars + (match_chars - max);
let mut out = String::new();
if dropped_before > 0 {
out.push_str(&format!("…[{dropped_before} chars] "));
}
out.push_str(&kept_match);
if dropped_after > 0 {
out.push_str(&format!(" …[{dropped_after} chars]"));
}
return out;
}
let rem = max - match_chars;
let half_before = rem / 2;
let half_after = rem - half_before;
let (take_before, take_after) = if before_chars < half_before {
let tb = before_chars;
let ta = (rem - tb).min(after_chars);
(tb, ta)
} else if after_chars < half_after {
let ta = after_chars;
let tb = (rem - ta).min(before_chars);
(tb, ta)
} else {
(half_before, half_after)
};
let dropped_before = before_chars - take_before;
let dropped_after = after_chars - take_after;
let mut out = String::new();
if dropped_before > 0 {
out.push_str(&format!("…[{dropped_before} chars] "));
}
let kept_before: String = before
.chars()
.skip(dropped_before)
.take(take_before)
.collect();
out.push_str(&kept_before);
out.push_str(matched);
let kept_after: String = after.chars().take(take_after).collect();
out.push_str(&kept_after);
if dropped_after > 0 {
out.push_str(&format!(" …[{dropped_after} chars]"));
}
out
}
const MAX_EXCERPTS_PER_LINE: usize = 5;
pub fn excerpt_matches(text: &str, found: &[(usize, usize)], max: usize) -> String {
if found.len() <= 1 || text.chars().count() <= max {
return match found.first() {
Some(&(s, e)) => excerpt_around(text, s, e, max),
None => text.to_string(),
};
}
let shown = &found[..found.len().min(MAX_EXCERPTS_PER_LINE)];
let match_chars: usize = shown.iter().map(|&(s, e)| text[s..e].chars().count()).sum();
let context = max.saturating_sub(match_chars) / (2 * shown.len());
let to_char = |b: usize| text[..b].chars().count();
let total = text.chars().count();
let mut windows: Vec<(usize, usize)> = Vec::new();
for &(s, e) in shown {
let (cs, ce) = (to_char(s), to_char(e));
let w = (cs.saturating_sub(context), (ce + context).min(total));
match windows.last_mut() {
Some(last) if w.0 <= last.1 => last.1 = last.1.max(w.1),
_ => windows.push(w),
}
}
let chars: Vec<char> = text.chars().collect();
let mut out = String::new();
let mut pos = 0;
for (i, &(a, b)) in windows.iter().enumerate() {
if a > pos {
if i == 0 {
out.push_str(&format!("…[{} chars] ", a - pos));
} else {
out.push_str(&format!(" …[{} chars] ", a - pos));
}
}
out.extend(&chars[a..b]);
pos = b;
}
if pos < total {
out.push_str(&format!(" …[{} chars]", total - pos));
}
if found.len() > shown.len() {
out.push_str(&format!(
" [{} more matches in this line]",
found.len() - shown.len()
));
}
out
}
fn split_grep_prefix(line: &str) -> (&str, &str) {
static PREFIX_RE: std::sync::LazyLock<regex::Regex> =
std::sync::LazyLock::new(|| regex::Regex::new(r"^(\d+:\d+:|\d+:|.*?:\d+:)").unwrap());
if let Some(m) = PREFIX_RE.find(line) {
(&line[..m.end()], &line[m.end()..])
} else {
("", line)
}
}
pub const COMMAND_TIMEOUT: Duration = Duration::from_secs(300);
pub const EDIT_FINISH_TIMEOUT: Duration = Duration::from_secs(3600);
pub fn blyte_command_timeout(subcommand: &str) -> Duration {
if subcommand == "edit-finish" {
EDIT_FINISH_TIMEOUT
} else {
COMMAND_TIMEOUT
}
}
fn command_ceiling(name: &str, args: &Value) -> Duration {
if name == "blyte" {
if let Some(first) = args
.get("args")
.and_then(|v| v.as_array())
.and_then(|a| a.first())
.and_then(|v| v.as_str())
{
return blyte_command_timeout(first);
}
}
COMMAND_TIMEOUT
}
#[derive(Debug, Clone, PartialEq)]
pub struct ToolOutcome {
pub content: String,
pub is_error: bool,
}
impl ToolOutcome {
fn ok(s: impl Into<String>) -> Self {
Self {
content: s.into(),
is_error: false,
}
}
fn err(s: impl Into<String>) -> Self {
Self {
content: s.into(),
is_error: true,
}
}
}
pub fn distil(text: &str, budget: usize) -> String {
let lines: Vec<&str> = text.lines().collect();
if lines.len() <= budget {
return text.to_string();
}
let head = budget * 2 / 3;
let tail = budget - head;
let dropped = lines.len() - budget;
let mut out = lines[..head].join("\n");
out.push_str(&format!(
"\n\n[... {dropped} lines elided by blyte ...]\n\n"
));
out.push_str(&lines[lines.len() - tail..].join("\n"));
out
}
fn lexically_normalize(p: &Path) -> PathBuf {
use std::path::Component;
let mut out = PathBuf::new();
for c in p.components() {
match c {
Component::CurDir => {}
Component::ParentDir => {
if !out.pop() {
out.push("..");
}
}
other => out.push(other.as_os_str()),
}
}
out
}
fn resolve_in_workspace(fs: &dyn Fs, root: &Path, raw: &str) -> Result<PathBuf, String> {
let joined = lexically_normalize(&if Path::new(raw).is_absolute() {
PathBuf::from(raw)
} else {
root.join(raw)
});
let root_c = fs
.canonicalize(root)
.map_err(|e| format!("workspace root unreadable: {e}"))?;
let mut probe = joined.as_path();
let probe_c = loop {
if let Ok(c) = fs.canonicalize(probe) {
break c;
}
match probe.parent() {
Some(p) => probe = p,
None => break joined.clone(),
}
};
if !probe_c.starts_with(&root_c) {
return Err(format!("path escapes the workspace: {raw}"));
}
Ok(joined)
}
fn resolve_real_target(fs: &dyn Fs, path: &Path) -> Result<PathBuf, String> {
let mut probe = path;
let mut tail: Vec<std::ffi::OsString> = Vec::new();
loop {
match fs.canonicalize(probe) {
Ok(mut resolved) => {
for part in tail.into_iter().rev() {
resolved.push(part);
}
return Ok(resolved);
}
Err(e) => {
let exists_or_unreadable = if fs.is_local() {
match std::fs::symlink_metadata(probe) {
Ok(_) => true,
Err(meta_err) => meta_err.kind() != std::io::ErrorKind::NotFound,
}
} else {
false
};
if exists_or_unreadable {
return Err(format!("cannot canonicalize {}: {e}", probe.display()));
}
let Some(name) = probe.file_name() else {
return Err(format!("cannot canonicalize {}: {e}", probe.display()));
};
tail.push(name.to_os_string());
let Some(parent) = probe.parent() else {
return Err(format!("cannot canonicalize {}: {e}", probe.display()));
};
probe = parent;
}
}
}
}
fn is_in_open_edit_worktree(edit_worktrees: &Path, real_target: &Path) -> Result<bool, String> {
use std::path::Component;
let Ok(rel) = real_target.strip_prefix(edit_worktrees) else {
return Ok(false);
};
let mut comps = rel.components();
let Some(Component::Normal(id)) = comps.next() else {
return Ok(false);
};
let mut has_child = false;
for comp in comps {
has_child = true;
match comp {
Component::Normal(name) if name == ".git" => return Ok(false),
Component::Normal(_) => {}
_ => return Ok(false),
}
}
if !has_child {
return Ok(false);
}
crate::sandbox::is_open_edit_worktree_id(edit_worktrees, id)
}
fn check_write_scope(fs: &dyn Fs, tool: &str, path: &Path) -> Result<(), String> {
let Some(scope) = write_scope() else {
return Ok(());
};
let real_target = resolve_real_target(fs, path)?;
if scope.allowed.iter().any(|dir| real_target.starts_with(dir)) {
return Ok(());
}
if let Some(edit_worktrees) = &scope.edit_worktrees {
if is_in_open_edit_worktree(edit_worktrees, &real_target)? {
return Ok(());
}
}
let allowed_list = scope
.allowed
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ");
let cmd = format!("{tool} {}", real_target.display());
let reason = format!("outside the directories this conversation may write ({allowed_list})");
let Some(cfg) = approval() else {
return Err(format!(
"write was not made: {} is outside the directories this conversation may write ({allowed_list}); no approver is configured (the user can approve writes outside these directories).",
real_target.display()
));
};
match cfg.approver.ask(&cmd, &reason) {
Approval::Approved => Ok(()),
Approval::Denied => Err(format!(
"write was not made: {} is outside the directories this conversation may write ({allowed_list}); the user refused (the user can approve writes outside these directories).",
real_target.display()
)),
Approval::Unavailable => Err(format!(
"write was not made: {} is outside the directories this conversation may write ({allowed_list}); nobody can approve it in this run (the user can approve writes outside these directories).",
real_target.display()
)),
}
}
pub(crate) fn resolve_for_read(fs: &dyn Fs, root: &Path, raw: &str) -> Result<PathBuf, String> {
if let Ok(p) = resolve_in_workspace(fs, root, raw) {
return Ok(p);
}
let roots = READ_ROOTS
.read()
.map(|r| r.clone())
.unwrap_or_else(|e| e.into_inner().clone());
let p = Path::new(raw);
if p.is_absolute() {
let joined = lexically_normalize(p);
let mut probe = joined.as_path();
let probe_c = loop {
if let Ok(c) = fs.canonicalize(probe) {
break Some(c);
}
match probe.parent() {
Some(p) => probe = p,
None => break None,
}
};
if let Some(probe_c) = probe_c {
for r in &roots {
if let Ok(rc) = fs.canonicalize(r) {
if probe_c.starts_with(&rc) {
return Ok(joined);
}
}
}
}
}
let extra = if roots.is_empty() {
String::new()
} else {
let list: Vec<String> = roots.iter().map(|r| r.display().to_string()).collect();
format!(" and {}", list.join(", "))
};
Err(format!(
"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."
))
}
fn shell_quote(s: &str) -> String {
format!("'{}'", s.replace('\'', r"'\''"))
}
pub const ACCELERATORS: &[&str] = &["rg", "fd", "sd", "tokei", "jq", "ast-grep"];
pub const TOOLCHAINS: &[&str] = &[
"git", "cargo", "go", "npm", "yarn", "pnpm", "python3", "pytest", "node", "make",
];
pub fn available_binaries(shell: &dyn Shell, root: &Path) -> Result<Vec<String>, String> {
let mut all: Vec<&'static str> = ACCELERATORS.to_vec();
all.extend_from_slice(TOOLCHAINS);
shell.available_binaries(root, &all)
}
fn bash_description() -> String {
format!(
"Run a shell command in the workspace and wait for it to finish. \
Commands run to completion (up to {}s). \
A background job started with its output redirected keeps running after the command \
returns, and nothing reports when it exits. \
Output over {} lines is elided in the middle. \
To find files or search file contents use the `glob` and `grep` tools, not \
`find`, `grep -r` or `rg` in the shell; they respect .gitignore, are capped \
and cannot hang.",
COMMAND_TIMEOUT.as_secs(),
OUTPUT_LINE_BUDGET
)
}
pub fn specs() -> Vec<ToolSpec> {
let mut tools = vec![
ToolSpec {
name: "read".into(),
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(),
parameters: json!({"type":"object","properties":{
"path":{"type":"string"},
"start_line":{"type":"integer","description":"1-indexed, inclusive"},
"end_line":{"type":"integer","description":"1-indexed, inclusive"}},
"required":["path"]}),
},
ToolSpec {
name: "write".into(),
description: "Create or overwrite a file with exact content.".into(),
parameters: json!({"type":"object","properties":{
"path":{"type":"string"},"content":{"type":"string"}},
"required":["path","content"]}),
},
ToolSpec {
name: "edit".into(),
description: "Replace an exact, unique string in a file. Fails if absent or ambiguous."
.into(),
parameters: json!({"type":"object","properties":{
"path":{"type":"string"},"old":{"type":"string"},"new":{"type":"string"}},
"required":["path","old","new"]}),
},
ToolSpec {
name: "bash".into(),
description: bash_description(),
parameters: if approval().is_some() {
json!({
"type": "object",
"properties": {
"command": {"type": "string"},
"unsandboxed": {
"type": "boolean",
"description": "Run this one command outside the sandbox, with the user's network and credentials. It runs only if the user approves it."
},
"reason": {
"type": "string",
"description": "One line telling the user why the command must leave the sandbox."
}
},
"required": ["command"]
})
} else {
json!({"type":"object","properties":{
"command":{"type":"string"}},"required":["command"]})
},
},
ToolSpec {
name: "glob".into(),
description: "Find files by glob pattern, e.g. `src/**/*.rs`. Respects .gitignore; \
`.git` is skipped. Fast, and the right \
first move when you do not know where something lives."
.into(),
parameters: json!({"type":"object","properties":{
"pattern":{"type":"string","description":"glob, relative to path (or the workspace)"},
"path":{"type":"string","description":"directory to search under; defaults to the workspace; may be an absolute path under a read root"}},
"required":["pattern"]}),
},
ToolSpec {
name: "grep".into(),
description: format!(
"Search file contents by regular expression, returning `path:line:text`. \
Respects .gitignore. Use `glob` to find files by name and `grep` to find them \
by content. Capped at {MAX_MATCHES} matches, and the total is always reported."
),
parameters: json!({"type":"object","properties":{
"pattern":{"type":"string","description":"regular expression"},
"path":{"type":"string","description":"subtree to search; defaults to the workspace"},
"glob":{"type":"string","description":"restrict to files matching this glob, e.g. `*.ts`"}},
"required":["pattern"]}),
},
];
if dispatch_cmd().is_some() {
tools.push(ToolSpec {
name: "dispatch".into(),
description: "Delegate work to an implementer task on the host.".into(),
parameters: json!({
"type": "object",
"properties": {
"task": {
"type": "string",
"description": "Task instructions for the implementer"
},
"gate": {
"type": "string",
"description": "Verification command that decides completion"
},
"max_seconds": {
"type": "integer",
"description": "Optional wall-clock limit in seconds"
}
},
"required": ["task", "gate"]
}),
});
}
if blyte_tool().is_some() {
tools.push(ToolSpec {
name: "blyte".into(),
description: "Run one of blyte's own commands on the host: dispatch, wait, status, review, plan, init, clean, edit-start, edit-finish.".into(),
parameters: json!({
"type": "object",
"properties": {
"args": {
"type": "array",
"items": {"type": "string"},
"description": "The words after `blyte`"
},
"background": {
"type": "boolean",
"description": "Start a `dispatch` in the background and return at once"
}
},
"required": ["args"]
}),
});
}
tools
}
pub fn grep_command(use_rg: bool, pattern: &str, sub: &str, glob: &str) -> String {
if use_rg {
let globarg = if glob.is_empty() {
String::new()
} else {
format!("--glob {}", shell_quote(glob))
};
format!(
"rg --line-number --no-heading --color never {globarg} -e {} {} | head -n {}",
shell_quote(pattern),
shell_quote(sub),
MAX_MATCHES + 1
)
} else {
let globarg = if glob.is_empty() {
String::new()
} else {
format!("--include={}", shell_quote(glob))
};
let excludes = ["node_modules", ".git", "target", ".venv", "dist", "build"]
.iter()
.map(|d| format!("--exclude-dir={d}"))
.collect::<Vec<_>>()
.join(" ");
format!(
"grep -rnIE {excludes} {globarg} -e {} {} | head -n {}",
shell_quote(pattern),
shell_quote(sub),
MAX_MATCHES + 1
)
}
}
pub fn execute(
root: &Path,
shell: &dyn Shell,
fs: &dyn Fs,
name: &str,
args: &Value,
) -> ToolOutcome {
execute_with_deadline(root, shell, fs, name, args, None)
}
pub fn execute_with_deadline(
root: &Path,
shell: &dyn Shell,
fs: &dyn Fs,
name: &str,
args: &Value,
deadline: Option<std::time::Instant>,
) -> ToolOutcome {
let ceiling = command_ceiling(name, args);
let command_timeout = match deadline {
Some(d) => ceiling.min(d.saturating_duration_since(std::time::Instant::now())),
None => ceiling,
};
execute_with_timeout(root, shell, fs, name, args, command_timeout)
}
pub fn execute_with_timeout(
root: &Path,
shell: &dyn Shell,
fs: &dyn Fs,
name: &str,
args: &Value,
timeout: Duration,
) -> ToolOutcome {
let ceiling = command_ceiling(name, args);
let mut outcome = execute_unbounded(root, shell, fs, name, args, ceiling.min(timeout));
outcome.content = if name == "read" {
bound_output_with(&outcome.content, READ_LINE_BUDGET, READ_LINE_CHARS)
} else if name == "grep" {
bound_output_with(&outcome.content, OUTPUT_LINE_BUDGET, READ_LINE_CHARS)
} else {
bound_output_lines(&outcome.content, OUTPUT_LINE_BUDGET)
};
outcome
}
fn execute_unbounded(
root: &Path,
shell: &dyn Shell,
fs: &dyn Fs,
name: &str,
args: &Value,
command_timeout: Duration,
) -> ToolOutcome {
let s = |k: &str| {
args.get(k)
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string()
};
match name {
"read" => {
let path = match resolve_for_read(fs, root, &s("path")) {
Ok(p) => p,
Err(e) => return ToolOutcome::err(e),
};
let body = match fs.read(&path) {
Ok(b) => b,
Err(e) => return ToolOutcome::err(e),
};
let lines: Vec<&str> = body.lines().collect();
let start = args
.get("start_line")
.and_then(|v| v.as_u64())
.unwrap_or(1)
.max(1) as usize;
let fits = lines.len() <= READ_LINE_BUDGET && body.chars().count() <= MAX_OUTPUT_CHARS;
let end = if start == 1 && fits {
lines.len()
} else {
args.get("end_line")
.and_then(|v| v.as_u64())
.map(|e| e as usize)
.unwrap_or(lines.len())
.min(lines.len())
};
if start > lines.len() {
return ToolOutcome::err(format!(
"{} has {} lines; start_line {start} is past the end",
s("path"),
lines.len()
));
}
if end < start {
return ToolOutcome::err(format!(
"end_line {end} is before start_line {start} in {}",
s("path")
));
}
let body = lines[start - 1..end]
.iter()
.enumerate()
.map(|(i, l)| format!("{:>6}\t{l}", start + i))
.collect::<Vec<_>>()
.join("\n");
ToolOutcome::ok(distil(&body, READ_LINE_BUDGET))
}
"write" => {
let path = match resolve_in_workspace(fs, root, &s("path")) {
Ok(p) => p,
Err(e) => return ToolOutcome::err(e),
};
if let Err(e) = check_write_scope(fs, "write", &path) {
return ToolOutcome::err(e);
}
match fs.write(&path, &s("content")) {
Ok(_) => ToolOutcome::ok(format!("wrote {}", s("path"))),
Err(e) => ToolOutcome::err(e),
}
}
"edit" => {
let path = match resolve_in_workspace(fs, root, &s("path")) {
Ok(p) => p,
Err(e) => return ToolOutcome::err(e),
};
if let Err(e) = check_write_scope(fs, "edit", &path) {
return ToolOutcome::err(e);
}
let body = match fs.read(&path) {
Ok(b) => b,
Err(e) => return ToolOutcome::err(e),
};
let (old, new) = (s("old"), s("new"));
match body.matches(&old).count() {
0 => ToolOutcome::err(format!("`old` not found in {}. Read it first.", s("path"))),
n if n > 1 => ToolOutcome::err(format!(
"`old` appears {n} times in {}; include more context to make it unique",
s("path")
)),
_ => match fs.write(&path, &body.replacen(&old, &new, 1)) {
Ok(_) => ToolOutcome::ok(format!("edited {}", s("path"))),
Err(e) => ToolOutcome::err(e),
},
}
}
"bash" => {
let command = s("command");
let unsandboxed = args
.get("unsandboxed")
.and_then(|v| v.as_bool())
.unwrap_or(false);
if unsandboxed {
let Some(cfg) = approval() else {
return ToolOutcome::err("this run cannot run commands outside the sandbox");
};
let reason_raw = s("reason");
let reason = reason_raw.trim();
if reason.is_empty() {
return ToolOutcome::err("give a one-line reason with an unsandboxed command");
}
let banner = if let Some(rule) = matching_rule(&command, &cfg.rules) {
format!("ran outside the sandbox (allowed by rule \"{rule}\")")
} else {
match cfg.approver.ask(&command, reason) {
Approval::Approved => {
"ran outside the sandbox (approved by the user)".to_string()
}
Approval::Denied => {
return ToolOutcome::err(
"the user refused this command; it was not run. Do not try to run it another way.",
);
}
Approval::Unavailable => {
return ToolOutcome::err(
"nobody can approve a command in this run, so it was not run",
);
}
}
};
match shell.exec_host(&command, root, command_timeout) {
Ok(o) => {
let body = distil(o.merged().trim_end(), OUTPUT_LINE_BUDGET);
ToolOutcome {
content: format!("{banner}\nexit {}\n{body}", o.exit_code),
is_error: o.exit_code != 0,
}
}
Err(e) => ToolOutcome::err(e),
}
} else {
match shell.exec_user(&command, root, command_timeout) {
Ok(o) => {
let body = distil(o.merged().trim_end(), OUTPUT_LINE_BUDGET);
ToolOutcome {
content: format!("exit {}\n{body}", o.exit_code),
is_error: o.exit_code != 0,
}
}
Err(e) => ToolOutcome::err(e),
}
}
}
"glob" => {
let pattern = s("pattern");
let raw_path = s("path");
let sub = if raw_path.is_empty() { "." } else { &raw_path };
let dir = match resolve_for_read(fs, root, sub) {
Ok(d) => d,
Err(e) => return ToolOutcome::err(e),
};
let outcome = |hits: Vec<String>| {
if hits.is_empty() {
ToolOutcome::ok(format!("no files match {pattern}"))
} else {
let shown: Vec<String> = if raw_path.is_empty() {
hits
} else {
let base = Path::new(&raw_path);
hits.into_iter()
.map(|h| base.join(h).to_string_lossy().into_owned())
.collect()
};
ToolOutcome::ok(format!("{} file(s):\n{}", shown.len(), shown.join("\n")))
}
};
if fs.is_local() {
if let Some(hits) = crate::search::glob_paths(&dir, &pattern, MAX_MATCHES) {
return outcome(hits);
}
} else if let Ok(o) = shell.exec(
"if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then \
git -c core.quotePath=off -c core.fsmonitor=false ls-files -co --exclude-standard; \
else echo __BLYTE_NO_GIT__; fi",
&dir,
command_timeout,
) {
if o.exit_code == 0 && !o.stdout.starts_with("__BLYTE_NO_GIT__") {
if let Some(hits) = crate::search::glob_filter(&o.stdout, &pattern, MAX_MATCHES)
{
return outcome(hits);
}
}
}
let cmd = format!(
"if shopt -s globstar 2>/dev/null; then \
shopt -s nullglob dotglob 2>/dev/null; \
printf '%s\\n' {pattern}; \
elif command -v zsh >/dev/null 2>&1; then \
zsh -c 'setopt null_glob glob_dots 2>/dev/null; printf \"%s\\n\" {pattern}'; \
else \
shopt -s nullglob dotglob 2>/dev/null; \
printf '%s\\n' {pattern}; \
fi | head -n {MAX_MATCHES}"
);
match shell.exec(&cmd, &dir, command_timeout) {
Ok(o) => {
let hits: Vec<String> = o
.stdout
.lines()
.filter(|l| !l.trim().is_empty())
.map(String::from)
.collect();
outcome(hits)
}
Err(e) => ToolOutcome::err(format!("glob failed: {e}")),
}
}
"grep" => {
let pattern = s("pattern");
let sub = {
let p = s("path");
if p.is_empty() {
".".to_string()
} else {
p
}
};
if let Err(e) = resolve_for_read(fs, root, &sub) {
return ToolOutcome::err(e);
}
let glob_str = s("glob");
let lines: Vec<String> = if fs.is_local() {
match crate::search::grep_lines(root, &sub, &pattern, &glob_str, MAX_MATCHES + 1) {
Ok(l) => l,
Err(e) => return ToolOutcome::err(format!("grep failed: {e}")),
}
} else {
let cmd = format!(
"if command -v rg >/dev/null 2>&1; then {}; else {}; fi",
grep_command(true, &pattern, &sub, &glob_str),
grep_command(false, &pattern, &sub, &glob_str)
);
match shell.exec(&cmd, root, command_timeout) {
Ok(o) => o
.stdout
.lines()
.filter(|l| !l.trim().is_empty())
.map(String::from)
.collect(),
Err(e) => return ToolOutcome::err(format!("grep failed: {e}")),
}
};
if lines.is_empty() {
return ToolOutcome::ok(format!("no matches for {pattern}"));
}
let pattern_re = regex::Regex::new(&pattern).ok();
let lines: Vec<String> = lines
.into_iter()
.map(|line| {
if line.chars().count() <= MAX_LINE_CHARS {
return line;
}
let Some(ref re) = pattern_re else {
return line;
};
let (prefix, rest) = split_grep_prefix(&line);
let found: Vec<(usize, usize)> =
re.find_iter(rest).map(|m| (m.start(), m.end())).collect();
if found.is_empty() {
line
} else {
format!("{prefix}{}", excerpt_matches(rest, &found, MAX_LINE_CHARS))
}
})
.collect();
if lines.len() > MAX_MATCHES {
ToolOutcome::ok(format!(
"{}\n\n[capped at {MAX_MATCHES} matches; narrow the pattern or pass `glob` \
to see the rest]",
lines[..MAX_MATCHES].join("\n")
))
} else {
ToolOutcome::ok(format!("{} match(es):\n{}", lines.len(), lines.join("\n")))
}
}
"dispatch" => {
let Some(cmd) = dispatch_cmd() else {
return ToolOutcome::err("unknown tool: dispatch");
};
let json_bytes = match serialize_dispatch_args(args) {
Ok(bytes) => bytes,
Err(msg) => return ToolOutcome::err(msg),
};
let parent_session = dispatch_parent_session();
let mut cmd_builder = std::process::Command::new("sh");
cmd_builder
.arg("-c")
.arg(&cmd)
.env("BLYTE_DISPATCH_PARENT", &parent_session)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped());
if root.is_dir() {
cmd_builder.current_dir(root);
}
let mut child = match cmd_builder.spawn() {
Ok(c) => c,
Err(e) => return ToolOutcome::err(format!("dispatch failed to spawn: {e}")),
};
let Some(mut stdin) = child.stdin.take() else {
let _ = child.kill();
let _ = child.wait();
return ToolOutcome::err("dispatch failed: stdin pipe unavailable");
};
let write_err = std::io::Write::write_all(&mut stdin, &json_bytes).err();
drop(stdin);
match (write_err, child.wait_with_output()) {
(None, Ok(output)) if output.status.success() => {
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
ToolOutcome::ok(stdout)
}
(None, Ok(output)) => ToolOutcome::err(format_dispatch_failure(&output)),
(None, Err(e)) => ToolOutcome::err(format!("dispatch command failed: {e}")),
(Some(write_err), Ok(output)) if output.status.success() => ToolOutcome::err(
format!("dispatch failed to write arguments to stdin: {write_err}"),
),
(Some(write_err), Ok(output)) => ToolOutcome::err(format!(
"{}\ndispatch also failed to write arguments to stdin: {write_err}",
format_dispatch_failure(&output)
)),
(Some(write_err), Err(wait_err)) => ToolOutcome::err(format!(
"dispatch failed to write arguments to stdin: {write_err}; dispatch command also failed: {wait_err}"
)),
}
}
"blyte" => {
let Some(exe) = blyte_tool() else {
return ToolOutcome::err("unknown tool: blyte");
};
let cmd_args: Vec<String> = match args.get("args").and_then(|v| v.as_array()) {
Some(arr) => {
let mut out = Vec::with_capacity(arr.len());
for item in arr {
match item.as_str() {
Some(s) => out.push(s.to_string()),
None => return ToolOutcome::err("args must be an array of strings"),
}
}
out
}
None => Vec::new(),
};
let Some(first) = cmd_args.first().map(|s| s.as_str()) else {
return ToolOutcome::err(format!(
"the blyte tool runs only: {}",
BLYTE_TOOL_COMMANDS.join(", ")
));
};
if let Some(refused) = refused_blyte_tool_command(&cmd_args) {
return ToolOutcome::err(crate::shell::model_shell_refusal_message(refused));
}
if !BLYTE_TOOL_COMMANDS.contains(&first) {
return ToolOutcome::err(format!(
"the blyte tool runs only: {}",
BLYTE_TOOL_COMMANDS.join(", ")
));
}
let background = args
.get("background")
.and_then(|v| v.as_bool())
.unwrap_or(false);
if background && first != "dispatch" {
return ToolOutcome::err("only dispatch can run in the background");
}
let mut exec_args = cmd_args.clone();
if matches!(first, "dispatch" | "edit-finish") {
if cmd_args
.iter()
.skip(1)
.any(|a| a == "--request" || a.starts_with("--request="))
{
return ToolOutcome::err("do not pass --request; blyte sets it automatically");
}
if cmd_args
.iter()
.skip(1)
.any(|a| a == "--surface" || a.starts_with("--surface="))
{
return ToolOutcome::err("do not pass --surface; blyte sets it automatically");
}
if let Some(req_id) = blyte_request() {
if let Some(pos) = exec_args.iter().position(|a| a == "--") {
exec_args.insert(pos, req_id);
exec_args.insert(pos, "--request".to_string());
} else {
exec_args.push("--request".to_string());
exec_args.push(req_id);
}
}
if let Some(surface_id) = blyte_surface() {
if let Some(pos) = exec_args.iter().position(|a| a == "--") {
exec_args.insert(pos, surface_id);
exec_args.insert(pos, "--surface".to_string());
} else {
exec_args.push("--surface".to_string());
exec_args.push(surface_id);
}
}
}
let parent_session = dispatch_parent_session();
let mut cmd_builder = std::process::Command::new(&exe);
cmd_builder
.args(&exec_args)
.env("BLYTE_DISPATCH_PARENT", &parent_session)
.env_remove(crate::shell::MODEL_SHELL_ENV)
.stdin(std::process::Stdio::null());
if root.is_dir() {
cmd_builder.current_dir(root);
}
if background {
let Some(id) = cmd_args.get(1).filter(|s| !s.is_empty()) else {
return ToolOutcome::err("dispatch needs an id");
};
return run_background_dispatch(cmd_builder, root, id);
}
match run_command_bounded(cmd_builder, command_timeout) {
Ok((0, stdout, _stderr)) => ToolOutcome::ok(stdout),
Ok((2, stdout, stderr)) if first == "wait" => {
let lines: Vec<&str> = stderr.lines().collect();
let tail = if lines.len() > OUTPUT_LINE_BUDGET {
lines[lines.len() - OUTPUT_LINE_BUDGET..].join("\n")
} else {
stderr.trim_end().to_string()
};
let mut parts = vec!["still waiting".to_string()];
if !stdout.trim().is_empty() {
parts.push(stdout.trim_end().to_string());
}
if !tail.trim().is_empty() {
parts.push(tail);
}
ToolOutcome::ok(parts.join("\n"))
}
Ok((code, stdout, stderr)) => {
let lines: Vec<&str> = stderr.lines().collect();
let tail = if lines.len() > OUTPUT_LINE_BUDGET {
lines[lines.len() - OUTPUT_LINE_BUDGET..].join("\n")
} else {
stderr.trim_end().to_string()
};
let mut parts = vec![format!("exit {code}")];
if !stdout.trim().is_empty() {
parts.push(stdout.trim_end().to_string());
}
if !tail.trim().is_empty() {
parts.push(tail);
}
ToolOutcome::err(parts.join("\n"))
}
Err(e) => ToolOutcome::err(e),
}
}
other => ToolOutcome::err(format!("unknown tool: {other}")),
}
}
const BACKGROUND_STARTUP_WAIT: Duration = Duration::from_secs(2);
const BACKGROUND_STARTUP_POLL: Duration = Duration::from_millis(50);
fn run_background_dispatch(
mut cmd_builder: std::process::Command,
root: &Path,
id: &str,
) -> ToolOutcome {
let wt_dir = root.join(".wt");
let out_path = wt_dir.join(format!("{id}.dispatch.out"));
if let Err(e) = std::fs::create_dir_all(&wt_dir) {
return ToolOutcome::err(format!(
"cannot create {} for {}: {e}",
wt_dir.display(),
out_path.display()
));
}
let out_file = match std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(&out_path)
{
Ok(f) => f,
Err(e) => {
return ToolOutcome::err(format!("cannot open {}: {e}", out_path.display()));
}
};
let err_file = match out_file.try_clone() {
Ok(f) => f,
Err(e) => {
return ToolOutcome::err(format!(
"cannot clone output file {}: {e}",
out_path.display()
));
}
};
cmd_builder
.stdout(std::process::Stdio::from(out_file))
.stderr(std::process::Stdio::from(err_file));
let mut child = match cmd_builder.spawn() {
Ok(c) => c,
Err(e) => return ToolOutcome::err(format!("blyte failed to spawn: {e}")),
};
drop(cmd_builder);
let deadline = std::time::Instant::now() + BACKGROUND_STARTUP_WAIT;
let exited = loop {
match child.try_wait() {
Ok(Some(status)) => break Some(status),
Ok(None) => {
let now = std::time::Instant::now();
if now >= deadline {
break None;
}
std::thread::sleep(BACKGROUND_STARTUP_POLL.min(deadline - now));
}
Err(e) => {
return ToolOutcome::err(format!("blyte wait failed for dispatch {id}: {e}"));
}
}
};
match exited {
Some(status) => {
let raw = match std::fs::read(&out_path) {
Ok(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
Err(e) => {
return ToolOutcome::err(format!(
"dispatch {id} exited ({status}), and reading {} failed: {e}",
out_path.display()
));
}
};
let body = raw.trim_end();
if status.success() {
if body.is_empty() {
ToolOutcome::ok(format!("dispatch {id} finished"))
} else {
ToolOutcome::ok(format!("dispatch {id} finished\n{body}"))
}
} else {
let header = match status.code() {
Some(code) => format!("dispatch {id} failed to start (exit {code})"),
None => format!("dispatch {id} failed to start ({status})"),
};
if body.is_empty() {
ToolOutcome::err(header)
} else {
ToolOutcome::err(format!("{header}\n{body}"))
}
}
}
None => {
std::thread::spawn(move || {
let _ = child.wait();
});
ToolOutcome::ok(format!(
"started {id} in the background; use wait to learn when it ends; output: {}",
out_path.display()
))
}
}
}
fn format_dispatch_failure(output: &std::process::Output) -> String {
let stderr_str = String::from_utf8_lossy(&output.stderr);
let lines: Vec<&str> = stderr_str.lines().collect();
let tail = if lines.len() > OUTPUT_LINE_BUDGET {
lines[lines.len() - OUTPUT_LINE_BUDGET..].join("\n")
} else if !stderr_str.trim().is_empty() {
stderr_str.trim_end().to_string()
} else {
match output.status.code() {
Some(code) => format!("exit {code}"),
None => format!("terminated without exit code ({})", output.status),
}
};
let stdout = String::from_utf8_lossy(&output.stdout);
if stdout.trim().is_empty() {
tail
} else {
format!("{}\n{tail}", stdout.trim_end())
}
}
fn serialize_dispatch_args<T: serde::Serialize>(args: &T) -> Result<Vec<u8>, String> {
serde_json::to_vec(args).map_err(|e| format!("dispatch failed to serialize arguments: {e}"))
}
fn dispatch_parent_session() -> String {
std::env::var("BLYTE_SESSION")
.ok()
.filter(|s| !s.is_empty())
.unwrap_or_else(|| {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
format!("{now}-{}", std::process::id())
})
}
fn run_command_bounded(
mut cmd: std::process::Command,
timeout: Duration,
) -> Result<(i32, String, String), String> {
use std::io::Read;
use std::process::Stdio;
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
let mut child = cmd
.spawn()
.map_err(|e| format!("blyte failed to spawn: {e}"))?;
let mut so = child.stdout.take().ok_or("no stdout")?;
let mut se = child.stderr.take().ok_or("no stderr")?;
let t_out = std::thread::spawn(move || {
let mut b = Vec::new();
let _ = so.read_to_end(&mut b);
String::from_utf8_lossy(&b).into_owned()
});
let t_err = std::thread::spawn(move || {
let mut b = Vec::new();
let _ = se.read_to_end(&mut b);
String::from_utf8_lossy(&b).into_owned()
});
let deadline = std::time::Instant::now() + timeout;
let mut poll = POLL_START;
let status = loop {
match child
.try_wait()
.map_err(|e| format!("blyte wait failed: {e}"))?
{
Some(s) => break Some(s),
None if std::time::Instant::now() >= deadline => {
#[cfg(unix)]
{
let pgid = child.id() as i32;
if pgid > 0 {
unsafe {
libc::kill(-pgid, libc::SIGKILL);
}
} else {
let _ = child.kill();
}
}
#[cfg(not(unix))]
{
let _ = child.kill();
}
let _ = child.wait();
break None;
}
None => {
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
let (sleep, next) = poll_backoff(poll, remaining);
std::thread::sleep(sleep);
poll = next;
}
}
};
let stdout = t_out
.join()
.map_err(|_| "blyte: reading the command's output failed".to_string())?;
let stderr = t_err
.join()
.map_err(|_| "blyte: reading the command's errors failed".to_string())?;
match status {
Some(s) => match s.code() {
Some(code) => Ok((code, stdout, stderr)),
None => Err(format!(
"blyte ended without an exit code ({s}); its output so far:\n{stdout}{stderr}"
)),
},
None => Ok((
124,
stdout,
format!("{stderr}\n[killed by blyte after {}s]", timeout.as_secs()),
)),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bash_description_says_background_jobs_keep_running() {
let all = specs();
let desc = &all
.iter()
.find(|t| t.name == "bash")
.expect("bash spec missing")
.description;
assert!(
desc.contains(
"A background job started with its output redirected keeps running after the command returns, and nothing reports when it exits."
),
"got {desc:?}"
);
assert!(
!desc.contains("there is no background mode"),
"got {desc:?}"
);
}
#[test]
fn serialize_dispatch_args_surfaces_serialization_error() {
struct FailingSerialize;
impl serde::Serialize for FailingSerialize {
fn serialize<S: serde::Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
Err(serde::ser::Error::custom("unsupported map key"))
}
}
let err = serialize_dispatch_args(&FailingSerialize).unwrap_err();
assert!(err.contains("serialize"), "got: {err}");
assert!(err.contains("unsupported map key"), "got: {err}");
}
}