Initial public release
Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
181
crates/luxe-tools/src/activate.rs
Normal file
181
crates/luxe-tools/src/activate.rs
Normal file
@@ -0,0 +1,181 @@
|
||||
//! `activate_tools` — load deferred tool schemas on demand (lazy-tools mode).
|
||||
//!
|
||||
//! When the registry is tiered ([`luxe_core::tool::ToolRegistry::set_tiers`]), only a curated
|
||||
//! core set ships in every request; situational tools are listed in the prompt as available and
|
||||
//! their full schemas are withheld until the model activates them here. This shrinks the request
|
||||
//! floor (tool schemas dominate it) and keeps tool-selection accuracy high (which degrades past
|
||||
//! ~30–50 tools).
|
||||
//!
|
||||
//! The tool holds no state. A successful call *is* the activation: the engine reads it back off
|
||||
//! the transcript ([`luxe_core::tool_activation`]) to decide what the next request loads, and an
|
||||
//! adapter that loads tools in place finds it there too.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use luxe_core::provider::ToolSchema;
|
||||
use luxe_core::tool::{Tool, ToolContext, ToolResultData, ACTIVATE_TOOLS_NAME};
|
||||
use serde_json::json;
|
||||
|
||||
/// The `activate_tools` meta-tool, which checks requested names against the deferred set.
|
||||
pub struct ActivateToolsTool {
|
||||
deferred: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl ActivateToolsTool {
|
||||
/// `deferred` is the set of names it may activate.
|
||||
pub fn new(deferred: impl IntoIterator<Item = String>) -> Self {
|
||||
Self { deferred: deferred.into_iter().collect() }
|
||||
}
|
||||
|
||||
fn available(&self) -> String {
|
||||
self.deferred.iter().map(String::as_str).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for ActivateToolsTool {
|
||||
fn name(&self) -> &str {
|
||||
ACTIVATE_TOOLS_NAME
|
||||
}
|
||||
|
||||
fn schema(&self) -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: ACTIVATE_TOOLS_NAME.to_string(),
|
||||
// The names live in the system prompt's catalog, which is always there when this tool
|
||||
// is; listing them here too paid for them twice on every request
|
||||
description: "Load tools that aren't sent up front. Call this with names from the \
|
||||
\"More tools\" list in your instructions, and their full schemas become \
|
||||
available to call on your next step."
|
||||
.to_string(),
|
||||
parameters: json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"names": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Tool names to activate, chosen from the available list."
|
||||
}
|
||||
},
|
||||
"required": ["names"]
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(&self, args: serde_json::Value, _cx: &ToolContext) -> ToolResultData {
|
||||
if args.get("names").and_then(|v| v.as_array()).is_none() {
|
||||
return ToolResultData::error(
|
||||
"Error: 'names' must be an array of tool names to activate.".to_string(),
|
||||
);
|
||||
}
|
||||
// The same reading the engine applies to the transcript, so the two can't disagree
|
||||
let requested = luxe_core::tool_activation::requested_names(&args);
|
||||
if requested.is_empty() {
|
||||
return ToolResultData::error(format!(
|
||||
"Error: 'names' was empty. Available to activate: {}.",
|
||||
self.available()
|
||||
));
|
||||
}
|
||||
|
||||
let (mut activated, mut unknown): (Vec<String>, Vec<String>) =
|
||||
requested.into_iter().partition(|name| self.deferred.contains(name));
|
||||
activated.sort();
|
||||
unknown.sort();
|
||||
|
||||
let mut message = String::new();
|
||||
if !activated.is_empty() {
|
||||
message.push_str(&format!(
|
||||
"Activated: {}. They are now available to call directly on your next step.",
|
||||
activated.join(", ")
|
||||
));
|
||||
}
|
||||
if !unknown.is_empty() {
|
||||
if !message.is_empty() {
|
||||
message.push('\n');
|
||||
}
|
||||
message.push_str(&format!(
|
||||
"Not activatable (already available or unknown): {}. Available to activate: {}.",
|
||||
unknown.join(", "),
|
||||
self.available()
|
||||
));
|
||||
}
|
||||
// A request that activated nothing valid is an error so the model corrects course, and so
|
||||
// the transcript records that nothing was loaded
|
||||
if activated.is_empty() {
|
||||
ToolResultData::error(message)
|
||||
} else {
|
||||
ToolResultData::text(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tool() -> ActivateToolsTool {
|
||||
ActivateToolsTool::new(["debug".to_string(), "ast_grep".to_string()])
|
||||
}
|
||||
|
||||
async fn run(args: serde_json::Value) -> (String, bool) {
|
||||
let (event_tx, _event_rx) = tokio::sync::mpsc::channel(1);
|
||||
let (_cancel_tx, cancel_rx) = tokio::sync::watch::channel(false);
|
||||
let cx = ToolContext {
|
||||
cwd: std::env::temp_dir(),
|
||||
session_id: "s".into(),
|
||||
cancelled: std::sync::Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
};
|
||||
let result = tool().run(args, &cx).await;
|
||||
let text = result
|
||||
.content
|
||||
.iter()
|
||||
.filter_map(|block| match block {
|
||||
luxe_core::ContentBlock::Text(text) => Some(text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<String>();
|
||||
(text, result.is_error)
|
||||
}
|
||||
|
||||
/// The catalog in the system prompt names every deferred tool; the schema shouldn't repeat it.
|
||||
#[test]
|
||||
fn the_schema_does_not_repeat_the_catalog() {
|
||||
let description = tool().schema().description;
|
||||
assert!(
|
||||
!description.contains("ast_grep") && !description.contains("debug"),
|
||||
"{description}"
|
||||
);
|
||||
assert!(description.contains("More tools"), "it says where the names are: {description}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_deferred_tool_activates() {
|
||||
let (text, is_error) = run(json!({ "names": ["debug"] })).await;
|
||||
assert!(!is_error);
|
||||
assert!(text.starts_with("Activated: debug."), "{text}");
|
||||
}
|
||||
|
||||
/// A partly wrong request still loads what it can and names what it couldn't, and it's not an
|
||||
/// error: the engine reads a successful call as an activation of the names it asked for.
|
||||
#[tokio::test]
|
||||
async fn a_mixed_request_loads_what_it_can() {
|
||||
let (text, is_error) = run(json!({ "names": ["read", "debug", "ast_grep"] })).await;
|
||||
assert!(!is_error);
|
||||
assert!(text.contains("Activated: ast_grep, debug."), "{text}");
|
||||
assert!(text.contains("Not activatable (already available or unknown): read."), "{text}");
|
||||
}
|
||||
|
||||
/// Nothing valid is an error, which is also what keeps the transcript from recording a load.
|
||||
#[tokio::test]
|
||||
async fn nothing_valid_is_an_error() {
|
||||
let (text, is_error) = run(json!({ "names": ["read"] })).await;
|
||||
assert!(is_error, "{text}");
|
||||
let (text, is_error) = run(json!({ "names": [] })).await;
|
||||
assert!(is_error && text.contains("was empty"), "{text}");
|
||||
let (text, is_error) = run(json!({ "names": "debug" })).await;
|
||||
assert!(is_error && text.contains("must be an array"), "{text}");
|
||||
}
|
||||
}
|
||||
463
crates/luxe-tools/src/astgrep.rs
Normal file
463
crates/luxe-tools/src/astgrep.rs
Normal file
@@ -0,0 +1,463 @@
|
||||
//! ast-grep — structural search and replace through a verified CLI.
|
||||
//!
|
||||
//! Engine-run calls classify concrete file reads before handing paths to the matcher. Its JSON
|
||||
//! output carries real files, positions and byte ranges. Binary discovery prefers `ast-grep` and
|
||||
//! verifies its version banner because `/usr/bin/sg` can be the unrelated shadow-utils group tool.
|
||||
|
||||
use async_trait::async_trait;
|
||||
use luxe_core::read_tracker::ReadTracker;
|
||||
use luxe_core::{Tool, ToolContext, ToolResultData};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use tokio::process::Command as TokioCommand;
|
||||
use tokio::sync::OnceCell;
|
||||
|
||||
mod guarded;
|
||||
mod render;
|
||||
|
||||
#[cfg(test)]
|
||||
use render::render_matches;
|
||||
use render::search_outcome;
|
||||
|
||||
/// Candidate binary names, best first (`sg` is upstream's deprecated alias).
|
||||
const BINARIES: [&str; 2] = ["ast-grep", "sg"];
|
||||
|
||||
/// What to do when no ast-grep is found.
|
||||
///
|
||||
/// The fallback comes first, deliberately. Leading with the install command invites the model to
|
||||
/// install a build dependency mid-task and then fight its CLI — observed live: one missing binary
|
||||
/// turned into eighteen `bash` calls. `grep` answers most structural searches well enough, and
|
||||
/// installing is the *user's* call.
|
||||
const INSTALL_HINT: &str = "use `grep` for this search instead. (To enable structural search, the \
|
||||
user can install it with `cargo install ast-grep --locked` or \
|
||||
`npm i -g @ast-grep/cli`; on Linux, `/usr/bin/sg` is the unrelated \
|
||||
shadow-utils group tool, so the `ast-grep` binary must be on PATH. Do \
|
||||
not install it yourself.)";
|
||||
|
||||
/// A compact pattern primer, appended when ast-grep rejects the pattern itself.
|
||||
///
|
||||
/// Upstream's message is correct but ends in a documentation URL, which a model cannot open — so a
|
||||
/// rejected pattern is a dead end. Observed: two invalid patterns in a row, then the model
|
||||
/// abandoned the tool for eight `bash` calls. The rules that actually matter fit in five lines.
|
||||
const PATTERN_HELP: &str =
|
||||
"Pattern rules: a pattern must be ONE syntactically valid snippet of the \
|
||||
target language — not a multi-line template, and not a fragment that cannot stand alone. \
|
||||
`$NAME` matches one node, `$$$ARGS` matches a variadic list. Examples: python \
|
||||
`def $NAME($$$ARGS): $$$BODY` · python decorated call `@$DEC` · rust \
|
||||
`fn $NAME($$$ARGS) { $$$BODY }` · typescript `$OBJ.$METHOD($$$ARGS)`. If the shape cannot be \
|
||||
expressed as one snippet (for example \"a function that has any decorator above it\"), that \
|
||||
is not an ast-grep query — use `grep` instead.";
|
||||
|
||||
/// The primer, when the failure is about the pattern rather than the environment.
|
||||
fn pattern_help(stderr: &str) -> Option<&'static str> {
|
||||
let lowered = stderr.to_ascii_lowercase();
|
||||
(lowered.contains("pattern") || lowered.contains("cannot parse")).then_some(PATTERN_HELP)
|
||||
}
|
||||
|
||||
/// Most rendered lines returned for one search — the same bound `grep` and `glob` apply.
|
||||
const MAX_MATCH_LINES: usize = 200;
|
||||
|
||||
/// Most source lines shown per individual match.
|
||||
const MAX_MATCH_BODY_LINES: usize = 6;
|
||||
|
||||
/// Cached resolution of the ast-grep binary. Only a *successful* probe is cached, so installing
|
||||
/// ast-grep mid-session is picked up on the next call.
|
||||
static BINARY: OnceCell<String> = OnceCell::const_new();
|
||||
|
||||
/// One ast-grep match.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct AstGrepMatch {
|
||||
/// File the match was found in.
|
||||
pub file: PathBuf,
|
||||
/// Byte range `(start, end)` of the matched node.
|
||||
pub range: (usize, usize),
|
||||
/// 1-based line of the match's start.
|
||||
pub line: usize,
|
||||
/// 0-based column of the match's start.
|
||||
pub column: usize,
|
||||
/// The matched source text.
|
||||
pub text: String,
|
||||
/// Rewritten text, when the run was a replace.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub replacement: Option<String>,
|
||||
}
|
||||
|
||||
/// ast-grep search parameters.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AstGrepSearchParams {
|
||||
/// SKELETON pattern (e.g., `fn $NAME() { $$$BODY }`).
|
||||
pub pattern: String,
|
||||
/// Language (e.g., "rust", "typescript", "python").
|
||||
pub lang: String,
|
||||
/// Paths to search (defaults to the current directory).
|
||||
#[serde(default, alias = "path", deserialize_with = "one_or_many")]
|
||||
pub paths: Vec<String>,
|
||||
}
|
||||
|
||||
/// `paths` as an array, or as the single `path` string `grep`, `glob` and `read` take.
|
||||
///
|
||||
/// Without it a model writing `path`, as every sibling tool spells it, had its scope dropped in
|
||||
/// silence and searched the whole project: a confident answer to a question it did not ask.
|
||||
fn one_or_many<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<String>, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum OneOrMany {
|
||||
One(String),
|
||||
Many(Vec<String>),
|
||||
}
|
||||
Ok(match OneOrMany::deserialize(deserializer)? {
|
||||
OneOrMany::One(path) => vec![path],
|
||||
OneOrMany::Many(paths) => paths,
|
||||
})
|
||||
}
|
||||
|
||||
/// ast-grep replace parameters.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AstGrepReplaceParams {
|
||||
/// SKELETON pattern.
|
||||
pub pattern: String,
|
||||
/// Rewrite pattern (e.g., `fn $NAME() { /* TODO */ }`).
|
||||
pub rewrite: String,
|
||||
/// Language.
|
||||
pub lang: String,
|
||||
/// Paths to rewrite.
|
||||
#[serde(default, alias = "path", deserialize_with = "one_or_many")]
|
||||
pub paths: Vec<String>,
|
||||
/// Apply the changes; otherwise preview them (default).
|
||||
#[serde(default)]
|
||||
pub apply: bool,
|
||||
}
|
||||
|
||||
/// ast-grep tool: structural search and replace via the `ast-grep` CLI.
|
||||
#[derive(Default)]
|
||||
pub struct AstGrepTool {
|
||||
tracker: Option<Arc<ReadTracker>>,
|
||||
}
|
||||
|
||||
/// Error type for ast-grep operations.
|
||||
#[derive(Debug)]
|
||||
pub enum AstGrepError {
|
||||
/// No usable ast-grep binary on PATH.
|
||||
CliNotFound,
|
||||
/// The CLI ran but failed.
|
||||
CommandFailed(String),
|
||||
/// The CLI's JSON output could not be parsed.
|
||||
ParseError(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for AstGrepError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::CliNotFound => write!(f, "ast-grep CLI not found — {INSTALL_HINT}"),
|
||||
Self::CommandFailed(msg) => match pattern_help(msg) {
|
||||
Some(help) => write!(f, "command failed: {msg}\n\n{help}"),
|
||||
None => write!(f, "command failed: {msg}"),
|
||||
},
|
||||
Self::ParseError(msg) => write!(f, "parse error: {msg}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for AstGrepError {}
|
||||
|
||||
/// Every path worth probing: each known name resolved through `PATH` and then the well-known
|
||||
/// install directories, so a `cargo install`-ed binary is found even when its bin directory never
|
||||
/// made it onto `PATH`.
|
||||
fn candidate_paths() -> Vec<String> {
|
||||
BINARIES
|
||||
.iter()
|
||||
.filter_map(|name| luxe_core::program::resolve(name))
|
||||
.map(|path| path.to_string_lossy().into_owned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Resolve a usable ast-grep binary, or `None` when none is installed.
|
||||
///
|
||||
/// A candidate must exit successfully *and* identify itself as ast-grep — spawning is not enough,
|
||||
/// which is how the shadow-utils `sg` gets mistaken for it.
|
||||
pub async fn resolve_binary() -> Option<String> {
|
||||
if let Some(found) = BINARY.get() {
|
||||
return Some(found.clone());
|
||||
}
|
||||
for candidate in candidate_paths() {
|
||||
let Ok(output) = TokioCommand::new(&candidate)
|
||||
.arg("--version")
|
||||
.stdin(std::process::Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.output()
|
||||
.await
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if identifies_itself(&output) {
|
||||
let _ = BINARY.set(candidate.clone());
|
||||
return Some(candidate);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether what `--version` printed is ast-grep.
|
||||
///
|
||||
/// Both the real binary and its `sg` alias print `ast-grep <version>`; the shadow-utils `sg`
|
||||
/// prints a usage line to stderr and exits non-zero, so it never passes.
|
||||
fn identifies_itself(output: &std::process::Output) -> bool {
|
||||
output.status.success()
|
||||
&& String::from_utf8_lossy(&output.stdout).to_ascii_lowercase().contains("ast-grep")
|
||||
}
|
||||
|
||||
/// Whether a real ast-grep is installed, checked synchronously so registration can skip the tool.
|
||||
///
|
||||
/// Without the binary every call answers "ast-grep CLI not found", which is not worth a schema in
|
||||
/// every request. This runs once at startup and seeds the same cache [`resolve_binary`] reads, so
|
||||
/// the verification is not repeated. It applies the identity check for the same reason that one
|
||||
/// does: the shadow-utils `sg` on `PATH` is not this tool.
|
||||
pub fn is_available() -> bool {
|
||||
if BINARY.get().is_some() {
|
||||
return true;
|
||||
}
|
||||
for candidate in candidate_paths() {
|
||||
let Ok(output) = std::process::Command::new(&candidate)
|
||||
.arg("--version")
|
||||
.stdin(std::process::Stdio::null())
|
||||
.output()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if identifies_itself(&output) {
|
||||
let _ = BINARY.set(candidate);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
impl AstGrepTool {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Attach the shared read tracker, so a file an applied rewrite changed stays editable.
|
||||
pub fn with_tracker(mut self, tracker: Arc<ReadTracker>) -> Self {
|
||||
self.tracker = Some(tracker);
|
||||
self
|
||||
}
|
||||
|
||||
/// Run an ast-grep `run` invocation and parse its streaming JSON output.
|
||||
///
|
||||
/// ast-grep exits non-zero when nothing matched, which is not an error here — it's an empty
|
||||
/// result. A genuine failure (bad pattern, unknown language) also writes to stderr, which is
|
||||
/// what we surface.
|
||||
async fn run_json(args: &[String], cwd: &Path) -> Result<Vec<AstGrepMatch>, AstGrepError> {
|
||||
let binary = resolve_binary().await.ok_or(AstGrepError::CliNotFound)?;
|
||||
let output = TokioCommand::new(&binary)
|
||||
// relative paths and the default scope belong to the session, not the process
|
||||
.current_dir(cwd)
|
||||
// ast-grep searches the paths it is given, never stdin — but the choice is made here
|
||||
// rather than inherited, because a search tool handed a readable stdin can search that.
|
||||
.stdin(std::process::Stdio::null())
|
||||
// A cancelled turn drops this future; without this the scan outlives it.
|
||||
.kill_on_drop(true)
|
||||
.args(args)
|
||||
.output()
|
||||
.await
|
||||
.map_err(|e| AstGrepError::CommandFailed(format!("could not run {binary}: {e}")))?;
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !output.status.success() && stdout.trim().is_empty() && !stderr.trim().is_empty() {
|
||||
return Err(AstGrepError::CommandFailed(stderr.trim().to_string()));
|
||||
}
|
||||
|
||||
let mut matches = Vec::new();
|
||||
for line in stdout.lines().filter(|line| !line.trim().is_empty()) {
|
||||
let value: serde_json::Value = serde_json::from_str(line)
|
||||
.map_err(|e| AstGrepError::ParseError(format!("{e}: {line}")))?;
|
||||
matches.push(parse_match(&value)?);
|
||||
}
|
||||
Ok(matches)
|
||||
}
|
||||
|
||||
/// Structural search, run in `cwd`.
|
||||
pub async fn search(
|
||||
params: &AstGrepSearchParams,
|
||||
cwd: &Path,
|
||||
) -> Result<Vec<AstGrepMatch>, AstGrepError> {
|
||||
let mut args = base_args(¶ms.pattern, ¶ms.lang);
|
||||
args.push("--json=stream".to_string());
|
||||
// a file named like a flag stays a file
|
||||
args.push("--".to_string());
|
||||
args.extend(params.paths.iter().cloned());
|
||||
Self::run_json(&args, cwd).await
|
||||
}
|
||||
|
||||
/// Structural replace, run in `cwd`: previews the rewrites, or applies them when `apply` is
|
||||
/// set, to exactly the files the preview matched.
|
||||
pub async fn replace(
|
||||
params: &AstGrepReplaceParams,
|
||||
cwd: &Path,
|
||||
) -> Result<Vec<AstGrepMatch>, AstGrepError> {
|
||||
// Collect the matches (with their replacements) first, so preview and apply report the
|
||||
// same thing and an apply can say exactly what it changed.
|
||||
let mut args = base_args(¶ms.pattern, ¶ms.lang);
|
||||
args.extend(["--rewrite".to_string(), params.rewrite.clone()]);
|
||||
args.push("--json=stream".to_string());
|
||||
// a file named like a flag stays a file
|
||||
args.push("--".to_string());
|
||||
args.extend(params.paths.iter().cloned());
|
||||
let matches = Self::run_json(&args, cwd).await?;
|
||||
|
||||
if params.apply && !matches.is_empty() {
|
||||
let binary = resolve_binary().await.ok_or(AstGrepError::CliNotFound)?;
|
||||
let mut apply_args = base_args(¶ms.pattern, ¶ms.lang);
|
||||
apply_args.extend(["--rewrite".to_string(), params.rewrite.clone()]);
|
||||
apply_args.push("--update-all".to_string());
|
||||
// the previewed files, not a fresh scan of the scope that could find something new
|
||||
let mut previewed: Vec<String> =
|
||||
matches.iter().map(|item| luxe_core::paths::display(&item.file)).collect();
|
||||
previewed.sort();
|
||||
previewed.dedup();
|
||||
apply_args.push("--".to_string());
|
||||
apply_args.extend(previewed);
|
||||
let output = TokioCommand::new(&binary)
|
||||
.current_dir(cwd)
|
||||
.args(&apply_args)
|
||||
.stdin(std::process::Stdio::null())
|
||||
// A cancelled turn drops this future; without this the rewrite outlives it.
|
||||
.kill_on_drop(true)
|
||||
.output()
|
||||
.await
|
||||
.map_err(|e| AstGrepError::CommandFailed(format!("could not run {binary}: {e}")))?;
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
return Err(AstGrepError::CommandFailed(stderr.trim().to_string()));
|
||||
}
|
||||
}
|
||||
Ok(matches)
|
||||
}
|
||||
}
|
||||
|
||||
/// The shared leading arguments for a `run` invocation.
|
||||
fn base_args(pattern: &str, lang: &str) -> Vec<String> {
|
||||
vec![
|
||||
"run".to_string(),
|
||||
"--pattern".to_string(),
|
||||
pattern.to_string(),
|
||||
"--lang".to_string(),
|
||||
lang.to_string(),
|
||||
"--color".to_string(),
|
||||
"never".to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
/// Convert one ast-grep JSON match object into an [`AstGrepMatch`].
|
||||
fn parse_match(value: &serde_json::Value) -> Result<AstGrepMatch, AstGrepError> {
|
||||
let missing = |field: &str| AstGrepError::ParseError(format!("match is missing `{field}`"));
|
||||
let file = value.get("file").and_then(|v| v.as_str()).ok_or_else(|| missing("file"))?;
|
||||
let text = value.get("text").and_then(|v| v.as_str()).unwrap_or_default();
|
||||
let range = value.get("range").ok_or_else(|| missing("range"))?;
|
||||
let byte = range.get("byteOffset");
|
||||
let start = byte.and_then(|b| b.get("start")).and_then(serde_json::Value::as_u64).unwrap_or(0);
|
||||
let end = byte.and_then(|b| b.get("end")).and_then(serde_json::Value::as_u64).unwrap_or(0);
|
||||
let position = range.get("start");
|
||||
let line =
|
||||
position.and_then(|p| p.get("line")).and_then(serde_json::Value::as_u64).unwrap_or(0);
|
||||
let column =
|
||||
position.and_then(|p| p.get("column")).and_then(serde_json::Value::as_u64).unwrap_or(0);
|
||||
Ok(AstGrepMatch {
|
||||
file: PathBuf::from(file),
|
||||
range: (start as usize, end as usize),
|
||||
// ast-grep reports 0-based lines; every other Luxe surface is 1-based.
|
||||
line: line as usize + 1,
|
||||
column: column as usize,
|
||||
text: text.to_string(),
|
||||
replacement: value
|
||||
.get("replacement")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(std::string::ToString::to_string),
|
||||
})
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for AstGrepTool {
|
||||
fn name(&self) -> &str {
|
||||
"ast_grep"
|
||||
}
|
||||
|
||||
fn schema(&self) -> luxe_core::ToolSchema {
|
||||
luxe_core::ToolSchema {
|
||||
name: "ast_grep".to_string(),
|
||||
description: "AST-aware structural search and replace via ast-grep. Match code by its \
|
||||
syntax tree, not text — use it to find or rewrite code patterns (e.g. all \
|
||||
calls to a function, a specific match arm shape) reliably across \
|
||||
formatting. Patterns use metavariables: `$VAR` matches one node, `$$$ARGS` \
|
||||
matches a variadic list. Prefer this over grep for code-structure edits; \
|
||||
use grep for plain text. action=replace previews the rewrite unless \
|
||||
apply=true."
|
||||
.to_string(),
|
||||
parameters: serde_json::json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["search", "replace"],
|
||||
"description": "search = find matches; replace = rewrite matches (needs `rewrite`)"
|
||||
},
|
||||
"pattern": {
|
||||
"type": "string",
|
||||
"description": "ast-grep pattern with metavariables, e.g. `foo($$$ARGS)` or `if let Some($X) = $Y { $$$BODY }`"
|
||||
},
|
||||
"rewrite": {
|
||||
"type": "string",
|
||||
"description": "replace only: replacement pattern reusing the same metavariables, e.g. `bar($$$ARGS)`"
|
||||
},
|
||||
"lang": {
|
||||
"type": "string",
|
||||
"description": "language id: rust | python | typescript | tsx | javascript | go | c | cpp | java | …"
|
||||
},
|
||||
"paths": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" },
|
||||
"description": "files or directories to scan (relative to cwd; default: the whole project). A single `path` string works too"
|
||||
},
|
||||
"apply": {
|
||||
"type": "boolean",
|
||||
"description": "replace only: write changes to disk (default false = preview the rewrite)"
|
||||
}
|
||||
},
|
||||
"required": ["action", "pattern", "lang"]
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_with_read_hook(
|
||||
&self,
|
||||
params: serde_json::Value,
|
||||
cx: &ToolContext,
|
||||
read_hook: &dyn luxe_core::tool::FileReadHook,
|
||||
) -> luxe_core::ToolResultData {
|
||||
guarded::run(self, params, cx, read_hook).await
|
||||
}
|
||||
|
||||
async fn run(&self, params: serde_json::Value, cx: &ToolContext) -> luxe_core::ToolResultData {
|
||||
let action = params.get("action").and_then(|v| v.as_str()).unwrap_or("search");
|
||||
match action {
|
||||
"search" => match serde_json::from_value::<AstGrepSearchParams>(params) {
|
||||
Ok(search) => search_outcome(Self::search(&search, &cx.cwd).await),
|
||||
Err(e) => ToolResultData::error(format!("Invalid params: {e}")),
|
||||
},
|
||||
"replace" => match serde_json::from_value::<AstGrepReplaceParams>(params) {
|
||||
Ok(replace) => {
|
||||
let found = Self::replace(&replace, &cx.cwd).await;
|
||||
render::finish_replace(self, found, replace.apply, cx).await
|
||||
}
|
||||
Err(e) => ToolResultData::error(format!("Invalid params: {e}")),
|
||||
},
|
||||
other => ToolResultData::error(format!("Unknown action: {other}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
257
crates/luxe-tools/src/astgrep/guarded.rs
Normal file
257
crates/luxe-tools/src/astgrep/guarded.rs
Normal file
@@ -0,0 +1,257 @@
|
||||
//! Guarded structural search — approve concrete read paths before invoking the matcher.
|
||||
//!
|
||||
//! The matcher gets the approved files themselves, never a directory it could read past the
|
||||
//! policy in, in batches under the platform's command-line limit. It runs in the session's working
|
||||
//! directory, the one the walk listed them from, so they go as the walk wrote them.
|
||||
|
||||
use super::*;
|
||||
use crate::walk::{StopOnDrop, Walked};
|
||||
use luxe_core::permission::PermissionAction;
|
||||
use luxe_core::tool::FileReadHook;
|
||||
use std::path::Path;
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
/// Bytes of path arguments one invocation carries. Windows caps a whole command line at 32K
|
||||
/// characters; unix allows far more, and fewer batches mean fewer process starts.
|
||||
#[cfg(windows)]
|
||||
const ARGUMENT_BUDGET: usize = 24 * 1024;
|
||||
#[cfg(not(windows))]
|
||||
const ARGUMENT_BUDGET: usize = 256 * 1024;
|
||||
|
||||
pub(super) enum Call {
|
||||
Search(AstGrepSearchParams),
|
||||
Replace(AstGrepReplaceParams),
|
||||
}
|
||||
|
||||
impl Call {
|
||||
pub(super) fn parse(params: serde_json::Value) -> Result<Self, String> {
|
||||
let action = params.get("action").and_then(|value| value.as_str()).unwrap_or("search");
|
||||
match action {
|
||||
"search" => serde_json::from_value(params).map(Self::Search),
|
||||
"replace" => serde_json::from_value(params).map(Self::Replace),
|
||||
other => return Err(format!("Unknown action: {other}")),
|
||||
}
|
||||
.map_err(|error| format!("Invalid params: {error}"))
|
||||
}
|
||||
|
||||
fn roots(&self) -> Vec<String> {
|
||||
let paths = match self {
|
||||
Self::Search(search) => &search.paths,
|
||||
Self::Replace(replace) => &replace.paths,
|
||||
};
|
||||
if paths.is_empty() {
|
||||
vec![".".into()]
|
||||
} else {
|
||||
paths.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the matcher once per batch and report every batch's matches as one result.
|
||||
pub(super) async fn over(
|
||||
mut self,
|
||||
tool: &AstGrepTool,
|
||||
batches: Vec<Vec<String>>,
|
||||
cx: &ToolContext,
|
||||
) -> luxe_core::ToolResultData {
|
||||
let mut matches = Vec::new();
|
||||
for batch in batches {
|
||||
let found = match &mut self {
|
||||
Self::Search(search) => {
|
||||
search.paths = batch;
|
||||
AstGrepTool::search(search, &cx.cwd).await
|
||||
}
|
||||
Self::Replace(replace) => {
|
||||
replace.paths = batch;
|
||||
AstGrepTool::replace(replace, &cx.cwd).await
|
||||
}
|
||||
};
|
||||
if let Err(error) = found.map(|found| matches.extend(found)) {
|
||||
return self.failed_after(tool, matches, error, cx).await;
|
||||
}
|
||||
}
|
||||
self.outcome(tool, Ok(matches), cx).await
|
||||
}
|
||||
|
||||
/// A later batch failed: an apply says what the earlier batches already rewrote.
|
||||
async fn failed_after(
|
||||
&self,
|
||||
tool: &AstGrepTool,
|
||||
matches: Vec<AstGrepMatch>,
|
||||
error: AstGrepError,
|
||||
cx: &ToolContext,
|
||||
) -> luxe_core::ToolResultData {
|
||||
match self {
|
||||
Self::Replace(replace) if replace.apply && !matches.is_empty() => {
|
||||
let mut result = super::render::finish_replace(tool, Ok(matches), true, cx).await;
|
||||
result.content.push(luxe_core::ContentBlock::Text(format!(
|
||||
"then ast-grep replace error: {error}; the rewrites above are on disk"
|
||||
)));
|
||||
result.is_error = true;
|
||||
result
|
||||
}
|
||||
_ => self.outcome(tool, Err(error), cx).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn outcome(
|
||||
&self,
|
||||
tool: &AstGrepTool,
|
||||
found: Result<Vec<AstGrepMatch>, AstGrepError>,
|
||||
cx: &ToolContext,
|
||||
) -> luxe_core::ToolResultData {
|
||||
match self {
|
||||
Self::Search(_) => search_outcome(found),
|
||||
Self::Replace(replace) => {
|
||||
super::render::finish_replace(tool, found, replace.apply, cx).await
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Split `paths` into runs whose argument bytes stay within `budget`; one oversized path still
|
||||
/// gets a batch of its own rather than being dropped.
|
||||
fn batches(paths: Vec<String>, budget: usize) -> Vec<Vec<String>> {
|
||||
let (mut batches, mut current, mut used) = (Vec::new(), Vec::new(), 0);
|
||||
for path in paths {
|
||||
let cost = path.len() + 1;
|
||||
if !current.is_empty() && used + cost > budget {
|
||||
batches.push(std::mem::take(&mut current));
|
||||
used = 0;
|
||||
}
|
||||
used += cost;
|
||||
current.push(path);
|
||||
}
|
||||
if !current.is_empty() {
|
||||
batches.push(current);
|
||||
}
|
||||
batches
|
||||
}
|
||||
|
||||
async fn candidates(
|
||||
cx: &ToolContext,
|
||||
roots: Vec<String>,
|
||||
stopped: Arc<AtomicBool>,
|
||||
) -> Result<Walked, String> {
|
||||
let cwd = cx.cwd.clone();
|
||||
let cancelled = cx.cancelled.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut all = Walked { files: Vec::new(), capped: false };
|
||||
for root in roots {
|
||||
let stop_walk = stopped.clone();
|
||||
let cancel_walk = cancelled.clone();
|
||||
let walked = crate::walk::files_until(&cwd, Path::new(&root), false, None, move || {
|
||||
stop_walk.load(Ordering::Relaxed) || *cancel_walk.borrow()
|
||||
});
|
||||
all.files.extend(walked.files);
|
||||
all.capped |= walked.capped;
|
||||
if stopped.load(Ordering::Relaxed) || *cancelled.borrow() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
all.files.sort();
|
||||
all.files.dedup();
|
||||
all
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("ast-grep candidate walk failed: {error}"))
|
||||
}
|
||||
|
||||
struct ReadPlan {
|
||||
allowed: Vec<String>,
|
||||
denied: usize,
|
||||
asks: usize,
|
||||
}
|
||||
|
||||
fn classify(files: Vec<PathBuf>, hook: &dyn FileReadHook) -> ReadPlan {
|
||||
let mut plan = ReadPlan { allowed: Vec::new(), denied: 0, asks: 0 };
|
||||
for file in files {
|
||||
match hook.decision(&file) {
|
||||
PermissionAction::Allow => plan.allowed.push(luxe_core::paths::display(&file)),
|
||||
PermissionAction::Deny => plan.denied += 1,
|
||||
PermissionAction::Ask => plan.asks += 1,
|
||||
}
|
||||
}
|
||||
plan
|
||||
}
|
||||
|
||||
pub(super) async fn run(
|
||||
tool: &AstGrepTool,
|
||||
params: serde_json::Value,
|
||||
cx: &ToolContext,
|
||||
hook: &dyn FileReadHook,
|
||||
) -> luxe_core::ToolResultData {
|
||||
let call = match Call::parse(params) {
|
||||
Ok(call) => call,
|
||||
Err(error) => return ToolResultData::error(error),
|
||||
};
|
||||
let stopped = Arc::new(AtomicBool::new(false));
|
||||
let _stop_on_drop = StopOnDrop(stopped.clone());
|
||||
let walked = match candidates(cx, call.roots(), stopped).await {
|
||||
Ok(walked) => walked,
|
||||
Err(error) => return ToolResultData::error(error),
|
||||
};
|
||||
let plan = classify(walked.files, hook);
|
||||
let mut result = if plan.allowed.is_empty() {
|
||||
ToolResultData::text("no policy-approved files to search")
|
||||
} else {
|
||||
call.over(tool, batches(plan.allowed, ARGUMENT_BUDGET), cx).await
|
||||
};
|
||||
if plan.denied + plan.asks > 0 {
|
||||
result.content.push(luxe_core::ContentBlock::Text(format!(
|
||||
"skipped {} files denied by read policy; {} files require approval and were not read",
|
||||
plan.denied, plan.asks
|
||||
)));
|
||||
}
|
||||
if walked.capped {
|
||||
result.content.push(luxe_core::ContentBlock::Text(crate::walk::capped_notice()));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use luxe_core::permission::{PermissionEngine, PermissionMode, Rule};
|
||||
|
||||
/// Candidate classification must preserve Ask and user denials even when default guards opt out.
|
||||
#[test]
|
||||
fn candidate_reads_honor_yolo_denials_and_approval_requirements() {
|
||||
let policy = PermissionEngine::assemble(
|
||||
PermissionMode::Yolo,
|
||||
vec![
|
||||
Rule {
|
||||
permission: "read".into(),
|
||||
pattern: "blocked.rs".into(),
|
||||
action: PermissionAction::Deny,
|
||||
},
|
||||
Rule {
|
||||
permission: "read".into(),
|
||||
pattern: "review.rs".into(),
|
||||
action: PermissionAction::Ask,
|
||||
},
|
||||
],
|
||||
vec![],
|
||||
false,
|
||||
);
|
||||
let files = [".env", "blocked.rs", "review.rs"].map(PathBuf::from).to_vec();
|
||||
let plan = classify(files, &policy);
|
||||
assert_eq!(plan.allowed, [".env"]);
|
||||
assert_eq!(plan.denied, 1);
|
||||
assert_eq!(plan.asks, 1);
|
||||
}
|
||||
|
||||
/// One invocation per project file list would overflow a command line on a large tree.
|
||||
#[test]
|
||||
fn approved_files_are_batched_within_the_argument_budget() {
|
||||
let paths: Vec<String> = (0..10).map(|n| format!("/project/src/file_{n}.rs")).collect();
|
||||
let batched = batches(paths.clone(), 60);
|
||||
assert!(batched.len() > 1, "{batched:?}");
|
||||
assert!(batched.iter().all(|batch| batch.iter().map(|p| p.len() + 1).sum::<usize>() <= 60));
|
||||
assert_eq!(batched.concat(), paths);
|
||||
let oversized = vec!["x".repeat(100), "y".into()];
|
||||
assert_eq!(batches(oversized.clone(), 60), [vec![oversized[0].clone()], vec!["y".into()]]);
|
||||
}
|
||||
}
|
||||
109
crates/luxe-tools/src/astgrep/render.rs
Normal file
109
crates/luxe-tools/src/astgrep/render.rs
Normal file
@@ -0,0 +1,109 @@
|
||||
//! ast-grep output — what a call reports, and what an applied rewrite tells the rest of Luxe.
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) fn search_outcome(
|
||||
found: Result<Vec<AstGrepMatch>, AstGrepError>,
|
||||
) -> luxe_core::ToolResultData {
|
||||
match found {
|
||||
Ok(matches) => ToolResultData::text(render_matches(&matches, false)),
|
||||
Err(e) => ToolResultData::error(format!("ast-grep search error: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Report a replace, first announcing each file an applied rewrite changed.
|
||||
pub(super) async fn finish_replace(
|
||||
tool: &AstGrepTool,
|
||||
found: Result<Vec<AstGrepMatch>, AstGrepError>,
|
||||
applied: bool,
|
||||
cx: &ToolContext,
|
||||
) -> luxe_core::ToolResultData {
|
||||
let injected = match (&found, applied) {
|
||||
(Ok(matches), true) => announce(tool, matches, cx).await,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let mut result = replace_outcome(found, applied);
|
||||
if !injected.is_empty() {
|
||||
let diagnostics = format!("\n--- Diagnostics ---\n{}", injected.join("\n"));
|
||||
result.content.push(luxe_core::ContentBlock::Text(diagnostics));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// `FileChanged` and the read tracker for every rewritten file, as an `edit` would get.
|
||||
async fn announce(tool: &AstGrepTool, matches: &[AstGrepMatch], cx: &ToolContext) -> Vec<String> {
|
||||
let mut files: Vec<&PathBuf> = matches.iter().map(|item| &item.file).collect();
|
||||
files.sort();
|
||||
files.dedup();
|
||||
let mut injected = Vec::new();
|
||||
for file in files {
|
||||
let path = cx.cwd.join(file);
|
||||
injected.extend(cx.file_changed(&path, "edit").await);
|
||||
if let Some(tracker) = &tool.tracker {
|
||||
tracker.record(&cx.session_id, &path);
|
||||
}
|
||||
}
|
||||
injected
|
||||
}
|
||||
|
||||
fn replace_outcome(
|
||||
found: Result<Vec<AstGrepMatch>, AstGrepError>,
|
||||
applied: bool,
|
||||
) -> luxe_core::ToolResultData {
|
||||
match found {
|
||||
Ok(matches) => {
|
||||
let mut body = render_matches(&matches, applied);
|
||||
if !applied && !matches.is_empty() {
|
||||
body.push_str("\npreview only — re-run with apply=true to write");
|
||||
}
|
||||
ToolResultData::text(body)
|
||||
}
|
||||
Err(e) => ToolResultData::error(format!("ast-grep replace error: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Render matches as a compact, model-friendly listing (not raw JSON).
|
||||
pub(super) fn render_matches(matches: &[AstGrepMatch], applied: bool) -> String {
|
||||
if matches.is_empty() {
|
||||
return "no matches".to_string();
|
||||
}
|
||||
let mut out = String::new();
|
||||
let verb = if applied { "rewrote" } else { "found" };
|
||||
out.push_str(&format!("{verb} {} match(es)\n", matches.len()));
|
||||
for item in matches {
|
||||
out.push_str(&format!(
|
||||
"{}:{}:{}\n",
|
||||
luxe_core::paths::display(&item.file),
|
||||
item.line,
|
||||
item.column
|
||||
));
|
||||
out.push_str(&excerpt(&item.text, " - "));
|
||||
if let Some(replacement) = &item.replacement {
|
||||
out.push_str(&excerpt(replacement, " + "));
|
||||
}
|
||||
}
|
||||
// Every other search tool bounds what it hands back; this one did not, and a structural
|
||||
// pattern matching whole function bodies across a large repo produced a payload that
|
||||
// *exceeded the model's context window* and killed the turn outright. A search must degrade
|
||||
// to "here is the head, narrow it" — never to a dead turn.
|
||||
crate::output_limit::cap_lines(
|
||||
&out,
|
||||
MAX_MATCH_LINES,
|
||||
"lines",
|
||||
"Narrow the pattern or pass `paths` to scope the search.",
|
||||
)
|
||||
}
|
||||
|
||||
/// One match's source, capped: a structural pattern can match an entire function body, and the
|
||||
/// opening lines are what identify it.
|
||||
fn excerpt(text: &str, prefix: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let total = text.lines().count();
|
||||
for line in text.lines().take(MAX_MATCH_BODY_LINES) {
|
||||
out.push_str(&format!("{prefix}{line}\n"));
|
||||
}
|
||||
if total > MAX_MATCH_BODY_LINES {
|
||||
out.push_str(&format!("{prefix}… ({} more lines)\n", total - MAX_MATCH_BODY_LINES));
|
||||
}
|
||||
out
|
||||
}
|
||||
320
crates/luxe-tools/src/astgrep/tests.rs
Normal file
320
crates/luxe-tools/src/astgrep/tests.rs
Normal file
@@ -0,0 +1,320 @@
|
||||
use super::*;
|
||||
|
||||
mod read_policy;
|
||||
#[cfg(unix)] // the stub CLI is a shell script
|
||||
mod session_cwd;
|
||||
|
||||
/// A stand-in CLI on PATH: `name` becomes an executable shell script printing `body`, so the
|
||||
/// tool can be driven without a real ast-grep install.
|
||||
///
|
||||
/// Writing a script and immediately exec'ing it races the kernel: while any handle is still
|
||||
/// open for writing, `execve` returns `ETXTBSY` ("Text file busy"). It only shows up under
|
||||
/// parallel test load, which makes it the worst kind of flake — so the handle is synced and
|
||||
/// dropped explicitly, before the mode is set.
|
||||
///
|
||||
/// Unix-only, like every test that uses it: the stub is a `#!/bin/sh` script.
|
||||
#[cfg(unix)]
|
||||
fn fake_binary(dir: &std::path::Path, name: &str, body: &str) {
|
||||
use std::io::Write as _;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let path = dir.join(name);
|
||||
{
|
||||
let mut file = std::fs::File::create(&path).expect("create fake binary");
|
||||
file.write_all(body.as_bytes()).expect("write fake binary");
|
||||
file.sync_all().expect("flush fake binary");
|
||||
}
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))
|
||||
.expect("chmod fake binary");
|
||||
}
|
||||
|
||||
/// Run a just-written stub, retrying the one failure that is nobody's fault.
|
||||
///
|
||||
/// Linux refuses to exec a file any process holds open for writing (`ETXTBSY`), and in a
|
||||
/// multithreaded test binary that is reachable without doing anything wrong: the write handle
|
||||
/// above is closed before the mode is set, but a *sibling* test spawning a process forks the whole
|
||||
/// descriptor table first and only drops its copy at its own `exec`. Land inside that window and
|
||||
/// this exec fails with "Text file busy".
|
||||
///
|
||||
/// The window is microseconds wide and cannot be closed from this side, so the answer is to try
|
||||
/// again rather than to let the suite's reliability depend on scheduling.
|
||||
#[cfg(unix)]
|
||||
async fn run_fake(binary: &std::path::Path, args: &[String]) -> std::process::Output {
|
||||
for attempt in 0..50u64 {
|
||||
match tokio::process::Command::new(binary).args(args).output().await {
|
||||
Ok(output) => return output,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::ExecutableFileBusy => {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(2 * (attempt + 1))).await;
|
||||
}
|
||||
Err(error) => panic!("run {}: {error}", binary.display()),
|
||||
}
|
||||
}
|
||||
panic!("{} stayed busy: a sibling test is holding it open", binary.display());
|
||||
}
|
||||
|
||||
/// The scope arrives however a model spells it: an array of `paths`, or one `path` like the
|
||||
/// sibling tools take. Dropping the second searched the whole project instead.
|
||||
#[test]
|
||||
fn a_single_path_scopes_the_search_like_paths_does() {
|
||||
let one: AstGrepSearchParams = serde_json::from_value(serde_json::json!(
|
||||
{"pattern": "$X.unwrap()", "lang": "rust", "path": "src/a.rs"}
|
||||
))
|
||||
.expect("parses");
|
||||
assert_eq!(one.paths, ["src/a.rs"]);
|
||||
let many: AstGrepSearchParams = serde_json::from_value(serde_json::json!(
|
||||
{"pattern": "$X", "lang": "rust", "paths": ["a", "b"]}
|
||||
))
|
||||
.expect("parses");
|
||||
assert_eq!(many.paths, ["a", "b"]);
|
||||
let none: AstGrepSearchParams =
|
||||
serde_json::from_value(serde_json::json!({"pattern": "$X", "lang": "rust"}))
|
||||
.expect("parses");
|
||||
assert!(none.paths.is_empty());
|
||||
let replace: AstGrepReplaceParams = serde_json::from_value(serde_json::json!(
|
||||
{"pattern": "$X", "rewrite": "$X", "lang": "rust", "path": "src"}
|
||||
))
|
||||
.expect("parses");
|
||||
assert_eq!(replace.paths, ["src"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_match_parses_into_file_position_and_range() {
|
||||
let value: serde_json::Value = serde_json::from_str(
|
||||
r#"{"text":"helper(1, 2)","range":{"byteOffset":{"start":37,"end":49},
|
||||
"start":{"line":2,"column":4},"end":{"line":2,"column":16}},
|
||||
"file":"src/a.rs","replacement":"assist(1, 2)"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let parsed = parse_match(&value).expect("parse");
|
||||
assert_eq!(parsed.file, PathBuf::from("src/a.rs"));
|
||||
assert_eq!(parsed.range, (37, 49));
|
||||
assert_eq!(parsed.line, 3, "ast-grep's 0-based line becomes 1-based");
|
||||
assert_eq!(parsed.column, 4);
|
||||
assert_eq!(parsed.text, "helper(1, 2)");
|
||||
assert_eq!(parsed.replacement.as_deref(), Some("assist(1, 2)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_render_as_a_compact_listing_with_the_rewrite() {
|
||||
let matches = vec![AstGrepMatch {
|
||||
file: PathBuf::from("src/a.rs"),
|
||||
range: (37, 49),
|
||||
line: 3,
|
||||
column: 4,
|
||||
text: "helper(1, 2)".into(),
|
||||
replacement: Some("assist(1, 2)".into()),
|
||||
}];
|
||||
let rendered = render_matches(&matches, false);
|
||||
assert!(rendered.contains("found 1 match(es)"));
|
||||
assert!(rendered.contains("src/a.rs:3:4"));
|
||||
assert!(rendered.contains(" - helper(1, 2)"));
|
||||
assert!(rendered.contains(" + assist(1, 2)"));
|
||||
assert_eq!(render_matches(&[], false), "no matches");
|
||||
}
|
||||
|
||||
/// A `sg` on PATH that is the shadow-utils group tool spawns fine and must still be rejected.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_colliding_unix_sg_is_not_mistaken_for_ast_grep() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
fake_binary(
|
||||
dir.path(),
|
||||
"sg",
|
||||
"#!/bin/sh\necho 'Usage: sg [-] group [[-c] command]' >&2\nexit 1\n",
|
||||
);
|
||||
// Probe the fake directly rather than through PATH (the resolution cache is per-process).
|
||||
let output = run_fake(&dir.path().join("sg"), &["--version".to_string()]).await;
|
||||
assert!(!output.status.success(), "the group tool exits non-zero");
|
||||
assert!(
|
||||
!String::from_utf8_lossy(&output.stdout).to_ascii_lowercase().contains("ast-grep"),
|
||||
"and never claims to be ast-grep"
|
||||
);
|
||||
}
|
||||
|
||||
/// End-to-end against a fake ast-grep that emits real streaming JSON: proves the argument
|
||||
/// shape and the parser agree without needing the binary installed.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_stub_cli_drives_search_argument_shape_and_parsing() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
let args_log = dir.path().join("args.txt");
|
||||
fake_binary(
|
||||
dir.path(),
|
||||
"ast-grep",
|
||||
&format!(
|
||||
"#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then echo 'ast-grep 0.45.0'; exit 0; fi\n\
|
||||
printf '%s\\n' \"$*\" > {log}\n\
|
||||
echo '{{\"text\":\"foo()\",\"range\":{{\"byteOffset\":{{\"start\":1,\"end\":6}},\
|
||||
\"start\":{{\"line\":0,\"column\":2}}}},\"file\":\"x.rs\"}}'\n",
|
||||
log = args_log.display()
|
||||
),
|
||||
);
|
||||
|
||||
let binary = dir.path().join("ast-grep");
|
||||
let mut args = base_args("foo()", "rust");
|
||||
args.push("--json=stream".to_string());
|
||||
let output = run_fake(&binary, &args).await;
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_str(stdout.lines().next().expect("one match")).expect("json");
|
||||
let parsed = parse_match(&value).expect("parse");
|
||||
assert_eq!(parsed.file, PathBuf::from("x.rs"));
|
||||
assert_eq!(parsed.line, 1);
|
||||
|
||||
let logged = std::fs::read_to_string(&args_log).expect("args log");
|
||||
assert!(logged.contains("run"), "uses the `run` subcommand: {logged}");
|
||||
assert!(logged.contains("--pattern foo()"), "passes --pattern: {logged}");
|
||||
assert!(logged.contains("--lang rust"), "passes --lang: {logged}");
|
||||
assert!(logged.contains("--json=stream"), "asks for streaming JSON: {logged}");
|
||||
assert!(!logged.contains("search"), "there is no `search` subcommand: {logged}");
|
||||
}
|
||||
|
||||
/// Runs only where a real ast-grep is installed; skipped otherwise so CI stays hermetic.
|
||||
#[tokio::test]
|
||||
async fn a_real_ast_grep_finds_a_structural_match() {
|
||||
let Some(_binary) = resolve_binary().await else {
|
||||
eprintln!("skipping: no ast-grep on PATH");
|
||||
return;
|
||||
};
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
std::fs::write(
|
||||
dir.path().join("a.rs"),
|
||||
"fn main() {\n helper(1, 2);\n}\nfn helper(a: i32, b: i32) -> i32 { a + b }\n",
|
||||
)
|
||||
.expect("write source");
|
||||
|
||||
let found = AstGrepTool::search(
|
||||
&AstGrepSearchParams {
|
||||
pattern: "helper($$$ARGS)".to_string(),
|
||||
lang: "rust".to_string(),
|
||||
paths: vec![dir.path().display().to_string()],
|
||||
},
|
||||
dir.path(),
|
||||
)
|
||||
.await
|
||||
.expect("search runs");
|
||||
assert_eq!(found.len(), 1, "the call site matches structurally: {found:?}");
|
||||
assert_eq!(found[0].line, 2);
|
||||
assert_eq!(found[0].text, "helper(1, 2)");
|
||||
|
||||
// No matches is an empty result, not an error — ast-grep exits non-zero for it.
|
||||
let none = AstGrepTool::search(
|
||||
&AstGrepSearchParams {
|
||||
pattern: "definitely_not_here($$$A)".to_string(),
|
||||
lang: "rust".to_string(),
|
||||
paths: vec![dir.path().display().to_string()],
|
||||
},
|
||||
dir.path(),
|
||||
)
|
||||
.await
|
||||
.expect("an empty result is not an error");
|
||||
assert!(none.is_empty());
|
||||
|
||||
// A preview reports the rewrite without touching the file; apply writes it.
|
||||
let params = AstGrepReplaceParams {
|
||||
pattern: "helper($$$ARGS)".to_string(),
|
||||
rewrite: "assist($$$ARGS)".to_string(),
|
||||
lang: "rust".to_string(),
|
||||
paths: vec![dir.path().display().to_string()],
|
||||
apply: false,
|
||||
};
|
||||
let preview = AstGrepTool::replace(¶ms, dir.path()).await.expect("preview runs");
|
||||
assert_eq!(preview[0].replacement.as_deref(), Some("assist(1, 2)"));
|
||||
assert!(std::fs::read_to_string(dir.path().join("a.rs")).unwrap().contains("helper(1, 2)"));
|
||||
|
||||
let applied = AstGrepReplaceParams { apply: true, ..params };
|
||||
AstGrepTool::replace(&applied, dir.path()).await.expect("apply runs");
|
||||
let rewritten = std::fs::read_to_string(dir.path().join("a.rs")).unwrap();
|
||||
assert!(rewritten.contains("assist(1, 2)"), "the rewrite landed: {rewritten}");
|
||||
}
|
||||
|
||||
/// The failure that killed a real turn: a structural pattern across a large repo returned
|
||||
/// 232,744 tokens — past the model's context window — because every match carried its whole
|
||||
/// body and nothing capped the total.
|
||||
#[test]
|
||||
fn a_broad_search_is_bounded_instead_of_flooding_context() {
|
||||
let body: String = (1..=40).map(|n| format!(" line {n}\n")).collect();
|
||||
let matches: Vec<AstGrepMatch> = (0..300)
|
||||
.map(|n| AstGrepMatch {
|
||||
file: PathBuf::from(format!("services/service_{n}.py")),
|
||||
range: (0, 10),
|
||||
line: 1,
|
||||
column: 0,
|
||||
text: format!("def handler_{n}():\n{body}"),
|
||||
replacement: None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let rendered = render_matches(&matches, false);
|
||||
let lines = rendered.lines().count();
|
||||
assert!(lines <= MAX_MATCH_LINES + 3, "bounded, got {lines} lines");
|
||||
assert!(rendered.contains("found 300 match(es)"), "the true count still leads");
|
||||
assert!(rendered.contains("more lines not shown"), "and says what it withheld");
|
||||
assert!(rendered.contains("Narrow the pattern"), "with a way to recover the rest");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_match_shows_its_head_not_its_whole_body() {
|
||||
let body: String = (1..=30).map(|n| format!(" line {n}\n")).collect();
|
||||
let one = vec![AstGrepMatch {
|
||||
file: PathBuf::from("a.py"),
|
||||
range: (0, 1),
|
||||
line: 1,
|
||||
column: 0,
|
||||
text: format!("def f():\n{body}"),
|
||||
replacement: None,
|
||||
}];
|
||||
let rendered = render_matches(&one, false);
|
||||
assert!(rendered.contains("def f():"), "the identifying line survives");
|
||||
assert!(rendered.contains("… (25 more lines)"), "the rest is accounted for: {rendered}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_result_is_untouched() {
|
||||
let one = vec![AstGrepMatch {
|
||||
file: PathBuf::from("a.py"),
|
||||
range: (0, 1),
|
||||
line: 3,
|
||||
column: 2,
|
||||
text: "def f(): pass".to_string(),
|
||||
replacement: None,
|
||||
}];
|
||||
let rendered = render_matches(&one, false);
|
||||
assert!(!rendered.contains("not shown"), "nothing to trim: {rendered}");
|
||||
assert!(rendered.contains("a.py:3:2"));
|
||||
}
|
||||
|
||||
/// Upstream's parse error ends in a URL a model cannot open, so a rejected pattern was a dead
|
||||
/// end — observed: two bad patterns, then eight `bash` calls instead.
|
||||
#[test]
|
||||
fn a_rejected_pattern_comes_back_with_the_rules_it_broke() {
|
||||
let upstream = "Error: Cannot parse query as a valid pattern.\n\
|
||||
Help: see https://ast-grep.github.io/guide/pattern-syntax.html";
|
||||
let shown = AstGrepError::CommandFailed(upstream.to_string()).to_string();
|
||||
|
||||
assert!(shown.contains("ONE syntactically valid snippet"), "{shown}");
|
||||
assert!(shown.contains("$$$ARGS"), "names the metavariable forms: {shown}");
|
||||
assert!(shown.contains("use `grep` instead"), "and when to give up: {shown}");
|
||||
}
|
||||
|
||||
/// An environment failure is not a pattern failure; don't lecture about syntax.
|
||||
#[test]
|
||||
fn an_unrelated_failure_gets_no_pattern_lecture() {
|
||||
let shown = AstGrepError::CommandFailed("permission denied".to_string()).to_string();
|
||||
assert_eq!(shown, "command failed: permission denied");
|
||||
}
|
||||
|
||||
/// A tool that cannot work here should not cost a schema; the identity check is the same one
|
||||
/// `resolve_binary` applies, because the shadow-utils `sg` on PATH is not this tool.
|
||||
#[test]
|
||||
fn availability_matches_whether_a_real_ast_grep_resolves() {
|
||||
let available = is_available();
|
||||
let paths = candidate_paths();
|
||||
if paths.is_empty() {
|
||||
assert!(!available, "nothing on PATH means nothing to offer");
|
||||
}
|
||||
// When it reports available it must have cached the binary it verified.
|
||||
if available {
|
||||
assert!(BINARY.get().is_some(), "seeds the cache resolve_binary reads");
|
||||
}
|
||||
}
|
||||
140
crates/luxe-tools/src/astgrep/tests/read_policy.rs
Normal file
140
crates/luxe-tools/src/astgrep/tests/read_policy.rs
Normal file
@@ -0,0 +1,140 @@
|
||||
use super::*;
|
||||
use luxe_core::permission::PermissionAction::Deny;
|
||||
#[cfg(unix)]
|
||||
use luxe_core::permission::{
|
||||
PermissionAction::{Allow, Ask},
|
||||
PermissionEngine, PermissionMode, Rule,
|
||||
};
|
||||
use luxe_core::tool::FileReadHook;
|
||||
|
||||
#[cfg(unix)]
|
||||
fn policy_rule(
|
||||
permission: &str,
|
||||
pattern: &str,
|
||||
action: luxe_core::permission::PermissionAction,
|
||||
) -> Rule {
|
||||
Rule { permission: permission.into(), pattern: pattern.into(), action }
|
||||
}
|
||||
|
||||
fn context(cwd: &std::path::Path) -> ToolContext {
|
||||
let (_, cancelled) = tokio::sync::watch::channel(false);
|
||||
let (event_tx, _) = tokio::sync::mpsc::channel(8);
|
||||
ToolContext {
|
||||
cwd: cwd.into(),
|
||||
session_id: "ast-read-policy".into(),
|
||||
cancelled: std::sync::Arc::new(cancelled),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn fixture() -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("data/nested")).unwrap();
|
||||
for (path, text) in [
|
||||
(".env", "ROOT_PRIVATE"),
|
||||
("nested/.env", "CHILD_PRIVATE"),
|
||||
("nested/.env.example", "PUBLIC_TEMPLATE"),
|
||||
("safe.rs", "SAFE_TEXT"),
|
||||
("review.rs", "REVIEW_TEXT"),
|
||||
] {
|
||||
std::fs::write(dir.path().join("data").join(path), text).unwrap();
|
||||
}
|
||||
fake_binary(
|
||||
dir.path(),
|
||||
"ast-policy-cli",
|
||||
r#"#!/bin/sh
|
||||
for arg in "$@"; do
|
||||
if [ -d "$arg" ]; then find "$arg" -type f
|
||||
elif [ -f "$arg" ]; then printf '%s\n' "$arg"
|
||||
fi
|
||||
done | while IFS= read -r file; do
|
||||
text=$(cat "$file")
|
||||
printf '{"file":"%s","text":"%s","range":{"byteOffset":{"start":0,"end":1},"start":{"line":0,"column":0}}}\n' "$file" "$text"
|
||||
done
|
||||
"#,
|
||||
);
|
||||
BINARY.set(dir.path().join("ast-policy-cli").to_string_lossy().into_owned()).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// A directory matcher must not see denied/Ask content before its output is filtered.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn the_matcher_receives_only_policy_approved_ast_files() {
|
||||
let dir = fixture();
|
||||
let data = dir.path().join("data");
|
||||
let policy = PermissionEngine::assemble(
|
||||
PermissionMode::Default,
|
||||
vec![policy_rule("read", ".env", Allow), policy_rule("read", "review.rs", Ask)],
|
||||
vec![],
|
||||
false,
|
||||
);
|
||||
for action in ["search", "replace"] {
|
||||
let args = serde_json::json!({"action": action, "pattern": "foo($A)", "rewrite": "bar($A)", "lang": "rust", "paths": [data]});
|
||||
let result = AstGrepTool::new().run_with_read_hook(args, &context(&data), &policy).await;
|
||||
assert!(!result.is_error, "{:?}", result.content);
|
||||
let text = result
|
||||
.content
|
||||
.iter()
|
||||
.filter_map(|block| match block {
|
||||
luxe_core::ContentBlock::Text(text) => Some(text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
assert!(
|
||||
text.contains("ROOT_PRIVATE")
|
||||
&& text.contains("PUBLIC_TEMPLATE")
|
||||
&& text.contains("SAFE_TEXT"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(!text.contains("CHILD_PRIVATE") && !text.contains("REVIEW_TEXT"), "{text}");
|
||||
assert!(text.contains("skipped") && text.contains("approval"), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Approved files go to the matcher absolute, but the model reads them project-relative, as an
|
||||
/// unguarded run shows them.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn guarded_matches_are_reported_relative_to_the_working_directory() {
|
||||
let dir = fixture();
|
||||
let data = dir.path().join("data");
|
||||
let args = serde_json::json!({"action": "search", "pattern": "foo($A)", "lang": "rust"});
|
||||
let result = AstGrepTool::new()
|
||||
.run_with_read_hook(args, &context(&data), &PermissionEngine::permissive())
|
||||
.await;
|
||||
let luxe_core::ContentBlock::Text(text) = &result.content[0] else { panic!("{result:?}") };
|
||||
assert!(text.contains("\nsafe.rs:1:0"), "{text}");
|
||||
assert!(!text.contains(&data.display().to_string()), "{text}");
|
||||
}
|
||||
|
||||
struct DenyEveryFile;
|
||||
impl FileReadHook for DenyEveryFile {
|
||||
fn decision(&self, _: &std::path::Path) -> luxe_core::permission::PermissionAction {
|
||||
Deny
|
||||
}
|
||||
}
|
||||
|
||||
/// With no approved files, no matcher invocation may fall back to the current directory.
|
||||
#[tokio::test]
|
||||
async fn a_fully_denied_ast_scope_never_starts_the_matcher() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("safe.rs"), "foo(1)").unwrap();
|
||||
let args = serde_json::json!({"action": "search", "pattern": "foo($A)", "lang": "rust", "paths": [dir.path()]});
|
||||
let result =
|
||||
AstGrepTool::new().run_with_read_hook(args, &context(dir.path()), &DenyEveryFile).await;
|
||||
assert!(!result.is_error, "{:?}", result.content);
|
||||
let luxe_core::ContentBlock::Text(body) = &result.content[0] else { panic!("{result:?}") };
|
||||
assert_eq!(body, "no policy-approved files to search");
|
||||
assert!(
|
||||
result.content.iter().any(
|
||||
|block| matches!(block, luxe_core::ContentBlock::Text(text) if text.contains("skipped"))
|
||||
),
|
||||
"{:?}",
|
||||
result.content
|
||||
);
|
||||
}
|
||||
144
crates/luxe-tools/src/astgrep/tests/session_cwd.rs
Normal file
144
crates/luxe-tools/src/astgrep/tests/session_cwd.rs
Normal file
@@ -0,0 +1,144 @@
|
||||
//! The session's working directory, the preview's files, and what an applied rewrite announces.
|
||||
|
||||
use super::*;
|
||||
use luxe_core::hook::{Hook, HookCtx, HookEvent, HookOutcome, HookPoint, HookRegistry};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
fn context(cwd: &std::path::Path) -> ToolContext {
|
||||
let (_, cancelled) = tokio::sync::watch::channel(false);
|
||||
let (event_tx, _) = tokio::sync::mpsc::channel(8);
|
||||
ToolContext {
|
||||
cwd: cwd.into(),
|
||||
session_id: "ast-cwd".into(),
|
||||
cancelled: Arc::new(cancelled),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A stub that logs each invocation's directory and arguments, then reports one match in `a.rs`.
|
||||
fn stub(dir: &std::path::Path) -> std::path::PathBuf {
|
||||
let log = dir.join("calls.log");
|
||||
fake_binary(
|
||||
dir,
|
||||
"ast-cwd-cli",
|
||||
&format!(
|
||||
"#!/bin/sh\nprintf '%s | %s\\n' \"$PWD\" \"$*\" >> {log}\n\
|
||||
echo '{{\"text\":\"foo(1)\",\"replacement\":\"bar(1)\",\"range\":{{\"byteOffset\":\
|
||||
{{\"start\":0,\"end\":6}},\"start\":{{\"line\":0,\"column\":0}}}},\"file\":\"a.rs\"}}'\n",
|
||||
log = log.display()
|
||||
),
|
||||
);
|
||||
BINARY.set(dir.join("ast-cwd-cli").to_string_lossy().into_owned()).unwrap();
|
||||
log
|
||||
}
|
||||
|
||||
/// A session in a worktree must search that tree, not wherever the process happened to start.
|
||||
#[tokio::test]
|
||||
async fn the_matcher_runs_in_the_sessions_working_directory() {
|
||||
let bin = tempfile::tempdir().unwrap();
|
||||
let log = stub(bin.path());
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let args = serde_json::json!({"action": "search", "pattern": "foo($A)", "lang": "rust"});
|
||||
AstGrepTool::new().run(args, &context(project.path())).await;
|
||||
let calls = std::fs::read_to_string(log).unwrap();
|
||||
let project = std::fs::canonicalize(project.path()).unwrap();
|
||||
assert!(calls.starts_with(&format!("{} |", project.display())), "{calls}");
|
||||
}
|
||||
|
||||
struct Announced(Arc<Mutex<Vec<String>>>);
|
||||
|
||||
#[async_trait]
|
||||
impl Hook for Announced {
|
||||
fn name(&self) -> &'static str {
|
||||
"announced"
|
||||
}
|
||||
fn interest(&self) -> &[HookPoint] {
|
||||
&[HookPoint::FileChanged]
|
||||
}
|
||||
async fn on(&self, _: HookPoint, event: &HookEvent, _: &HookCtx) -> HookOutcome {
|
||||
if let HookEvent::FileChanged { path, .. } = event {
|
||||
self.0.lock().unwrap().push(path.clone());
|
||||
}
|
||||
HookOutcome::InjectContext("diagnostics: clean".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// The write pass rewrites what the preview showed, not a fresh scan of the whole scope, and each
|
||||
/// rewritten file goes through `FileChanged` and the read tracker like an `edit` would.
|
||||
#[tokio::test]
|
||||
async fn an_applied_rewrite_writes_the_previewed_files_and_announces_them() {
|
||||
let bin = tempfile::tempdir().unwrap();
|
||||
let log = stub(bin.path());
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
std::fs::write(project.path().join("a.rs"), "foo(1)").unwrap();
|
||||
let announced = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut registry = HookRegistry::new();
|
||||
registry.register(Arc::new(Announced(announced.clone())));
|
||||
let mut cx = context(project.path());
|
||||
cx.hook_ctx = Some(HookCtx {
|
||||
session_id: cx.session_id.clone(),
|
||||
event_tx: cx.event_tx.clone(),
|
||||
hook_registry: registry,
|
||||
});
|
||||
let tracker = Arc::new(luxe_core::read_tracker::ReadTracker::new());
|
||||
let tool = AstGrepTool::new().with_tracker(tracker.clone());
|
||||
let args = serde_json::json!({"action": "replace", "pattern": "foo($A)", "rewrite": "bar($A)",
|
||||
"lang": "rust", "paths": ["src", "."], "apply": true});
|
||||
let result = tool.run(args, &cx).await;
|
||||
assert!(!result.is_error, "{result:?}");
|
||||
let calls = std::fs::read_to_string(log).unwrap();
|
||||
let update = calls.lines().find(|line| line.contains("--update-all")).expect(&calls);
|
||||
assert!(update.ends_with(" a.rs"), "{update}");
|
||||
assert!(!update.contains(" src") && !update.contains(" ."), "{update}");
|
||||
let file = project.path().join("a.rs");
|
||||
assert_eq!(*announced.lock().unwrap(), [luxe_core::paths::display(&file)]);
|
||||
assert_eq!(tracker.status("ast-cwd", &file), luxe_core::read_tracker::ReadStatus::Current);
|
||||
assert!(format!("{result:?}").contains("diagnostics: clean"), "{result:?}");
|
||||
}
|
||||
|
||||
/// A batch that fails after earlier ones were rewritten must not read as nothing having happened.
|
||||
#[tokio::test]
|
||||
async fn a_failed_batch_reports_the_rewrites_already_on_disk() {
|
||||
let bin = tempfile::tempdir().unwrap();
|
||||
fake_binary(
|
||||
bin.path(),
|
||||
"ast-batch-cli",
|
||||
"#!/bin/sh\ncase \"$*\" in *--update-all*b.rs*) echo 'disk full' >&2; exit 1;; esac\n\
|
||||
case \"$*\" in *--update-all*) exit 0;; esac\n\
|
||||
for f in \"$@\"; do case \"$f\" in *.rs) printf '{\"text\":\"foo(1)\",\"replacement\":\"bar(1)\",\
|
||||
\"range\":{\"byteOffset\":{\"start\":0,\"end\":6},\"start\":{\"line\":0,\"column\":0}},\
|
||||
\"file\":\"%s\"}\\n' \"$f\";; esac; done\n",
|
||||
);
|
||||
BINARY.set(bin.path().join("ast-batch-cli").to_string_lossy().into_owned()).unwrap();
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
for file in ["a.rs", "b.rs"] {
|
||||
std::fs::write(project.path().join(file), "foo(1)").unwrap();
|
||||
}
|
||||
let args = serde_json::json!({"action": "replace", "pattern": "foo($A)", "rewrite": "bar($A)",
|
||||
"lang": "rust", "apply": true});
|
||||
let call = super::super::guarded::Call::parse(args).unwrap();
|
||||
let batches = vec![vec!["a.rs".to_string()], vec!["b.rs".to_string()]];
|
||||
let result = call.over(&AstGrepTool::new(), batches, &context(project.path())).await;
|
||||
let text = format!("{result:?}");
|
||||
assert!(result.is_error, "{text}");
|
||||
assert!(text.contains("rewrote 1 match") && text.contains("a.rs"), "{text}");
|
||||
assert!(text.contains("disk full") && text.contains("on disk"), "{text}");
|
||||
}
|
||||
|
||||
/// A file named like a flag reaches the matcher as a file: a repository cannot turn a search into a
|
||||
/// rewrite with a file called `-U`.
|
||||
#[tokio::test]
|
||||
async fn paths_follow_an_end_of_options_marker() {
|
||||
let bin = tempfile::tempdir().unwrap();
|
||||
let log = stub(bin.path());
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let args = serde_json::json!({"action": "replace", "pattern": "foo($A)", "rewrite": "bar($A)",
|
||||
"lang": "rust", "paths": ["-U"], "apply": true});
|
||||
AstGrepTool::new().run(args, &context(project.path())).await;
|
||||
let calls = std::fs::read_to_string(log).unwrap();
|
||||
let mut lines = calls.lines();
|
||||
assert!(lines.next().unwrap().ends_with(" -- -U"), "{calls}");
|
||||
assert!(lines.next().unwrap().ends_with("--update-all -- a.rs"), "{calls}");
|
||||
}
|
||||
490
crates/luxe-tools/src/bash.rs
Normal file
490
crates/luxe-tools/src/bash.rs
Normal file
@@ -0,0 +1,490 @@
|
||||
//! `bash` tool — execute shell commands with timeout and output truncation.
|
||||
//!
|
||||
//! Supports:
|
||||
//! - Executing shell commands via tokio::process
|
||||
//! - Timeout enforcement (kills child on timeout)
|
||||
//! - Output truncation (keeps head+tail, notes truncation)
|
||||
//! - Exit code reporting
|
||||
//!
|
||||
//! The call ends when the **command** does. A process it deliberately left running is not the
|
||||
//! command, however long it holds the output pipe. Running, capturing and reaping are
|
||||
//! `crate::process`'s, shared with `test`.
|
||||
//!
|
||||
//! A command that printed files — `cat`, `head`, `tail`, `nl`, `sed -n` — counts as reading them
|
||||
//! for the read-before-edit guard; see `seen`.
|
||||
|
||||
pub(crate) mod seen;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use luxe_core::compression::{
|
||||
compress, CommandInvocation, CommandOutput, CompressionConfig, ReducerRegistry, TestReducer,
|
||||
};
|
||||
use luxe_core::{ContentBlock, Tool, ToolContext, ToolResultData, ToolSchema};
|
||||
use serde_json::json;
|
||||
use std::time::Duration;
|
||||
use tracing::{debug, warn};
|
||||
|
||||
/// Default timeout for bash commands (30 seconds).
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 30;
|
||||
|
||||
/// Ceiling on the model-supplied `timeout`, in seconds (one hour).
|
||||
///
|
||||
/// The argument exists because a build or a suite legitimately needs longer than the default, and
|
||||
/// the model is the one who knows which. It is clamped because it is also the one number a model can
|
||||
/// set that removes its own safety net — `timeout: 99999999` is not a considered choice about a
|
||||
/// build, and there is no repo task on the other side of an hour that a fresh call cannot resume.
|
||||
const MAX_TIMEOUT_SECS: u64 = 3_600;
|
||||
|
||||
/// Final safety clamp on the model-facing body, guarding the pathological single huge line the
|
||||
/// line-based compressor cannot shrink (a minified bundle, a one-line JSON response).
|
||||
///
|
||||
/// The compressor handles *volume* beautifully — 200,000 lines of `seq` come back as ~550
|
||||
/// characters — but it works per line, so one 500 KB line passes straight through, and a 1 MB
|
||||
/// ceiling is no guard at any real context window (roughly 250,000 tokens).
|
||||
/// Clamping hard is safe precisely because oversized output is *also* teed to `.luxe/artifacts/`
|
||||
/// with its path in the result: nothing is lost, only deferred. The same ceiling `read` keeps, so
|
||||
/// one long line costs the same whichever tool printed it.
|
||||
const MAX_OUTPUT_BYTES: usize = luxe_core::output_limit::RESULT_MAX_CHARS;
|
||||
|
||||
/// Resolves the compression config, honoring the `LUXE_COMPRESS=0` opt-out.
|
||||
fn compression_config() -> CompressionConfig {
|
||||
let disabled = std::env::var("LUXE_COMPRESS").map(|v| v == "0").unwrap_or(false);
|
||||
CompressionConfig { enabled: !disabled, ..CompressionConfig::default() }
|
||||
}
|
||||
|
||||
/// Command-specific reducers applied to bash output. The structured test reducer turns test-runner
|
||||
/// noise into a pass/fail summary; unmatched commands take the generic pipeline.
|
||||
fn reducer_registry() -> ReducerRegistry {
|
||||
let mut registry = ReducerRegistry::new();
|
||||
registry.register(Box::new(TestReducer));
|
||||
registry
|
||||
}
|
||||
|
||||
/// Head+tail byte clamp — the last-resort guard when compression can't shrink a huge single line.
|
||||
///
|
||||
/// Cut on char boundaries: a byte offset can land inside a multi-byte character, and slicing there
|
||||
/// panicked on any long enough line of non-ASCII output.
|
||||
fn clamp_bytes(text: &str, max: usize) -> String {
|
||||
if text.len() <= max {
|
||||
return text.to_string();
|
||||
}
|
||||
let head = &text[..crate::output_limit::floor_boundary(text, max / 2)];
|
||||
let tail = &text[crate::output_limit::ceil_boundary(text, text.len() - max / 2)..];
|
||||
format!("{head}\n-- clamped {} bytes --\n{tail}", text.len() - head.len() - tail.len())
|
||||
}
|
||||
|
||||
/// JSON-schema for the bash tool arguments.
|
||||
fn bash_schema() -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: "bash".to_string(),
|
||||
description: "Execute a shell command with a timeout, for what the other tools do not \
|
||||
cover: builds, scripts, package managers, running the program.\n\
|
||||
Do not use it for what a tool here does better, because the tool's output \
|
||||
is bounded and structured, the person watching sees what you did, and edits \
|
||||
are checked and formatted:\n\
|
||||
- reading files (cat, head, tail, sed -n): `read`, which takes several \
|
||||
paths in one call\n\
|
||||
- listing and finding files (ls, find): `glob`; searching inside them \
|
||||
(grep, rg): `grep`\n\
|
||||
- changing files (heredocs, sed -i, echo >): `edit` and `write`\n\
|
||||
- git and GitHub (git, gh): `git`, including issues and pull requests\n\
|
||||
- running the tests: `test`\n\
|
||||
Calls in one reply run in a single round trip, so several tool calls cost no \
|
||||
more than one shell line doing the same.\n\
|
||||
Each call gets a fresh shell already rooted at the project directory, so \
|
||||
there is nothing to `cd` into first and a `cd` does not carry to the next \
|
||||
call. Noisy output is deterministically compressed before it reaches you — \
|
||||
ANSI/progress/duplicate lines are stripped and long logs are truncated while \
|
||||
errors, warnings, failing tests, and file:line locations are always kept. \
|
||||
When output is reduced, the untouched output is saved to .luxe/artifacts/ \
|
||||
(each stream whole up to 8 MB, or its first and last 4 MB past that) and its path is \
|
||||
included, so you can read it if you need the detail."
|
||||
.to_string(),
|
||||
parameters: json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
// First, so the model writes it before the command and the card is named by it
|
||||
// from the start rather than renamed when the call lands
|
||||
"description": {
|
||||
"type": "string",
|
||||
"description": "What the command does, in 5–10 plain words, for the person \
|
||||
watching: \"Run the forms tests\", not the command's own text. \
|
||||
Their card shows this in place of the command."
|
||||
},
|
||||
"command": {
|
||||
"type": "string",
|
||||
"description": "Shell command to execute, from the project directory"
|
||||
},
|
||||
"timeout": {
|
||||
"type": "integer",
|
||||
"description": "Timeout in seconds (optional, defaults to 30)"
|
||||
}
|
||||
},
|
||||
"required": ["command"]
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `bash` tool implementation.
|
||||
pub struct BashTool {
|
||||
/// Shared read tracker; a file a command printed is recorded as read
|
||||
tracker: Option<std::sync::Arc<luxe_core::read_tracker::ReadTracker>>,
|
||||
}
|
||||
|
||||
impl BashTool {
|
||||
/// Create a new bash tool instance.
|
||||
pub fn new() -> Self {
|
||||
Self { tracker: None }
|
||||
}
|
||||
|
||||
/// Attach the shared read tracker, so a `cat` of a file satisfies the edit guards.
|
||||
pub fn with_tracker(
|
||||
mut self,
|
||||
tracker: std::sync::Arc<luxe_core::read_tracker::ReadTracker>,
|
||||
) -> Self {
|
||||
self.tracker = Some(tracker);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for BashTool {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Most surviving processes a timeout names before the rest become a count.
|
||||
const MAX_SURVIVORS_LISTED: usize = 10;
|
||||
|
||||
/// Longest command line a timeout shows for one surviving process.
|
||||
const SURVIVOR_COMMAND_CHARS: usize = 120;
|
||||
|
||||
/// What follows a timeout's output: the processes still running, and what to do next.
|
||||
///
|
||||
/// A suspended process changes the advice: it was never going to finish, so a longer `timeout`
|
||||
/// would only wait longer. Commands start without a terminal, so a spinner or a prompt cannot cause
|
||||
/// it; a `SIGSTOP` or a debugger still can.
|
||||
fn timeout_advice(survivors: &[luxe_core::program::GroupMember]) -> String {
|
||||
let mut out = String::new();
|
||||
if !survivors.is_empty() {
|
||||
out.push_str("\n\nStill running when it was stopped (pid, state, command):");
|
||||
for member in survivors.iter().take(MAX_SURVIVORS_LISTED) {
|
||||
let command: String = member.command.chars().take(SURVIVOR_COMMAND_CHARS).collect();
|
||||
let cut =
|
||||
if member.command.chars().count() > SURVIVOR_COMMAND_CHARS { "…" } else { "" };
|
||||
out.push_str(&format!("\n {} {} {command}{cut}", member.pid, member.state));
|
||||
}
|
||||
if survivors.len() > MAX_SURVIVORS_LISTED {
|
||||
out.push_str(&format!("\n … +{} more", survivors.len() - MAX_SURVIVORS_LISTED));
|
||||
}
|
||||
}
|
||||
if survivors.iter().any(luxe_core::program::GroupMember::is_stopped) {
|
||||
out.push_str(
|
||||
"\n\nState T means suspended, not slow: something stopped it (a `SIGSTOP`, a job-control \
|
||||
signal, a debugger) and it will not continue on its own. More time will not help; find \
|
||||
what stops it, or ask the user to run it in their own terminal.",
|
||||
);
|
||||
} else {
|
||||
out.push_str(&format!(
|
||||
"\n\nFor a command that needs longer, pass `timeout` (up to {MAX_TIMEOUT_SECS} \
|
||||
seconds); to leave one running, start it in the background with `&` and its output \
|
||||
redirected to a file."
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for BashTool {
|
||||
/// No engine-side deadline: this tool spawns its command as its own **process group** and kills
|
||||
/// the whole tree itself, which the engine cannot do (dropping the future reaps the direct
|
||||
/// child and orphans everything it started). It owns the bound because it owns the kill — the
|
||||
/// `timeout` argument, defaulted and clamped in [`Self::run`], and `crate::process`'s tree
|
||||
/// guard for every other way the call can end.
|
||||
fn timeout(&self) -> Option<Duration> {
|
||||
None
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
"bash"
|
||||
}
|
||||
|
||||
fn schema(&self) -> ToolSchema {
|
||||
bash_schema()
|
||||
}
|
||||
|
||||
async fn run(&self, args: serde_json::Value, cx: &ToolContext) -> ToolResultData {
|
||||
let Some(command) = args.get("command").and_then(|v| v.as_str()) else {
|
||||
return ToolResultData::error("Error: 'command' argument is required");
|
||||
};
|
||||
let timeout_secs = timeout_secs(&args);
|
||||
debug!(command, timeout = timeout_secs, "executing bash command");
|
||||
let timeout = Duration::from_secs(timeout_secs);
|
||||
match crate::process::run_captured(command, &cx.cwd, timeout).await {
|
||||
Ok(crate::process::Outcome::Finished(output)) => self.finish(command, cx, output),
|
||||
Ok(crate::process::Outcome::TimedOut(stopped)) => {
|
||||
warn!(command, timeout = timeout_secs, "command timed out");
|
||||
timed_out(timeout_secs, &stopped)
|
||||
}
|
||||
Err(error) => {
|
||||
warn!(command, %error, "failed to run command");
|
||||
ToolResultData::error(format!("Error running command: {error}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The model's `timeout`, defaulted and clamped.
|
||||
///
|
||||
/// A negative or absent value takes the default; anything past the ceiling is clamped rather than
|
||||
/// refused, since the intent ("this one is slow") is still worth honoring.
|
||||
fn timeout_secs(args: &serde_json::Value) -> u64 {
|
||||
args.get("timeout")
|
||||
.and_then(|v| v.as_i64())
|
||||
.and_then(|secs| u64::try_from(secs).ok())
|
||||
.filter(|secs| *secs > 0)
|
||||
.unwrap_or(DEFAULT_TIMEOUT_SECS)
|
||||
.min(MAX_TIMEOUT_SECS)
|
||||
}
|
||||
|
||||
/// A timeout's reply: what the command had printed, which is the evidence of where it got to, and
|
||||
/// the way out. A bare "timed out" left the agent to guess both, and usually to run it again.
|
||||
fn timed_out(timeout_secs: u64, stopped: &crate::process::TimedOut) -> ToolResultData {
|
||||
let printed = match stopped.printed.is_empty() {
|
||||
true => "It printed nothing before it was stopped.".to_string(),
|
||||
false => format!("Output before it was stopped:\n{}", stopped.printed),
|
||||
};
|
||||
ToolResultData::error(format!(
|
||||
"Command timed out after {timeout_secs} seconds and was stopped. {printed}{}",
|
||||
timeout_advice(&stopped.survivors)
|
||||
))
|
||||
}
|
||||
|
||||
impl BashTool {
|
||||
/// The reply for a command that ran to its end.
|
||||
fn finish(
|
||||
&self,
|
||||
command: &str,
|
||||
cx: &ToolContext,
|
||||
output: crate::process::Captured,
|
||||
) -> ToolResultData {
|
||||
let crate::process::Captured { stdout, stderr, status, detached_writer } = output;
|
||||
// A failed command may have printed half of what it was asked to, so only a clean exit counts
|
||||
if let Some(tracker) = self.tracker.as_ref().filter(|_| status.success()) {
|
||||
for path in seen::files_shown(command, &cx.cwd, &stdout) {
|
||||
tracker.record(&cx.session_id, &path);
|
||||
}
|
||||
}
|
||||
let exit = status.code();
|
||||
if detached_writer {
|
||||
debug!(command, "a process outlived the shell still holding its pipe");
|
||||
}
|
||||
let mut body = compressed_body(command, cx, (&stdout, &stderr, exit));
|
||||
if detached_writer {
|
||||
body.push_str(crate::process::DETACHED_WRITER_NOTE);
|
||||
}
|
||||
// A failure on a Windows box with no POSIX shell is usually about the *shell*, not the
|
||||
// command. Said once, on failure only, so `cargo test` through `cmd` stays quiet.
|
||||
if !crate::process::posix_shell() && !status.success() {
|
||||
body.push_str(NO_POSIX_SHELL_NOTE);
|
||||
}
|
||||
// `grep` and `rg` exit 1 for "nothing matched", which is an answer rather than a failure,
|
||||
// when the search ends the command and said nothing at all
|
||||
let no_match = exit == Some(1)
|
||||
&& stdout.trim().is_empty()
|
||||
&& stderr.trim().is_empty()
|
||||
&& ends_in_search(command);
|
||||
let exit_note = if no_match {
|
||||
" — the search matched nothing, which is what exit code 1 means for it"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
ToolResultData {
|
||||
content: vec![ContentBlock::Text(format!(
|
||||
"{body}\n\nExit code: {}{exit_note}",
|
||||
exit.unwrap_or(-1)
|
||||
))],
|
||||
is_error: !status.success() && !no_match,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The output as the model reads it: compressed, led by a test run's regressions, pointed at the
|
||||
/// untouched copy whenever anything was dropped, and clamped last.
|
||||
fn compressed_body(
|
||||
command: &str,
|
||||
cx: &ToolContext,
|
||||
(stdout, stderr, exit): (&str, &str, Option<i32>),
|
||||
) -> String {
|
||||
// Noisy output keeps its signal — errors, warnings, failing tests, file:line, exit codes — and
|
||||
// the test reducer turns `cargo test`/`pytest` output into a pass/fail summary.
|
||||
let invocation = CommandInvocation::parse(command);
|
||||
let captured =
|
||||
CommandOutput { stdout: stdout.to_owned(), stderr: stderr.to_owned(), exit_code: exit };
|
||||
let result = compress(&invocation, &captured, &compression_config(), &reducer_registry());
|
||||
let mut body =
|
||||
if result.output.is_empty() { "(no output)".to_string() } else { result.output.clone() };
|
||||
if let Some(note) = test_delta(command, cx, &invocation, stdout, stderr) {
|
||||
body = format!("{note}{body}");
|
||||
}
|
||||
// A body too long to send whole is a reduction too, so its untouched output is saved the same
|
||||
// way, or the clamp below would drop text with no path back to it
|
||||
if result.was_reduced() || body.len() > MAX_OUTPUT_BYTES {
|
||||
// The schema promises the untouched output is recoverable whenever this reduces, so a tee
|
||||
// that could not write has to say so rather than leave the reader looking for a path
|
||||
match crate::process::tee_artifact(&cx.cwd, "cmd", command, (stdout, stderr, exit)) {
|
||||
Some(path) => {
|
||||
body.push_str(&format!("\n\nFull output: {}", luxe_core::paths::display(&path)))
|
||||
}
|
||||
None => body.push_str(
|
||||
"\n\nThe full output could not be saved to .luxe/artifacts/ — re-run with a \
|
||||
narrower command if you need the part that was dropped.",
|
||||
),
|
||||
}
|
||||
if let Some(footer) = result.footer().filter(|_| result.was_reduced()) {
|
||||
body.push('\n');
|
||||
body.push_str(&footer);
|
||||
}
|
||||
}
|
||||
clamp_bytes(&body, MAX_OUTPUT_BYTES)
|
||||
}
|
||||
|
||||
/// A suite run through the shell gets the `test` tool's "what broke since last time" too. Keyed by
|
||||
/// the whole command, so each subset a model runs is compared only with itself.
|
||||
fn test_delta(
|
||||
command: &str,
|
||||
cx: &ToolContext,
|
||||
invocation: &CommandInvocation,
|
||||
stdout: &str,
|
||||
stderr: &str,
|
||||
) -> Option<String> {
|
||||
if !luxe_core::compression::is_test_command(invocation) {
|
||||
return None;
|
||||
}
|
||||
let summary = luxe_core::compression::parse_test_output(stdout, stderr)?;
|
||||
let failing = summary.failures.iter().map(|f| f.name.clone()).collect();
|
||||
crate::test_baseline::diff_and_record(
|
||||
&cx.cwd,
|
||||
command,
|
||||
&failing,
|
||||
summary.passed,
|
||||
summary.failed,
|
||||
false,
|
||||
)
|
||||
.render()
|
||||
}
|
||||
|
||||
/// `cmd`'s complaint about a pipe or a quote reads like the command was wrong.
|
||||
const NO_POSIX_SHELL_NOTE: &str = "\n\nNote: no POSIX shell was found, so this ran through \
|
||||
cmd.exe, which does not understand `|`, `&&`, single quotes, `$VAR` or unix tool names. \
|
||||
Install Git for Windows (its `bash` is picked up automatically) to run commands as written.";
|
||||
|
||||
/// Whether the last command `command` runs is a search whose exit 1 means "no match".
|
||||
///
|
||||
/// The last one, because that is whose status the shell reports: `npm test | grep x` exits as
|
||||
/// `grep` did. Quotes are respected — a pattern like `"^ok|^not ok"` is full of pipes — and anything
|
||||
/// unclear after the search, like a redirection's `2>&1`, makes this false, which keeps the call
|
||||
/// reported exactly as it was.
|
||||
fn ends_in_search(command: &str) -> bool {
|
||||
let bytes = command.as_bytes();
|
||||
let (mut single, mut double, mut start) = (false, false, 0);
|
||||
let mut index = 0;
|
||||
while index < bytes.len() {
|
||||
match bytes[index] {
|
||||
b'\'' if !double => single = !single,
|
||||
b'"' if !single => double = !double,
|
||||
b'\\' if !single => index += 1,
|
||||
b'|' | b';' | b'&' | b'\n' if !single && !double => start = index + 1,
|
||||
_ => {}
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
let Some(words) = shlex::split(&command[start..]) else { return false };
|
||||
let program = words
|
||||
.iter()
|
||||
.find(|word| !word.contains('='))
|
||||
.map(|word| word.rsplit('/').next().unwrap_or(word));
|
||||
matches!(program, Some("grep" | "egrep" | "fgrep" | "rg"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// A cancelled command has to stop, and so does everything it started.
|
||||
///
|
||||
/// The engine cancels a tool by dropping its future, and `kill_on_drop` reaps only the shell — so
|
||||
/// this is the one property no amount of testing the timeout path establishes. Both endings are
|
||||
/// here, because they are the same obligation reached two different ways.
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tree_teardown {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
fn context(cwd: &std::path::Path) -> ToolContext {
|
||||
let (event_tx, _event_rx) = mpsc::channel(64);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
ToolContext {
|
||||
cwd: cwd.to_path_buf(),
|
||||
session_id: "tree-teardown".to_string(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A shell that backgrounds a grandchild and waits on it. Killing the shell alone leaves the
|
||||
/// grandchild touching `marker` — which is how a survivor makes itself known.
|
||||
fn script(marker: &std::path::Path) -> String {
|
||||
format!("(for _ in $(seq 1 40); do touch {}; sleep 0.25; done) & wait", marker.display())
|
||||
}
|
||||
|
||||
/// Whether anything is still touching `marker` after it is removed.
|
||||
async fn survivor_still_running(marker: &std::path::Path) -> bool {
|
||||
let _ = std::fs::remove_file(marker);
|
||||
tokio::time::sleep(Duration::from_millis(1_200)).await;
|
||||
marker.exists()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_dropped_call_takes_the_whole_tree_with_it() {
|
||||
if !cfg!(unix) {
|
||||
return; // the script is a POSIX one
|
||||
}
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let marker = dir.path().join("alive");
|
||||
let cx = context(dir.path());
|
||||
{
|
||||
let tool = BashTool::new();
|
||||
let run = tool.run(serde_json::json!({"command": script(&marker)}), &cx);
|
||||
tokio::pin!(run);
|
||||
// Poll far enough to spawn the tree, then drop it — exactly what a cancel does.
|
||||
let _ = tokio::time::timeout(Duration::from_millis(900), &mut run).await;
|
||||
}
|
||||
assert!(
|
||||
!survivor_still_running(&marker).await,
|
||||
"a cancelled command left its grandchild running"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_timed_out_call_takes_the_whole_tree_with_it() {
|
||||
if !cfg!(unix) {
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let marker = dir.path().join("alive");
|
||||
let cx = context(dir.path());
|
||||
let result = BashTool::new()
|
||||
.run(serde_json::json!({"command": script(&marker), "timeout": 1}), &cx)
|
||||
.await;
|
||||
assert!(result.is_error, "a command that outlives its timeout is an error");
|
||||
assert!(
|
||||
!survivor_still_running(&marker).await,
|
||||
"a timed-out command left its grandchild running"
|
||||
);
|
||||
}
|
||||
}
|
||||
356
crates/luxe-tools/src/bash/seen.rs
Normal file
356
crates/luxe-tools/src/bash/seen.rs
Normal file
@@ -0,0 +1,356 @@
|
||||
//! seen — the files a shell command printed for the model, so a `cat` counts as a read.
|
||||
//!
|
||||
//! The read-before-edit guard asks "have you looked at this file?", and a model that looked with
|
||||
//! `cat` has. Counting only `read` would turn the commonest opening move — `cat` the files, then
|
||||
//! edit them — into a refused edit per file and a second round of reads, which is all friction and
|
||||
//! no protection: a one-line `read` already satisfies the guard, and what actually stops a blind
|
||||
//! edit is `edit`'s exact-match rule (see [`luxe_core::read_tracker`]).
|
||||
//!
|
||||
//! So a command that printed files counts, read narrowly. A segment counts only when its output
|
||||
//! reaches the model as printed: not redirected, not backgrounded, and piped only into `head` or
|
||||
//! `tail` — `cat f | head -60` shows the model what `head -60 f` does, which is a slice of the file
|
||||
//! like a `read` with a `limit`. Only the plain printers count — `cat`, `head`, `tail`, `nl`, and
|
||||
//! `sed -n` (never `sed -i`) — with their file arguments resolved against the project and simple
|
||||
//! globs expanded. Anything this cannot read with confidence counts for nothing, which leaves the
|
||||
//! guard as strict as `read` alone.
|
||||
//!
|
||||
//! A search counts too, for the files whose lines it printed: `grep -n -A8 'def x' f.py` shows the
|
||||
//! model a slice of `f.py` as surely as `sed -n` does, and grepping for the spot and then editing it
|
||||
//! is how models work. Refusing that edit costs a round trip and a `read` of text the model had
|
||||
//! just seen. A search that prints no lines — `-l`, `-c`, `-q`, `-o` — counts for nothing, and one
|
||||
//! over many files counts the files its output names, since that output is what the model read.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The programs whose output is the file itself, or a slice of it.
|
||||
const PRINTERS: &[&str] = &["cat", "head", "tail", "nl", "sed"];
|
||||
|
||||
/// Flags of `head`/`tail` that take a value as the next word.
|
||||
const VALUE_FLAGS: &[&str] = &["-n", "-c", "--lines", "--bytes"];
|
||||
|
||||
/// The programs whose output is lines of the files they search.
|
||||
const SEARCHERS: &[&str] = &["grep", "egrep", "fgrep", "rg"];
|
||||
|
||||
/// Short flags of a searcher that take a value, as the next word or attached (`-A8`).
|
||||
const SEARCH_VALUE_SHORT: &str = "ABCefmdDgtTMj";
|
||||
|
||||
/// Long flags of a searcher that take a value as the next word when not given one with `=`.
|
||||
const SEARCH_VALUE_LONG: &[&str] = &[
|
||||
"--regexp",
|
||||
"--file",
|
||||
"--after-context",
|
||||
"--before-context",
|
||||
"--context",
|
||||
"--max-count",
|
||||
"--include",
|
||||
"--exclude",
|
||||
"--exclude-dir",
|
||||
"--glob",
|
||||
"--type",
|
||||
"--type-not",
|
||||
"--max-columns",
|
||||
"--threads",
|
||||
];
|
||||
|
||||
/// Searcher flags under which nothing printed is a line of a file.
|
||||
const SEARCH_NO_LINES_SHORT: &str = "lLcqo";
|
||||
const SEARCH_NO_LINES_LONG: &[&str] = &[
|
||||
"--files-with-matches",
|
||||
"--files-without-match",
|
||||
"--count",
|
||||
"--count-matches",
|
||||
"--quiet",
|
||||
"--silent",
|
||||
"--only-matching",
|
||||
"--files",
|
||||
];
|
||||
|
||||
/// The existing files `command` printed, resolved against `cwd`.
|
||||
///
|
||||
/// `stdout` is what the command printed, which names the files a search over many of them showed.
|
||||
pub(crate) fn files_shown(command: &str, cwd: &Path, stdout: &str) -> Vec<PathBuf> {
|
||||
let mut shown = Vec::new();
|
||||
let add = |path: PathBuf, shown: &mut Vec<PathBuf>| {
|
||||
if path.is_file() && !shown.contains(&path) {
|
||||
shown.push(path);
|
||||
}
|
||||
};
|
||||
let mut searched_many = false;
|
||||
for stages in segments(command) {
|
||||
let Some((first, slices)) = stages.split_first() else { continue };
|
||||
let Some(words) = shlex::split(first) else { continue };
|
||||
let sliced =
|
||||
slices.iter().all(|stage| shlex::split(stage).is_some_and(|words| slice(&words)));
|
||||
if !sliced {
|
||||
continue;
|
||||
}
|
||||
if let Some(paths) = search_paths(&words) {
|
||||
let paths: Vec<PathBuf> = paths.iter().flat_map(|word| expand(word, cwd)).collect();
|
||||
match paths.as_slice() {
|
||||
// One file prints its lines bare, with no name in front to find
|
||||
[file] if file.is_file() && !stdout.trim().is_empty() => {
|
||||
add(file.clone(), &mut shown);
|
||||
}
|
||||
_ => searched_many = true,
|
||||
}
|
||||
continue;
|
||||
}
|
||||
for word in arguments(&words) {
|
||||
for path in expand(&word, cwd) {
|
||||
add(path, &mut shown);
|
||||
}
|
||||
}
|
||||
}
|
||||
if searched_many {
|
||||
for path in files_in_rows(stdout, cwd) {
|
||||
add(path, &mut shown);
|
||||
}
|
||||
}
|
||||
shown
|
||||
}
|
||||
|
||||
/// The files named at the head of search-result rows, `path:12:text` or `path-12-text`.
|
||||
///
|
||||
/// Only names that are files under `cwd` count, so a compiler's `src/a.rs:3:1: error` in the same
|
||||
/// output is the only kind of row that could be mistaken for one, and a search was asked for.
|
||||
pub(crate) fn files_in_rows(output: &str, cwd: &Path) -> Vec<PathBuf> {
|
||||
let mut found: Vec<PathBuf> = Vec::new();
|
||||
let mut misses: Vec<&str> = Vec::new();
|
||||
for row in output.lines().take(5_000) {
|
||||
let bytes = row.as_bytes();
|
||||
for (at, byte) in bytes.iter().enumerate() {
|
||||
if !matches!(byte, b':' | b'-') || at == 0 {
|
||||
continue;
|
||||
}
|
||||
let digits = bytes[at + 1..].iter().take_while(|b| b.is_ascii_digit()).count();
|
||||
let closes = bytes.get(at + 1 + digits).is_some_and(|b| *b == b':' || *b == b'-');
|
||||
if digits == 0 || !closes {
|
||||
continue;
|
||||
}
|
||||
let name = &row[..at];
|
||||
if misses.contains(&name) {
|
||||
continue;
|
||||
}
|
||||
let path = cwd.join(name);
|
||||
if path.is_file() {
|
||||
if !found.contains(&path) {
|
||||
found.push(path);
|
||||
}
|
||||
break;
|
||||
}
|
||||
misses.push(name);
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// A searcher's path arguments, or `None` when `words` is not a search whose output is lines.
|
||||
///
|
||||
/// A search given no path reads standard input or the working directory, which comes back as
|
||||
/// `Some` of nothing, so its rows are what name the files.
|
||||
fn search_paths(words: &[String]) -> Option<Vec<String>> {
|
||||
let program = words.first()?;
|
||||
let program = program.rsplit('/').next().unwrap_or(program);
|
||||
if !SEARCHERS.contains(&program) {
|
||||
return None;
|
||||
}
|
||||
let mut positional = Vec::new();
|
||||
let mut pattern_given = false;
|
||||
let mut words = words[1..].iter();
|
||||
let mut flags_done = false;
|
||||
while let Some(word) = words.next() {
|
||||
if flags_done || !word.starts_with('-') || word == "-" {
|
||||
positional.push(word.clone());
|
||||
} else if word == "--" {
|
||||
flags_done = true;
|
||||
} else if let Some(long) = word.strip_prefix("--") {
|
||||
let name = format!("--{}", long.split('=').next().unwrap_or(long));
|
||||
if SEARCH_NO_LINES_LONG.contains(&name.as_str()) {
|
||||
return None;
|
||||
}
|
||||
if name == "--regexp" || name == "--file" {
|
||||
pattern_given = true;
|
||||
}
|
||||
if SEARCH_VALUE_LONG.contains(&name.as_str()) && !long.contains('=') {
|
||||
words.next();
|
||||
}
|
||||
} else {
|
||||
for (at, flag) in word.char_indices().skip(1) {
|
||||
if SEARCH_NO_LINES_SHORT.contains(flag) {
|
||||
return None;
|
||||
}
|
||||
if SEARCH_VALUE_SHORT.contains(flag) {
|
||||
if flag == 'e' || flag == 'f' {
|
||||
pattern_given = true;
|
||||
}
|
||||
if at + 1 == word.len() {
|
||||
words.next();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !pattern_given && !positional.is_empty() {
|
||||
positional.remove(0);
|
||||
}
|
||||
Some(positional.into_iter().filter(|word| word != "-").collect())
|
||||
}
|
||||
|
||||
/// The segments of a command list whose output reaches the model, each as its pipeline's stages.
|
||||
///
|
||||
/// Split on `;`, newlines, `&&` and `||` outside quotes, and each segment on `|`. A segment with a
|
||||
/// redirection, a lone `&`, a substitution or a heredoc is dropped whole rather than parsed further.
|
||||
fn segments(command: &str) -> Vec<Vec<&str>> {
|
||||
let mut out = Vec::new();
|
||||
let mut stages = Vec::new();
|
||||
let (mut start, mut clean) = (0, true);
|
||||
let (mut single, mut double) = (false, false);
|
||||
let bytes = command.as_bytes();
|
||||
let mut index = 0;
|
||||
fn close<'a>(
|
||||
out: &mut Vec<Vec<&'a str>>,
|
||||
mut stages: Vec<&'a str>,
|
||||
last: &'a str,
|
||||
clean: bool,
|
||||
) {
|
||||
stages.push(last.trim());
|
||||
if clean && stages.iter().all(|stage| !stage.is_empty()) {
|
||||
out.push(stages);
|
||||
}
|
||||
}
|
||||
while index < bytes.len() {
|
||||
let byte = bytes[index];
|
||||
match byte {
|
||||
b'\'' if !double => single = !single,
|
||||
b'"' if !single => double = !double,
|
||||
b'\\' if !single => index += 1,
|
||||
b'`' | b'$' if !single => {
|
||||
// `$(…)` and backticks run something else; `$VAR` and `${VAR}` are just words
|
||||
if byte == b'`' || bytes.get(index + 1) == Some(&b'(') {
|
||||
clean = false;
|
||||
}
|
||||
}
|
||||
_ if single || double => {}
|
||||
b';' | b'\n' => {
|
||||
close(&mut out, std::mem::take(&mut stages), &command[start..index], clean);
|
||||
(start, clean) = (index + 1, true);
|
||||
}
|
||||
b'&' | b'|' if bytes.get(index + 1) == Some(&byte) => {
|
||||
close(&mut out, std::mem::take(&mut stages), &command[start..index], clean);
|
||||
index += 1;
|
||||
(start, clean) = (index + 1, true);
|
||||
}
|
||||
b'|' => {
|
||||
stages.push(command[start..index].trim());
|
||||
start = index + 1;
|
||||
}
|
||||
// `2>` sends only stderr away, so what the model sees is untouched; `2>&1` folds stderr
|
||||
// into it, which hides nothing either. Any other redirection may hide the output.
|
||||
b'>' if stderr_redirect(bytes, index) => {
|
||||
if bytes.get(index + 1) == Some(&b'&') {
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
b'&' | b'>' | b'<' => clean = false,
|
||||
_ => {}
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
close(&mut out, stages, &command[start..], clean && !single && !double);
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the `>` at `at` is a `2>` standing on its own, not the tail of a longer number.
|
||||
fn stderr_redirect(bytes: &[u8], at: usize) -> bool {
|
||||
at >= 1 && bytes[at - 1] == b'2' && (at == 1 || bytes[at - 2].is_ascii_whitespace())
|
||||
}
|
||||
|
||||
/// Whether a pipeline stage only cuts its input down: `head` or `tail` with flags and no files.
|
||||
fn slice(words: &[String]) -> bool {
|
||||
let Some(program) = words.first() else { return false };
|
||||
if !matches!(program.as_str(), "head" | "tail") {
|
||||
return false;
|
||||
}
|
||||
let follows = words.iter().any(|word| word == "-f" || word == "-F" || word == "--follow");
|
||||
!follows && arguments(words).is_empty()
|
||||
}
|
||||
|
||||
/// The file arguments of one printer invocation, or none for anything else.
|
||||
fn arguments(words: &[String]) -> Vec<String> {
|
||||
let Some(program) = words.first() else { return Vec::new() };
|
||||
let program = program.rsplit('/').next().unwrap_or(program);
|
||||
if !PRINTERS.contains(&program) {
|
||||
return Vec::new();
|
||||
}
|
||||
let rest = &words[1..];
|
||||
if program == "sed" {
|
||||
return sed_files(rest);
|
||||
}
|
||||
// `tail -f` never finishes, and one that did would print what arrived, not the file
|
||||
if program == "tail"
|
||||
&& rest.iter().any(|word| word == "-f" || word == "-F" || word == "--follow")
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
let mut words = rest.iter();
|
||||
let mut flags_done = false;
|
||||
while let Some(word) = words.next() {
|
||||
if word == "-" {
|
||||
// standard input, not a file called `-`, even past `--`
|
||||
} else if !flags_done && word == "--" {
|
||||
flags_done = true;
|
||||
} else if !flags_done && VALUE_FLAGS.contains(&word.as_str()) {
|
||||
words.next();
|
||||
} else if !flags_done && word.starts_with('-') {
|
||||
// a bundled flag such as `-40` or `-n40` carries its own value
|
||||
} else {
|
||||
files.push(word.clone());
|
||||
}
|
||||
}
|
||||
files
|
||||
}
|
||||
|
||||
/// `sed -n 'script' file…`: the files after the script, and only for a `-n` that edits nothing.
|
||||
fn sed_files(words: &[String]) -> Vec<String> {
|
||||
let flags: Vec<&String> = words.iter().take_while(|word| word.starts_with('-')).collect();
|
||||
let quiet = flags.iter().any(|flag| *flag == "-n" || *flag == "--quiet" || *flag == "--silent");
|
||||
let in_place =
|
||||
flags.iter().any(|flag| flag.starts_with("-i") || flag.starts_with("--in-place"));
|
||||
let scripted = flags.iter().any(|flag| *flag == "-e" || *flag == "-f");
|
||||
if !quiet || in_place || scripted {
|
||||
return Vec::new();
|
||||
}
|
||||
words.iter().skip(flags.len() + 1).cloned().collect()
|
||||
}
|
||||
|
||||
/// `word` as paths under `cwd`: itself, or what a glob in its last component matches.
|
||||
fn expand(word: &str, cwd: &Path) -> Vec<PathBuf> {
|
||||
let path = cwd.join(word);
|
||||
if !word.contains(['*', '?', '[']) {
|
||||
return vec![path];
|
||||
}
|
||||
let (Some(parent), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str()))
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
// A glob in a folder name is more than this needs to understand
|
||||
if parent.to_string_lossy().contains(['*', '?', '[']) {
|
||||
return Vec::new();
|
||||
}
|
||||
let Ok(matcher) = globset::Glob::new(name).map(|glob| glob.compile_matcher()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Ok(entries) = std::fs::read_dir(parent) else { return Vec::new() };
|
||||
let mut matched: Vec<PathBuf> = entries
|
||||
.flatten()
|
||||
.map(|entry| entry.path())
|
||||
.filter(|path| path.file_name().is_some_and(|name| matcher.is_match(name)))
|
||||
.collect();
|
||||
matched.sort();
|
||||
matched
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
192
crates/luxe-tools/src/bash/seen/tests.rs
Normal file
192
crates/luxe-tools/src/bash/seen/tests.rs
Normal file
@@ -0,0 +1,192 @@
|
||||
use super::*;
|
||||
|
||||
/// A project holding the names a careless parse would count: files named like flags, like
|
||||
/// standard input, and with shell operators in them. Each exists, so a wrong answer has
|
||||
/// something to land on rather than being filtered out as missing.
|
||||
fn project(extra: &[&str]) -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
let base =
|
||||
["src/cli.js", "src/filter.js", "test/filter.test.js", "a.txt", "b.txt", "-n", "-40"];
|
||||
for path in base.iter().chain(extra) {
|
||||
let path = dir.path().join(path);
|
||||
std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
|
||||
std::fs::write(path, "x\n").expect("write");
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
fn shown(command: &str, dir: &Path) -> Vec<String> {
|
||||
// Joined by component rather than by replacing `\`, which is a legal character in a name
|
||||
let relative = |path: &PathBuf| {
|
||||
let inside = path.strip_prefix(dir).expect("inside");
|
||||
let parts: Vec<_> = inside.iter().map(|part| part.to_string_lossy()).collect();
|
||||
parts.join("/")
|
||||
};
|
||||
files_shown(command, dir, "x\n").iter().map(relative).collect()
|
||||
}
|
||||
|
||||
/// The opening move this exists for: look at a few files, then edit them.
|
||||
#[test]
|
||||
fn a_cat_of_files_and_globs_counts() {
|
||||
let dir = project(&[]);
|
||||
assert_eq!(
|
||||
shown("cat src/*.js; ls test; head -40 test/*filter*", dir.path()),
|
||||
["src/cli.js", "src/filter.js", "test/filter.test.js"]
|
||||
);
|
||||
assert_eq!(shown("cat a.txt && tail -n 5 src/cli.js", dir.path()), ["a.txt", "src/cli.js"]);
|
||||
assert_eq!(shown("cat a.txt || cat b.txt", dir.path()), ["a.txt", "b.txt"]);
|
||||
assert_eq!(shown("cat a.txt\nnl -ba b.txt", dir.path()), ["a.txt", "b.txt"]);
|
||||
assert_eq!(shown("/bin/cat 'src/cli.js'", dir.path()), ["src/cli.js"]);
|
||||
assert_eq!(shown("cat a.txt ${UNSET}", dir.path()), ["a.txt"], "a braced variable is a word");
|
||||
}
|
||||
|
||||
/// Output the model never saw as printed counts for nothing.
|
||||
#[test]
|
||||
fn piped_redirected_or_backgrounded_output_does_not_count() {
|
||||
let dir = project(&[]);
|
||||
for command in [
|
||||
"cat a.txt | grep foo",
|
||||
"cat a.txt > /tmp/copy",
|
||||
"cat a.txt >> notes",
|
||||
"cat a.txt < b.txt",
|
||||
"cat a.txt &",
|
||||
"cat a.txt $(true)",
|
||||
"cat a.txt `true`",
|
||||
"cat a.txt \"$(true)\"",
|
||||
"cat a.txt \"`true`\"",
|
||||
"cat a.txt 'unterminated",
|
||||
"cat > a.txt <<'E'\nnew\nE",
|
||||
] {
|
||||
assert!(shown(command, dir.path()).is_empty(), "{command}");
|
||||
}
|
||||
for command in ["cat a.txt >&2", "cat a.txt 1>out", "cat a.txt &>out", "cat a.txt 12>x"] {
|
||||
assert!(shown(command, dir.path()).is_empty(), "stdout may be hidden: {command}");
|
||||
}
|
||||
// A pipe in one segment leaves the others alone
|
||||
assert_eq!(shown("cat a.txt; cat b.txt | wc -l", dir.path()), ["a.txt"]);
|
||||
}
|
||||
|
||||
/// Piped into `head` or `tail`, a file is still shown, a slice of it the way `read` with a
|
||||
/// `limit` shows one. Into anything that changes the text, it is not.
|
||||
#[test]
|
||||
fn a_pipe_into_head_or_tail_is_a_slice() {
|
||||
let dir = project(&[]);
|
||||
assert_eq!(shown("cat a.txt | head -60", dir.path()), ["a.txt"]);
|
||||
// Sending stderr away hides nothing the model reads
|
||||
assert_eq!(
|
||||
shown("cat test/*filter* 2>/dev/null | head -40", dir.path()),
|
||||
["test/filter.test.js"]
|
||||
);
|
||||
assert_eq!(shown("cat a.txt 2>&1 | head -5", dir.path()), ["a.txt"]);
|
||||
assert_eq!(shown("cat a.txt 2> /dev/null", dir.path()), ["a.txt"]);
|
||||
assert_eq!(shown("cat test/*.js | head -80", dir.path()), ["test/filter.test.js"]);
|
||||
assert_eq!(shown("nl a.txt | head -n 5 | tail -n 2", dir.path()), ["a.txt"]);
|
||||
for command in [
|
||||
"cat a.txt | head | sort",
|
||||
"cat a.txt | head -5 b.txt",
|
||||
"cat a.txt | tail -f",
|
||||
"cat a.txt | tail -F",
|
||||
"cat a.txt | tail --follow",
|
||||
"cat a.txt | head -5 > out.txt",
|
||||
"cat a.txt |",
|
||||
"| head",
|
||||
"grep x a.txt | sort",
|
||||
] {
|
||||
assert!(shown(command, dir.path()).is_empty(), "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Operators inside quotes, or escaped, are part of a name; outside them they split or taint.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn quoted_and_escaped_operators_are_names() {
|
||||
let dir = project(&["a|b.txt", "a;b.txt", "a>b.txt", "it\"s.txt", "it's.txt", "x\\"]);
|
||||
assert_eq!(shown("cat 'a|b.txt'", dir.path()), ["a|b.txt"]);
|
||||
assert_eq!(shown("cat \"a;b.txt\"", dir.path()), ["a;b.txt"]);
|
||||
assert_eq!(shown("cat 'a>b.txt' a.txt", dir.path()), ["a>b.txt", "a.txt"]);
|
||||
assert_eq!(shown("cat a\\|b.txt", dir.path()), ["a|b.txt"]);
|
||||
assert_eq!(shown("cat 'it\"s.txt'", dir.path()), ["it\"s.txt"]);
|
||||
assert_eq!(shown("cat \"it's.txt\"", dir.path()), ["it's.txt"]);
|
||||
// A backslash in single quotes is a character, so the quote still closes at the next `'`
|
||||
assert_eq!(shown("cat 'x\\' ; true", dir.path()), ["x\\"]);
|
||||
assert_eq!(shown("cat '$(true)' a.txt", dir.path()), ["a.txt"], "single quotes run nothing");
|
||||
}
|
||||
|
||||
/// Only the printers count, and only the forms of them that print.
|
||||
#[test]
|
||||
fn only_plain_printers_count() {
|
||||
let dir = project(&[]);
|
||||
for command in [
|
||||
"sed -i 's/a/b/' a.txt",
|
||||
"sed --in-place -n '1p' a.txt",
|
||||
"sed 's/a/b/' a.txt",
|
||||
"sed -n -e '1p' a.txt",
|
||||
"sed -n -f script.sed a.txt",
|
||||
"tail -f a.txt",
|
||||
"tail -F a.txt",
|
||||
"tail --follow a.txt",
|
||||
"grep -l foo a.txt",
|
||||
"grep -c foo a.txt",
|
||||
"grep -qn foo a.txt",
|
||||
"rg --files-with-matches foo a.txt",
|
||||
"grep -o foo a.txt",
|
||||
"less a.txt",
|
||||
"rm a.txt",
|
||||
"echo 'cat a.txt'",
|
||||
] {
|
||||
assert!(shown(command, dir.path()).is_empty(), "{command}");
|
||||
}
|
||||
assert!(shown("cat missing.txt", dir.path()).is_empty(), "not a file, not a read");
|
||||
}
|
||||
|
||||
/// `sed -n` prints the files after its script, whichever spelling of quiet it was given.
|
||||
#[test]
|
||||
fn sed_counts_the_files_after_its_script() {
|
||||
let dir = project(&["1p"]);
|
||||
assert_eq!(shown("sed -n '1,40p' src/filter.js", dir.path()), ["src/filter.js"]);
|
||||
assert_eq!(shown("sed --quiet 1p a.txt", dir.path()), ["a.txt"]);
|
||||
assert_eq!(shown("sed --silent 1p a.txt", dir.path()), ["a.txt"]);
|
||||
// The script is a script even when a file shares its name
|
||||
assert_eq!(shown("sed -n 1p b.txt", dir.path()), ["b.txt"]);
|
||||
}
|
||||
|
||||
/// A search shows the lines it matched, which is a slice of the file like `sed -n` prints.
|
||||
#[test]
|
||||
fn a_search_that_prints_lines_counts_its_file() {
|
||||
let dir = project(&[]);
|
||||
assert_eq!(shown("grep -n -A8 'def x' a.txt", dir.path()), ["a.txt"]);
|
||||
assert_eq!(shown("grep -n x a.txt | head -40", dir.path()), ["a.txt"]);
|
||||
assert_eq!(shown("rg -C3 x src/cli.js", dir.path()), ["src/cli.js"]);
|
||||
assert_eq!(shown("grep -e a.txt b.txt", dir.path()), ["b.txt"], "a.txt is the pattern");
|
||||
assert_eq!(shown("grep -A 3 x b.txt", dir.path()), ["b.txt"], "3 is -A's value");
|
||||
assert_eq!(shown("grep --context=3 x b.txt", dir.path()), ["b.txt"]);
|
||||
assert_eq!(shown("grep a.txt b.txt", dir.path()), ["b.txt"], "the first word is the pattern");
|
||||
// Nothing printed, nothing seen
|
||||
assert!(files_shown("grep x a.txt", dir.path(), "").is_empty());
|
||||
}
|
||||
|
||||
/// A search over many files counts the files its rows name, matches and context alike.
|
||||
#[test]
|
||||
fn a_search_over_many_files_counts_the_files_it_printed() {
|
||||
let dir = project(&["src/a-1.js"]);
|
||||
let printed = "src/cli.js:12:x\nsrc/a-1.js-3-context\nsrc/a-1.js:4:x\nnot/a/file.js:1:x\n";
|
||||
let rows = files_shown("grep -rn x src", dir.path(), printed);
|
||||
let names: Vec<_> =
|
||||
rows.iter().map(|p| p.strip_prefix(dir.path()).unwrap().to_owned()).collect();
|
||||
assert_eq!(names, [PathBuf::from("src/cli.js"), PathBuf::from("src/a-1.js")]);
|
||||
// A printer's own output is never read as rows
|
||||
assert!(files_shown("cat missing", dir.path(), printed).is_empty());
|
||||
}
|
||||
|
||||
/// Flags and their values are not files, `--` ends the flags, and `-` is standard input.
|
||||
#[test]
|
||||
fn flags_are_not_files() {
|
||||
let dir = project(&["-"]);
|
||||
assert_eq!(shown("head -n 20 -q a.txt", dir.path()), ["a.txt"]);
|
||||
assert_eq!(shown("head -n a.txt b.txt", dir.path()), ["b.txt"], "a.txt is -n's value");
|
||||
assert_eq!(shown("tail -40 src/filter.js", dir.path()), ["src/filter.js"]);
|
||||
assert_eq!(shown("cat -n -- src/cli.js", dir.path()), ["src/cli.js"]);
|
||||
assert_eq!(shown("cat -- -n", dir.path()), ["-n"], "past `--`, a dash is a name");
|
||||
assert_eq!(shown("cat - a.txt", dir.path()), ["a.txt"]);
|
||||
assert_eq!(shown("cat -- - a.txt", dir.path()), ["a.txt"], "still standard input");
|
||||
}
|
||||
564
crates/luxe-tools/src/bash/tests.rs
Normal file
564
crates/luxe-tools/src/bash/tests.rs
Normal file
@@ -0,0 +1,564 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
fn test_context(tmp_dir: &std::path::Path) -> ToolContext {
|
||||
let (event_tx, _event_rx) = mpsc::channel(64);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
ToolContext {
|
||||
cwd: tmp_dir.to_path_buf(),
|
||||
session_id: "test-session".to_string(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the assertions below can mean anything on this machine.
|
||||
///
|
||||
/// They are written in POSIX — `sleep 10`, `echo 'x'`, a pipeline — because that is the dialect
|
||||
/// the model writes and the one the tool promises. A Windows box with no Git for Windows has no
|
||||
/// shell that speaks it, and `cmd`'s complaint about a quote would be a fixture failure dressed
|
||||
/// as a product failure. The behavior *there* has its own assertion below.
|
||||
fn posix_shell_available() -> bool {
|
||||
luxe_core::program::has_posix_shell()
|
||||
}
|
||||
|
||||
/// A directory of this test's own, deleted when it is dropped; it reads as the path it holds.
|
||||
struct Scratch(tempfile::TempDir);
|
||||
|
||||
impl std::ops::Deref for Scratch {
|
||||
type Target = std::path::Path;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.0.path()
|
||||
}
|
||||
}
|
||||
|
||||
fn scratch_dir(name: &str) -> Scratch {
|
||||
Scratch(
|
||||
tempfile::Builder::new()
|
||||
.prefix(&format!("luxe-test-{name}-"))
|
||||
.tempdir()
|
||||
.expect("scratch dir"),
|
||||
)
|
||||
}
|
||||
|
||||
/// The last command is the one whose status the shell reports, and a pipe inside a quoted
|
||||
/// pattern does not end it.
|
||||
#[test]
|
||||
fn a_search_is_found_at_the_end_of_the_command() {
|
||||
assert!(ends_in_search("grep -n foo src/lib.rs"));
|
||||
assert!(ends_in_search(r#"npm test 2>&1 | grep -E "^not ok|^# (pass|fail)""#));
|
||||
assert!(ends_in_search("cd x && LC_ALL=C /usr/bin/rg needle"));
|
||||
assert!(ends_in_search("ls; egrep 'a|b' notes"));
|
||||
assert!(!ends_in_search("grep foo src | wc -l"), "wc ends it");
|
||||
assert!(!ends_in_search("grep foo src 2>&1"), "a redirection after it is unclear");
|
||||
assert!(!ends_in_search("echo 'grep x'"));
|
||||
assert!(!ends_in_search("false"));
|
||||
}
|
||||
|
||||
/// Nothing matched is an answer: no red card, and the model is told what exit 1 meant. A search
|
||||
/// that complained, or any other failing command, is still a failure.
|
||||
#[tokio::test]
|
||||
async fn a_search_that_matches_nothing_is_not_a_failure() {
|
||||
if !posix_shell_available() {
|
||||
return;
|
||||
}
|
||||
let tmp_dir = scratch_dir("no-match");
|
||||
let tool = BashTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
let text = |result: &ToolResultData| match &result.content[0] {
|
||||
ContentBlock::Text(text) => text.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
|
||||
let quiet = tool.run(json!({"command": "printf 'ok\\n' | grep zzz"}), &cx).await;
|
||||
assert!(!quiet.is_error, "{}", text(&quiet));
|
||||
assert!(text(&quiet).contains("matched nothing"), "{}", text(&quiet));
|
||||
|
||||
let missing = tool.run(json!({"command": "grep zzz no-such-file"}), &cx).await;
|
||||
assert!(missing.is_error, "a search that complained failed: {}", text(&missing));
|
||||
|
||||
let failed = tool.run(json!({"command": "false"}), &cx).await;
|
||||
assert!(failed.is_error);
|
||||
assert!(!text(&failed).contains("matched nothing"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bash_tool_basic() {
|
||||
if !posix_shell_available() {
|
||||
return;
|
||||
}
|
||||
let tmp_dir = scratch_dir("bash");
|
||||
|
||||
let tool = BashTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({
|
||||
"command": "echo 'Hello, World!'"
|
||||
});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(!result.is_error);
|
||||
if let ContentBlock::Text(text) = &result.content[0] {
|
||||
assert!(text.contains("Hello, World!"));
|
||||
assert!(text.contains("Exit code: 0"));
|
||||
} else {
|
||||
panic!("expected Text block");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bash_tool_timeout() {
|
||||
if !posix_shell_available() {
|
||||
return;
|
||||
}
|
||||
let tmp_dir = scratch_dir("bash-timeout");
|
||||
|
||||
let tool = BashTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({
|
||||
"command": "sleep 10",
|
||||
"timeout": 1
|
||||
});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(result.is_error);
|
||||
if let ContentBlock::Text(text) = &result.content[0] {
|
||||
assert!(text.contains("timed out"));
|
||||
} else {
|
||||
panic!("expected Text block");
|
||||
}
|
||||
}
|
||||
|
||||
/// A command that leaves something running returns when *it* is done.
|
||||
///
|
||||
/// The incident: `cd /tmp && nohup setsid app >log 2>&1 </dev/null &` followed by `sleep 8`.
|
||||
/// Everything about it is right except that `&` backgrounds the whole `&&` list, so the
|
||||
/// subshell — which never got the redirections — sat holding this call's pipe for as long as
|
||||
/// the app was open. Waiting for the pipe to close meant waiting for the app to be closed;
|
||||
/// the call reported `8s` and ran for a minute, and the reader interrupted it.
|
||||
///
|
||||
/// The reported command is kept verbatim, and what it is asserted to do is only the part that
|
||||
/// does not depend on the shell: **whether the pipe is still held is bash's call, not ours.**
|
||||
/// The long-lived command here redirects away from the pipe, so the only thing that can hold it
|
||||
/// is the intermediate subshell — and whether one survives is an optimization. bash 5.3 forks
|
||||
/// and keeps it; the 5.2 on CI execs the tail in place and the pipe closes with the shell. The
|
||||
/// note that says output was cut short is therefore pinned by the test below, on a command that
|
||||
/// holds the pipe on any shell.
|
||||
#[tokio::test]
|
||||
async fn a_process_left_running_does_not_hold_the_call_open() {
|
||||
if !posix_shell_available() {
|
||||
return;
|
||||
}
|
||||
let tmp_dir = scratch_dir("bash-detached");
|
||||
let tool = BashTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let started = std::time::Instant::now();
|
||||
let result = tool
|
||||
.run(
|
||||
json!({
|
||||
"command": "true && sleep 30 >/dev/null 2>&1 </dev/null & \nsleep 1; echo ran",
|
||||
"timeout": 20,
|
||||
}),
|
||||
&cx,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(10),
|
||||
"the call ends with the command, not with what the command left running"
|
||||
);
|
||||
assert!(!result.is_error);
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected Text block") };
|
||||
assert!(text.contains("ran"), "the output it did produce is still there: {text}");
|
||||
}
|
||||
|
||||
/// Output cut short by something still holding the pipe says so.
|
||||
///
|
||||
/// `sleep 30 &` with no redirection is the unambiguous shape: the child inherits this call's
|
||||
/// stdout and keeps it for thirty seconds, which no shell can optimize away, so the drain grace
|
||||
/// always expires. The reader is about to compare this output against what the command prints
|
||||
/// in a terminal, and the difference is a detail of shell syntax rather than anything they got
|
||||
/// wrong.
|
||||
#[tokio::test]
|
||||
async fn output_held_open_by_a_detached_writer_says_so() {
|
||||
if !posix_shell_available() {
|
||||
return;
|
||||
}
|
||||
let tmp_dir = scratch_dir("bash-detached-note");
|
||||
let tool = BashTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let started = std::time::Instant::now();
|
||||
let result = tool.run(json!({ "command": "sleep 30 & echo ran", "timeout": 20 }), &cx).await;
|
||||
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(10),
|
||||
"the call ends with the command: {:?}",
|
||||
started.elapsed()
|
||||
);
|
||||
assert!(!result.is_error);
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected Text block") };
|
||||
assert!(text.contains("ran"), "the output it did produce is still there: {text}");
|
||||
assert!(
|
||||
text.contains("still held its output"),
|
||||
"and the reader is told why it might be short: {text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bash_tool_nonzero_exit() {
|
||||
let tmp_dir = scratch_dir("bash-exit");
|
||||
|
||||
let tool = BashTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({
|
||||
"command": "exit 1"
|
||||
});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(result.is_error);
|
||||
if let ContentBlock::Text(text) = &result.content[0] {
|
||||
assert!(text.contains("Exit code: 1"));
|
||||
} else {
|
||||
panic!("expected Text block");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bash_tool_compresses_noisy_output_but_keeps_errors() {
|
||||
if !posix_shell_available() {
|
||||
return;
|
||||
}
|
||||
let tmp_dir = scratch_dir("bash-compress");
|
||||
let tool = BashTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
// 600 lines of build noise with one real error buried inside.
|
||||
let args = json!({
|
||||
"command": "for i in $(seq 1 600); do echo \" Compiling crate_$i v1.0\"; done; \
|
||||
echo 'error: boom at src/x.rs:9:1'"
|
||||
});
|
||||
let result = tool.run(args, &cx).await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else {
|
||||
panic!("expected Text block");
|
||||
};
|
||||
assert!(text.contains("error: boom"), "buried error must survive: {text}");
|
||||
assert!(text.contains("src/x.rs:9:1"), "file:line must survive");
|
||||
assert!(text.contains("compressed"), "savings footer expected: {text}");
|
||||
assert!(text.contains("Full output:"), "artifact reference expected");
|
||||
let artifacts = tmp_dir.join(".luxe").join("artifacts");
|
||||
assert!(artifacts.is_dir() && artifacts.read_dir().unwrap().count() >= 1);
|
||||
}
|
||||
|
||||
/// A suite run through the shell names what broke since its last run, as the `test` tool does.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_test_run_through_bash_names_its_regressions() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if !posix_shell_available() {
|
||||
return;
|
||||
}
|
||||
let tmp_dir = scratch_dir("bash-regression");
|
||||
let script = tmp_dir.join("tests").join("runtests.py");
|
||||
std::fs::create_dir_all(script.parent().unwrap()).unwrap();
|
||||
std::fs::write(
|
||||
&script,
|
||||
"#!/bin/sh\n\
|
||||
if [ -f ../broken ]; then\n\
|
||||
printf 'test_a (app.tests.T) ... ok\\ntest_b (app.tests.T) ... FAIL\\n\\n'\n\
|
||||
printf '======================================================================\\n'\n\
|
||||
printf 'FAIL: test_b (app.tests.T)\\n'\n\
|
||||
printf -- '----------------------------------------------------------------------\\n'\n\
|
||||
printf 'AssertionError\\n\\n'\n\
|
||||
printf -- '----------------------------------------------------------------------\\n'\n\
|
||||
printf 'Ran 2 tests in 0.001s\\n\\nFAILED (failures=1)\\n' >&2; exit 1\n\
|
||||
fi\n\
|
||||
printf 'Ran 2 tests in 0.001s\\n\\nOK\\n' >&2\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let tool = BashTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
let run = || async {
|
||||
let result =
|
||||
tool.run(json!({"command": "cd tests && ./runtests.py app 2>&1 | tail -20"}), &cx);
|
||||
let result = result.await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("text") };
|
||||
text.clone()
|
||||
};
|
||||
|
||||
let green = run().await;
|
||||
assert!(!green.contains("REGRESSION"), "{green}");
|
||||
std::fs::write(tmp_dir.join("broken"), "").unwrap();
|
||||
let red = run().await;
|
||||
assert!(red.starts_with("REGRESSION — 1 test(s)"), "{red}");
|
||||
assert!(red.contains("test_b"), "{red}");
|
||||
}
|
||||
|
||||
/// A Windows box without Git for Windows runs through `cmd`, which refuses most of what a
|
||||
/// model writes. The tool must say *why* once, on failure, instead of handing back cmd's
|
||||
/// complaint about a quote and letting the model debug its own perfectly good command.
|
||||
///
|
||||
/// `exit 1` is understood by both shells, so the assertion is about the annotation, not the
|
||||
/// dialect: present when there is no POSIX shell, absent when there is.
|
||||
#[tokio::test]
|
||||
async fn a_failure_without_a_posix_shell_says_that_is_why() {
|
||||
let tmp_dir = scratch_dir("bash-noshell");
|
||||
let result = BashTool::new().run(json!({"command": "exit 1"}), &test_context(&tmp_dir)).await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
|
||||
assert_eq!(
|
||||
text.contains("no POSIX shell was found"),
|
||||
!posix_shell_available(),
|
||||
"the note appears exactly when cmd.exe is what ran it: {text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bash_tool_missing_command() {
|
||||
let tmp_dir = scratch_dir("bash-mc");
|
||||
|
||||
let tool = BashTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(result.is_error);
|
||||
}
|
||||
|
||||
/// The compressor works per line, so a single enormous line escaped it entirely and 500 KB
|
||||
/// went straight into the context window. The clamp is the backstop.
|
||||
#[tokio::test]
|
||||
async fn one_enormous_line_is_clamped() {
|
||||
if !posix_shell_available() {
|
||||
return;
|
||||
}
|
||||
let tmp_dir = tempfile::tempdir().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
let tool = BashTool::new();
|
||||
|
||||
let result =
|
||||
tool.run(serde_json::json!({"command": "python3 -c \"print('x'*500000)\""}), &ctx).await;
|
||||
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(
|
||||
text.chars().count() < MAX_OUTPUT_BYTES + 2_000,
|
||||
"clamped, got {} chars",
|
||||
text.chars().count()
|
||||
);
|
||||
assert!(text.contains("clamped"), "and says it clamped: {}", &text[..200.min(text.len())]);
|
||||
assert!(text.contains("Full output: "), "with the path back to all of it");
|
||||
let artifacts = tmp_dir.path().join(".luxe").join("artifacts");
|
||||
assert_eq!(artifacts.read_dir().map(Iterator::count).unwrap_or(0), 1, "saved there");
|
||||
}
|
||||
|
||||
/// A long line of multi-byte characters is cut between characters. The cut used to land on a
|
||||
/// byte offset and panic whenever that offset was inside one.
|
||||
#[test]
|
||||
fn the_clamp_never_cuts_inside_a_character() {
|
||||
for unit in ["€", "é", "\u{1F600}", "x"] {
|
||||
for extra in 0..4 {
|
||||
let text = format!("{}{}", "x".repeat(extra), unit.repeat(MAX_OUTPUT_BYTES));
|
||||
let clamped = clamp_bytes(&text, MAX_OUTPUT_BYTES);
|
||||
if text.len() <= MAX_OUTPUT_BYTES {
|
||||
assert_eq!(clamped, text, "at the cap, untouched");
|
||||
continue;
|
||||
}
|
||||
assert!(clamped.len() <= MAX_OUTPUT_BYTES + 60, "{unit} {extra}: {}", clamped.len());
|
||||
let dropped: usize = clamped
|
||||
.split_once("-- clamped ")
|
||||
.and_then(|(_, rest)| rest.split_once(' '))
|
||||
.and_then(|(count, _)| count.parse().ok())
|
||||
.expect("says how much it dropped");
|
||||
let kept = clamped.len() - format!("\n-- clamped {dropped} bytes --\n").len();
|
||||
assert_eq!(kept + dropped, text.len(), "{unit} {extra}: the count is exact");
|
||||
}
|
||||
}
|
||||
assert_eq!(clamp_bytes("short", MAX_OUTPUT_BYTES), "short");
|
||||
}
|
||||
|
||||
/// A command that runs out of time still says what it had printed, and how to give it longer.
|
||||
#[tokio::test]
|
||||
async fn a_timeout_keeps_what_the_command_printed() {
|
||||
if !posix_shell_available() {
|
||||
return;
|
||||
}
|
||||
let tmp_dir = tempfile::tempdir().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
let result = BashTool::new()
|
||||
.run(serde_json::json!({"command": "echo started; sleep 5", "timeout": 1}), &ctx)
|
||||
.await;
|
||||
assert!(result.is_error);
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("timed out after 1 seconds"), "{text}");
|
||||
assert!(text.contains("Output before it was stopped:\nstarted"), "{text}");
|
||||
assert!(text.contains("pass `timeout`"), "{text}");
|
||||
|
||||
let silent =
|
||||
BashTool::new().run(serde_json::json!({"command": "sleep 5", "timeout": 1}), &ctx).await;
|
||||
let ContentBlock::Text(text) = &silent.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("printed nothing"), "{text}");
|
||||
}
|
||||
|
||||
/// A timeout names what was still running, so "slow" and "stuck" stop looking the same.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_timeout_lists_what_was_still_running() {
|
||||
let tmp_dir = tempfile::tempdir().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
let result = BashTool::new()
|
||||
.run(serde_json::json!({"command": "sleep 7 & sleep 8", "timeout": 1}), &ctx)
|
||||
.await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("Still running when it was stopped (pid, state, command):"), "{text}");
|
||||
assert!(text.contains("sleep 7"), "{text}");
|
||||
assert!(text.contains("pass `timeout`"), "nothing suspended, so more time may help: {text}");
|
||||
assert!(!text.contains("State T"), "{text}");
|
||||
}
|
||||
|
||||
/// Marks the run of [`under_a_terminal`] that [`a_command_that_touches_the_terminal_still_finishes`]
|
||||
/// starts, so a plain `--ignored` run of the suite skips it.
|
||||
#[cfg(unix)]
|
||||
const UNDER_A_TERMINAL: &str = "LUXE_TEST_UNDER_A_TERMINAL";
|
||||
|
||||
/// The omacvm incident, end to end: a background job that changes the terminal's settings, as a
|
||||
/// spinner does with `stty -echo < /dev/tty`, then a foreground `echo`.
|
||||
///
|
||||
/// Before commands left Luxe's terminal, the kernel suspended the whole process group for that,
|
||||
/// foreground shell included, and the call timed out having "printed nothing". Reproducing it
|
||||
/// takes a real controlling terminal and a process not run by nextest (which runs tests where
|
||||
/// none of this happens), so this re-runs its own test binary under `script(1)`.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_command_that_touches_the_terminal_still_finishes() {
|
||||
let Some(script) = luxe_core::program::resolve("script") else {
|
||||
eprintln!("skipped: script(1) is not installed, so there is no terminal to test under");
|
||||
return;
|
||||
};
|
||||
let exe = std::env::current_exe().expect("the test binary");
|
||||
let inner = ["bash::tests::under_a_terminal", "--exact", "--ignored", "--nocapture"];
|
||||
let mut command = std::process::Command::new(script);
|
||||
if cfg!(target_os = "macos") {
|
||||
command.args(["-q", "/dev/null"]).arg(&exe).args(inner);
|
||||
} else {
|
||||
let quote = |text: &str| format!("'{}'", text.replace('\'', "'\\''"));
|
||||
let line = std::iter::once(quote(&exe.to_string_lossy()))
|
||||
.chain(inner.iter().map(|arg| quote(arg)))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
command.args(["-qec", &line, "/dev/null"]);
|
||||
}
|
||||
let output = command
|
||||
.env(UNDER_A_TERMINAL, "1")
|
||||
.stdin(std::process::Stdio::null())
|
||||
.output()
|
||||
.expect("script runs");
|
||||
let said = format!(
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
if said.contains("NO_TERMINAL") {
|
||||
eprintln!("skipped: script(1) gave the test no controlling terminal");
|
||||
return;
|
||||
}
|
||||
assert!(said.contains("FINISHED_PAST_THE_TERMINAL"), "{said}");
|
||||
}
|
||||
|
||||
/// The half of the test above that runs under the terminal. Reports by marker, because its
|
||||
/// output reaches the outer test through `script`, not through the test harness.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
#[ignore = "run under a real terminal by a_command_that_touches_the_terminal_still_finishes"]
|
||||
async fn under_a_terminal() {
|
||||
if std::env::var_os(UNDER_A_TERMINAL).is_none() {
|
||||
return;
|
||||
}
|
||||
if std::fs::File::open("/dev/tty").is_err() {
|
||||
println!("NO_TERMINAL");
|
||||
return;
|
||||
}
|
||||
let tmp_dir = tempfile::tempdir().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
let result = BashTool::new()
|
||||
.run(
|
||||
serde_json::json!({
|
||||
"command": "(stty -echo </dev/tty; sleep 20) & sleep 1; echo reached",
|
||||
"timeout": 8
|
||||
}),
|
||||
&ctx,
|
||||
)
|
||||
.await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
if !result.is_error && text.contains("reached") {
|
||||
println!("FINISHED_PAST_THE_TERMINAL");
|
||||
} else {
|
||||
println!("STUCK: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A suspended command could never finish, and the old advice was to give it longer. A terminal
|
||||
/// can no longer suspend one (see `a_command_that_touches_the_terminal_still_finishes`), so this
|
||||
/// stops one by hand.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_suspended_command_is_called_stuck_not_slow() {
|
||||
let tmp_dir = tempfile::tempdir().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
let result = BashTool::new()
|
||||
.run(serde_json::json!({"command": "sleep 9 & kill -STOP $!; sleep 8", "timeout": 1}), &ctx)
|
||||
.await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("State T means suspended, not slow"), "{text}");
|
||||
assert!(!text.contains("pass `timeout`"), "more time cannot help a suspended command: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timeout_with_nothing_left_running_lists_nothing_and_a_long_list_is_counted() {
|
||||
use luxe_core::program::GroupMember;
|
||||
assert!(!timeout_advice(&[]).contains("Still running"));
|
||||
let member = |pid: u32| GroupMember {
|
||||
pid,
|
||||
state: "S".into(),
|
||||
command: format!("worker {pid} {}", "x".repeat(200)),
|
||||
};
|
||||
let crowd: Vec<GroupMember> = (1..=12).map(member).collect();
|
||||
let text = timeout_advice(&crowd);
|
||||
assert!(text.contains(" 10 S worker 10"), "{text}");
|
||||
assert!(!text.contains(" 11 S"), "{text}");
|
||||
assert!(text.contains("… +2 more"), "{text}");
|
||||
assert!(text.contains("x…"), "a long command line is cut: {text}");
|
||||
|
||||
let exactly = |pid: u32| GroupMember {
|
||||
pid,
|
||||
state: "S".into(),
|
||||
command: "y".repeat(SURVIVOR_COMMAND_CHARS),
|
||||
};
|
||||
let full: Vec<GroupMember> = (1..=MAX_SURVIVORS_LISTED as u32).map(exactly).collect();
|
||||
let text = timeout_advice(&full);
|
||||
assert!(!text.contains('…'), "a list and a line exactly at their caps are whole: {text}");
|
||||
}
|
||||
|
||||
/// Volume was never the problem — proving the compressor still does its job.
|
||||
#[tokio::test]
|
||||
async fn many_lines_still_compress_far_below_the_clamp() {
|
||||
if !posix_shell_available() {
|
||||
return;
|
||||
}
|
||||
let tmp_dir = tempfile::tempdir().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
let result = BashTool::new().run(serde_json::json!({"command": "seq 1 200000"}), &ctx).await;
|
||||
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.chars().count() < 5_000, "compressed, got {} chars", text.chars().count());
|
||||
}
|
||||
202
crates/luxe-tools/src/brave.rs
Normal file
202
crates/luxe-tools/src/brave.rs
Normal file
@@ -0,0 +1,202 @@
|
||||
//! Brave Search — a keyed web index, reached over its REST API.
|
||||
//!
|
||||
//! Brave has no domain-filter parameter, so `domains` becomes `site:`/`-site:` operators in the
|
||||
//! query itself, which its index understands. Recency is Brave's own coarse `freshness` code
|
||||
//! rather than a date. What it cannot do is carry a page's text: `description` is a search snippet
|
||||
//! of a couple of hundred characters, so [`SearchBackend::honors`] says so and the caller passes
|
||||
//! that on rather than letting the model treat a snippet as the passage.
|
||||
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::web::{SearchBackend, SearchHit, SearchOptions, WebError};
|
||||
|
||||
/// Most results Brave's API accepts. It answers 422 above this, not a clamped list.
|
||||
const MAX_COUNT: usize = 20;
|
||||
|
||||
/// Brave Search API response.
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct BraveResponse {
|
||||
web: Option<BraveWeb>,
|
||||
/// Present instead of `web` when Brave rejects the request.
|
||||
error: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct BraveWeb {
|
||||
results: Option<Vec<BraveResult>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct BraveResult {
|
||||
title: Option<String>,
|
||||
url: Option<String>,
|
||||
description: Option<String>,
|
||||
}
|
||||
|
||||
/// Brave search backend.
|
||||
pub struct BraveBackend {
|
||||
api_key: String,
|
||||
base_url: String,
|
||||
}
|
||||
|
||||
impl BraveBackend {
|
||||
/// A backend against Brave's public endpoint.
|
||||
pub fn new(api_key: String) -> Self {
|
||||
Self { api_key, base_url: "https://api.search.brave.com/res/v1/web/search".to_string() }
|
||||
}
|
||||
|
||||
/// Point the backend at a stand-in endpoint (tests, a proxy).
|
||||
pub fn with_base_url(api_key: String, base_url: impl Into<String>) -> Self {
|
||||
Self { api_key, base_url: base_url.into() }
|
||||
}
|
||||
|
||||
/// The URL for one search, with every value properly encoded.
|
||||
///
|
||||
/// Built through `query_pairs_mut` rather than `format!`, which is not a style preference: an
|
||||
/// interpolated query ends at the first `&` and at the first `#`, so `tokio select! &
|
||||
/// cancellation` reached Brave as `tokio select!` and `rust #[tokio::main]` as `rust` — a
|
||||
/// wrong answer returned with no error at all.
|
||||
fn request_url(&self, query: &str, n: usize, options: &SearchOptions) -> String {
|
||||
let mut url = match url::Url::parse(&self.base_url) {
|
||||
Ok(url) => url,
|
||||
Err(_) => return self.base_url.clone(),
|
||||
};
|
||||
{
|
||||
let mut pairs = url.query_pairs_mut();
|
||||
pairs.append_pair("q", &options.applied_to(query));
|
||||
pairs.append_pair("count", &n.clamp(1, MAX_COUNT).to_string());
|
||||
if let Some(recency) = options.recency {
|
||||
pairs.append_pair("freshness", recency.brave_code());
|
||||
}
|
||||
}
|
||||
url.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl SearchBackend for BraveBackend {
|
||||
async fn search(
|
||||
&self,
|
||||
query: &str,
|
||||
n: usize,
|
||||
options: &SearchOptions,
|
||||
) -> Result<Vec<SearchHit>, WebError> {
|
||||
let response = reqwest::Client::new()
|
||||
.get(self.request_url(query, n, options))
|
||||
.header("Accept", "application/json")
|
||||
.header("X-Subscription-Token", &self.api_key)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| WebError::Network(e.to_string()))?;
|
||||
|
||||
let status = response.status();
|
||||
let body = response.text().await.map_err(|e| WebError::Network(e.to_string()))?;
|
||||
if !status.is_success() {
|
||||
return Err(WebError::Http(format!("Brave returned {status}: {}", body.trim())));
|
||||
}
|
||||
|
||||
let parsed: BraveResponse =
|
||||
serde_json::from_str(&body).map_err(|e| WebError::Parse(e.to_string()))?;
|
||||
if let Some(error) = parsed.error {
|
||||
return Err(WebError::Backend(format!("Brave: {error}")));
|
||||
}
|
||||
|
||||
Ok(parsed
|
||||
.web
|
||||
.and_then(|web| web.results)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|result| SearchHit {
|
||||
title: result.title.unwrap_or_default(),
|
||||
url: result.url.unwrap_or_default(),
|
||||
snippet: result.description.unwrap_or_default(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn honors(&self, options: &SearchOptions) -> Vec<String> {
|
||||
match options.include_content {
|
||||
true => {
|
||||
vec!["Brave returns a short search snippet per result, not the page's own text — \
|
||||
web_fetch a result for the full page."
|
||||
.to_string()]
|
||||
}
|
||||
false => Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn backend() -> BraveBackend {
|
||||
BraveBackend::new("test-key".to_string())
|
||||
}
|
||||
|
||||
/// The reported failure, as the three characters that caused it. Brave answered 200 with
|
||||
/// results for a *different* query, so nothing downstream could tell.
|
||||
#[test]
|
||||
fn a_query_reaches_brave_whole_however_it_is_punctuated() {
|
||||
for (query, encoded) in [
|
||||
("tokio select! & cancellation", "%26"),
|
||||
("rust #[tokio::main] macro", "%23"),
|
||||
("a + b in rust", "%2B"),
|
||||
] {
|
||||
let url = backend().request_url(query, 5, &SearchOptions::default());
|
||||
let parsed = url::Url::parse(&url).expect("a valid URL");
|
||||
let got = parsed
|
||||
.query_pairs()
|
||||
.find(|(key, _)| key == "q")
|
||||
.map(|(_, value)| value.into_owned())
|
||||
.expect("q is present");
|
||||
assert_eq!(got, query, "{url}");
|
||||
assert!(url.contains(encoded), "the character must go over the wire escaped: {url}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Brave answers 422 above 20 rather than returning what it can, so the ceiling is ours to
|
||||
/// hold — and a caller asking for one result must not be handed Brave's default page.
|
||||
#[test]
|
||||
fn the_result_count_is_clamped_to_what_brave_accepts() {
|
||||
let count = |n: usize| {
|
||||
let url = backend().request_url("rust", n, &SearchOptions::default());
|
||||
url::Url::parse(&url)
|
||||
.expect("a valid URL")
|
||||
.query_pairs()
|
||||
.find(|(key, _)| key == "count")
|
||||
.map(|(_, value)| value.into_owned())
|
||||
.expect("count is present")
|
||||
};
|
||||
assert_eq!(count(3), "3");
|
||||
assert_eq!(count(20), "20");
|
||||
assert_eq!(count(50), "20");
|
||||
assert_eq!(count(0), "1");
|
||||
}
|
||||
|
||||
/// Brave has no domain parameter, so a filter the schema advertises has to become something
|
||||
/// its index reads — otherwise it is a request that silently does nothing.
|
||||
#[test]
|
||||
fn domain_filters_become_site_operators_and_recency_becomes_a_freshness_code() {
|
||||
let options = SearchOptions {
|
||||
include_domains: vec!["docs.rs".to_string()],
|
||||
exclude_domains: vec!["reddit.com".to_string()],
|
||||
recency: Some(crate::web::Recency::Week),
|
||||
..Default::default()
|
||||
};
|
||||
let url = url::Url::parse(&backend().request_url("tokio", 5, &options)).expect("valid");
|
||||
let pairs: std::collections::HashMap<_, _> = url.query_pairs().into_owned().collect();
|
||||
assert_eq!(pairs["q"], "tokio site:docs.rs -site:reddit.com");
|
||||
assert_eq!(pairs["freshness"], "pw");
|
||||
}
|
||||
|
||||
/// A snippet is not a passage, and a model told otherwise stops fetching pages it needs.
|
||||
#[test]
|
||||
fn brave_admits_it_returns_snippets_rather_than_page_text() {
|
||||
let asked = SearchOptions { include_content: true, ..Default::default() };
|
||||
assert!(backend().honors(&asked)[0].contains("web_fetch"));
|
||||
assert!(backend().honors(&SearchOptions::default()).is_empty());
|
||||
}
|
||||
}
|
||||
232
crates/luxe-tools/src/diff_preview.rs
Normal file
232
crates/luxe-tools/src/diff_preview.rs
Normal file
@@ -0,0 +1,232 @@
|
||||
//! Diff previews — line-numbered, context-bearing summaries of `edit`/`write` changes.
|
||||
//!
|
||||
//! `edit` knows each change exactly (a literal `oldText → newText` at a unique location), so the
|
||||
//! preview is computed directly from those replacements — no diff algorithm, no extra dependency.
|
||||
//!
|
||||
//! The rendering deliberately drops unified-diff hunk headers (`@@ -1,4 +1,4 @@`), which carry
|
||||
//! nothing a reader of a tool card wants. Instead every row is `<sign><line> <text>` and skipped
|
||||
//! regions collapse to a `...` row, so a card reads like the file with the change highlighted:
|
||||
//!
|
||||
//! ```text
|
||||
//! ...
|
||||
//! 11 fn main() {
|
||||
//! -12 println!("old");
|
||||
//! +12 println!("new");
|
||||
//! 13 }
|
||||
//! ...
|
||||
//! ```
|
||||
//!
|
||||
//! `write` shows its new content the same way, as an all-additions block.
|
||||
//!
|
||||
//! Context is measured from what actually *differs*, never from the text the caller matched. A
|
||||
//! model that matches a whole block to change one line inside it gets a preview of the change
|
||||
//! rather than of the block.
|
||||
|
||||
use crate::output_limit::cap_lines;
|
||||
|
||||
/// Rows a preview is capped at before pointing to the guided review.
|
||||
const DIFF_MAX_LINES: usize = 24;
|
||||
/// Unchanged lines kept either side of what differs.
|
||||
const CONTEXT_LINES: usize = 3;
|
||||
|
||||
/// One rendered preview row.
|
||||
struct Row {
|
||||
/// `' '` context, `'-'` removed, `'+'` added.
|
||||
sign: char,
|
||||
/// Line number to show, or `None` for an elision row.
|
||||
number: Option<usize>,
|
||||
text: String,
|
||||
}
|
||||
|
||||
/// Build a line-numbered preview for a set of literal replacements against `original`.
|
||||
///
|
||||
/// Line numbers are the *original* file's, which is what the model just read and what a follow-up
|
||||
/// edit will be written against. Overlapping or adjacent changes share one context block.
|
||||
pub fn edits_diff(original: &str, edits: &[(&str, &str)]) -> String {
|
||||
let located: Vec<(std::ops::Range<usize>, &str)> = edits
|
||||
.iter()
|
||||
.filter_map(|(old, new)| original.find(old).map(|at| (at..at + old.len(), *new)))
|
||||
.collect();
|
||||
ranges_diff(original, &located)
|
||||
}
|
||||
|
||||
/// A preview of replacements already resolved to byte ranges.
|
||||
///
|
||||
/// The caller that knows *where* an edit landed should say so. Re-finding the search text here
|
||||
/// cannot: a match that was tolerated (whitespace, indentation) is not a substring of the file at
|
||||
/// all, and a `replaceAll` has several homes rather than one; re-finding would preview something
|
||||
/// other than what was written.
|
||||
pub fn ranges_diff(original: &str, edits: &[(std::ops::Range<usize>, &str)]) -> String {
|
||||
let lines: Vec<&str> = original.split('\n').collect();
|
||||
let mut changes: Vec<Change> =
|
||||
edits.iter().map(|(range, new)| change_at(original, &lines, range.clone(), new)).collect();
|
||||
changes.sort_by_key(|change| change.replaced.start);
|
||||
|
||||
let mut rows: Vec<Row> = Vec::new();
|
||||
// The first line no block has covered yet.
|
||||
let mut emitted_through: Option<usize> = None;
|
||||
for change in &changes {
|
||||
let context_start = change.replaced.start.saturating_sub(CONTEXT_LINES);
|
||||
// Elide whatever sits between the previous block and this one.
|
||||
match emitted_through {
|
||||
None if context_start > 0 => rows.push(elision()),
|
||||
Some(previous) if context_start > previous => rows.push(elision()),
|
||||
_ => {}
|
||||
}
|
||||
let leading_from =
|
||||
emitted_through.map_or(context_start, |previous| context_start.max(previous));
|
||||
for index in leading_from..change.replaced.start {
|
||||
rows.push(context_row(&lines, index));
|
||||
}
|
||||
push_change_rows(&mut rows, change);
|
||||
let trailing_end = (change.replaced.end + CONTEXT_LINES).min(lines.len());
|
||||
for index in change.replaced.end..trailing_end {
|
||||
rows.push(context_row(&lines, index));
|
||||
}
|
||||
emitted_through = Some(trailing_end);
|
||||
}
|
||||
if emitted_through.is_some_and(|last| last < lines.len()) {
|
||||
rows.push(elision());
|
||||
}
|
||||
|
||||
cap_lines(&render(&rows), DIFF_MAX_LINES, "diff lines", "`read` the file for the rest.")
|
||||
}
|
||||
|
||||
/// A preview of everything that differs between two versions of a file, as one change.
|
||||
///
|
||||
/// For when the change is not one the caller made: format-on-save rewrites the file after an edit,
|
||||
/// and the preview has to show the text the next edit will be matched against. Without a diff
|
||||
/// algorithm it spans from the first difference to the last, so far-apart changes share a block.
|
||||
pub fn texts_diff(before: &str, after: &str) -> String {
|
||||
let prefix = before
|
||||
.char_indices()
|
||||
.zip(after.chars())
|
||||
.find(|((_, a), b)| a != b)
|
||||
.map_or(before.len().min(after.len()), |((at, _), _)| at);
|
||||
let suffix = before[prefix..]
|
||||
.chars()
|
||||
.rev()
|
||||
.zip(after[prefix..].chars().rev())
|
||||
.take_while(|(a, b)| a == b)
|
||||
.map(|(a, _)| a.len_utf8())
|
||||
.sum::<usize>();
|
||||
let replaced = prefix..before.len() - suffix;
|
||||
ranges_diff(before, &[(replaced, &after[prefix..after.len() - suffix])])
|
||||
}
|
||||
|
||||
/// Render `content` as an all-additions block — a `write` creates every line.
|
||||
pub fn added_lines(content: &str) -> String {
|
||||
let rows = content
|
||||
.split('\n')
|
||||
.enumerate()
|
||||
.map(|(index, line)| Row { sign: '+', number: Some(index + 1), text: line.to_string() })
|
||||
.collect::<Vec<_>>();
|
||||
// Nothing to follow here, so the hint says so rather than sending the caller to re-read a file
|
||||
// it just authored: this is the preview of a `write` that already succeeded in full.
|
||||
cap_lines(
|
||||
&render(&rows),
|
||||
DIFF_MAX_LINES,
|
||||
"lines",
|
||||
"The file has all of it; the preview is trimmed.",
|
||||
)
|
||||
}
|
||||
|
||||
/// One located replacement, reduced to the original-file lines it actually changes.
|
||||
///
|
||||
/// The span is what *differs*, not what the caller matched. A model routinely matches a whole block
|
||||
/// to change one line inside it, and measuring from the match spends the preview on lines that
|
||||
/// never moved — ahead of the three this module promises either side, so on a big enough match the
|
||||
/// change itself falls off the end of whatever is reading it.
|
||||
struct Change {
|
||||
/// Original-file lines being replaced, 0-based and half-open. Empty for a pure insertion.
|
||||
replaced: std::ops::Range<usize>,
|
||||
removed: Vec<String>,
|
||||
added: Vec<String>,
|
||||
}
|
||||
|
||||
/// Expand a byte-position replacement to the whole lines it touches, so a mid-line edit shows the
|
||||
/// full before/after line rather than a dangling fragment.
|
||||
fn change_at(original: &str, lines: &[&str], range: std::ops::Range<usize>, new: &str) -> Change {
|
||||
let position = range.start;
|
||||
let start_line = original[..position].matches('\n').count();
|
||||
let end_line = start_line + original[range.clone()].matches('\n').count();
|
||||
let line_start = original[..position].rfind('\n').map_or(0, |index| index + 1);
|
||||
let prefix = &original[line_start..position];
|
||||
let suffix_start = range.end;
|
||||
let suffix_end =
|
||||
original[suffix_start..].find('\n').map_or(original.len(), |index| suffix_start + index);
|
||||
let suffix = &original[suffix_start..suffix_end];
|
||||
|
||||
let removed: Vec<String> = lines[start_line..=end_line.min(lines.len().saturating_sub(1))]
|
||||
.iter()
|
||||
.map(|line| (*line).to_string())
|
||||
.collect();
|
||||
let added: Vec<String> =
|
||||
format!("{prefix}{new}{suffix}").split('\n').map(str::to_string).collect();
|
||||
trim_unchanged(start_line, removed, added)
|
||||
}
|
||||
|
||||
/// Reduces a matched replacement to the lines that differ, dropping the identical ends.
|
||||
///
|
||||
/// Appending one line to a three-line file by matching the whole file described three removals and
|
||||
/// four additions; trimming turns that back into one addition, which is both what happened and a
|
||||
/// fraction of the tokens, since the model reads this result back. The trimmed ends are not context
|
||||
/// rows either — they are ordinary file lines, and [`ranges_diff`] measures its context block from
|
||||
/// the span this leaves behind.
|
||||
fn trim_unchanged(start_line: usize, removed: Vec<String>, added: Vec<String>) -> Change {
|
||||
let lead = removed.iter().zip(&added).take_while(|(before, after)| before == after).count();
|
||||
let tail = removed[lead..]
|
||||
.iter()
|
||||
.rev()
|
||||
.zip(added[lead..].iter().rev())
|
||||
.take_while(|(before, after)| before == after)
|
||||
.count();
|
||||
Change {
|
||||
replaced: start_line + lead..start_line + removed.len() - tail,
|
||||
removed: removed[lead..removed.len() - tail].to_vec(),
|
||||
added: added[lead..added.len() - tail].to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Emits the lines that differ, numbered against the original file.
|
||||
fn push_change_rows(rows: &mut Vec<Row>, change: &Change) {
|
||||
let first = change.replaced.start + 1;
|
||||
for (offset, text) in change.removed.iter().enumerate() {
|
||||
rows.push(Row { sign: '-', number: Some(first + offset), text: text.clone() });
|
||||
}
|
||||
for (offset, text) in change.added.iter().enumerate() {
|
||||
rows.push(Row { sign: '+', number: Some(first + offset), text: text.clone() });
|
||||
}
|
||||
}
|
||||
|
||||
fn context_row(lines: &[&str], index: usize) -> Row {
|
||||
Row {
|
||||
sign: ' ',
|
||||
number: Some(index + 1),
|
||||
text: lines.get(index).copied().unwrap_or_default().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn elision() -> Row {
|
||||
Row { sign: ' ', number: None, text: "...".to_string() }
|
||||
}
|
||||
|
||||
/// Lay the rows out with a right-aligned line-number gutter.
|
||||
fn render(rows: &[Row]) -> String {
|
||||
let width = rows
|
||||
.iter()
|
||||
.filter_map(|row| row.number)
|
||||
.map(|number| number.to_string().len())
|
||||
.max()
|
||||
.unwrap_or(1);
|
||||
rows.iter()
|
||||
.map(|row| match row.number {
|
||||
Some(number) => format!("{}{number:>width$} {}", row.sign, row.text, width = width),
|
||||
None => format!("{}{:>width$} {}", row.sign, "", row.text, width = width),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
148
crates/luxe-tools/src/diff_preview/tests.rs
Normal file
148
crates/luxe-tools/src/diff_preview/tests.rs
Normal file
@@ -0,0 +1,148 @@
|
||||
use super::*;
|
||||
|
||||
/// Two versions of a file preview as the change between them, numbered against the first.
|
||||
#[test]
|
||||
fn two_versions_preview_as_one_change() {
|
||||
let before = "fn a() {}\nfn sub(a:i32)->i32{a}\nfn c() {}\n";
|
||||
let after = "fn a() {}\nfn sub(a: i32) -> i32 {\n a\n}\nfn c() {}\n";
|
||||
let shown = texts_diff(before, after);
|
||||
assert!(shown.contains("-2 fn sub(a:i32)->i32{a}"), "{shown}");
|
||||
assert!(shown.contains("+2 fn sub(a: i32) -> i32 {"), "{shown}");
|
||||
assert!(shown.contains("+4 }"), "{shown}");
|
||||
assert!(
|
||||
!shown.contains("-1") && !shown.contains("+1 "),
|
||||
"unchanged lines are context: {shown}"
|
||||
);
|
||||
// multibyte text on both sides of the change keeps the slices on char boundaries
|
||||
let shown = texts_diff("é→a←é", "é→b←é");
|
||||
assert!(shown.contains("-1 é→a←é") && shown.contains("+1 é→b←é"), "{shown}");
|
||||
assert_eq!(texts_diff("same\n", "same\n"), ranges_diff("same\n", &[(5..5, "")]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_shows_line_numbers_and_context_without_hunk_headers() {
|
||||
let original = "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight";
|
||||
let diff = edits_diff(original, &[("four", "FOUR")]);
|
||||
|
||||
assert!(!diff.contains("@@"), "no unified hunk headers: {diff}");
|
||||
assert!(diff.contains("-4 four"), "the removed line is numbered: {diff}");
|
||||
assert!(diff.contains("+4 FOUR"), "the added line is numbered: {diff}");
|
||||
assert!(diff.contains(" 3 three"), "context above: {diff}");
|
||||
assert!(diff.contains(" 5 five"), "context below: {diff}");
|
||||
assert!(diff.contains("..."), "the elided tail is marked: {diff}");
|
||||
assert!(!diff.contains("eight"), "far-away lines aren't shown: {diff}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_at_the_top_has_no_leading_elision() {
|
||||
let original = "alpha\nbeta\ngamma";
|
||||
let diff = edits_diff(original, &[("alpha", "ALPHA")]);
|
||||
assert!(diff.starts_with("-1 alpha"), "starts right at the change: {diff:?}");
|
||||
assert!(!diff.contains("..."), "everything else is context: {diff}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mid_line_edit_shows_the_whole_before_and_after_line() {
|
||||
let original = "fn main() {\n println!(\"old\");\n}";
|
||||
let diff = edits_diff(original, &[("\"old\"", "\"new\"")]);
|
||||
assert!(diff.contains("-2 println!(\"old\");"), "{diff}");
|
||||
assert!(diff.contains("+2 println!(\"new\");"), "{diff}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_line_and_multi_edit_changes_keep_their_positions() {
|
||||
let original = "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten";
|
||||
let diff = edits_diff(original, &[("two\nthree", "TWO"), ("nine", "NINE")]);
|
||||
// The gutter is two wide here (line 10 exists), so numbers are right-aligned into it.
|
||||
assert!(diff.contains("- 2 two"), "{diff}");
|
||||
assert!(diff.contains("- 3 three"), "{diff}");
|
||||
assert!(diff.contains("+ 2 TWO"), "{diff}");
|
||||
assert!(diff.contains("- 9 nine"), "{diff}");
|
||||
assert!(diff.contains("+ 9 NINE"), "{diff}");
|
||||
// These two changes are close enough that their context blocks meet, so nothing is elided.
|
||||
assert!(!diff.contains("..."), "adjacent context blocks merge: {diff}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_far_apart_pair_of_edits_elides_the_span_between_them() {
|
||||
let original = (1..=40).map(|n| format!("line {n}")).collect::<Vec<_>>().join("\n");
|
||||
let diff = edits_diff(&original, &[("line 5", "FIVE"), ("line 35", "THIRTY-FIVE")]);
|
||||
assert!(diff.matches("...").count() >= 3, "head, middle, and tail are elided: {diff}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gutter_is_wide_enough_for_the_largest_line_number() {
|
||||
let original = (1..=120).map(|n| format!("line {n}")).collect::<Vec<_>>().join("\n");
|
||||
let diff = edits_diff(&original, &[("line 100", "LINE 100")]);
|
||||
assert!(diff.contains("-100 line 100"), "{diff}");
|
||||
assert!(diff.contains(" 99 line 99"), "context aligns under it: {diff}");
|
||||
}
|
||||
|
||||
/// An append shows the appended line, not the whole matched block rewritten.
|
||||
///
|
||||
/// The model routinely matches a block it is only adding to; printing every unchanged line as
|
||||
/// a removal *and* an addition made a one-line append read like a rewrite, and the model reads
|
||||
/// this result back.
|
||||
#[test]
|
||||
fn an_insertion_shows_only_what_was_inserted() {
|
||||
let diff = edits_diff("keep this", &[("keep this", "keep this\nplus a line")]);
|
||||
assert!(diff.contains("+2 plus a line"), "the new line is an addition: {diff}");
|
||||
assert!(diff.contains(" 1 keep this"), "the untouched line is context: {diff}");
|
||||
assert!(!diff.contains("-1 keep this"), "and never a removal: {diff}");
|
||||
assert!(!diff.contains("\n-\n"), "no empty removal row: {diff:?}");
|
||||
}
|
||||
|
||||
/// The same, at the scale it was reported at: appending one line to a three-line file.
|
||||
#[test]
|
||||
fn appending_to_a_small_file_prints_one_added_row() {
|
||||
let original = "alpha\nbeta\ngamma\n";
|
||||
let diff = edits_diff(original, &[(original, "alpha\nbeta\ngamma\nzeta\n")]);
|
||||
let removals = diff.lines().filter(|line| line.starts_with('-')).count();
|
||||
let additions = diff.lines().filter(|line| line.starts_with('+')).count();
|
||||
assert_eq!(removals, 0, "nothing was removed: {diff}");
|
||||
assert_eq!(additions, 1, "exactly one line was added: {diff}");
|
||||
assert!(diff.contains("+4 zeta"), "{diff}");
|
||||
}
|
||||
|
||||
/// A model that matches a whole block to change one line in it gets a preview of the change.
|
||||
///
|
||||
/// The lines a match covers but does not touch are ordinary file lines: three of them either
|
||||
/// side, like any other context, and the rest elided. Printing all nine put the edit below the
|
||||
/// fold of every surface reading this — a collapsed tool card was ten rows of scenery — and
|
||||
/// charged the model for the scenery on the way past.
|
||||
#[test]
|
||||
fn a_big_match_around_a_small_change_previews_the_change_not_the_match() {
|
||||
let original = (1..=40).map(|n| format!("line {n}")).collect::<Vec<_>>().join("\n");
|
||||
let matched = (20..=32).map(|n| format!("line {n}")).collect::<Vec<_>>().join("\n");
|
||||
let replaced = matched.replace("line 30", "LINE 30");
|
||||
let diff = edits_diff(&original, &[(matched.as_str(), replaced.as_str())]);
|
||||
|
||||
let rows: Vec<&str> = diff.lines().collect();
|
||||
assert_eq!(rows[0].trim(), "...", "everything above the change is elided: {diff}");
|
||||
assert_eq!(rows[1], " 27 line 27", "three lines of context, no more: {diff}");
|
||||
assert_eq!(rows[4], "-30 line 30", "{diff}");
|
||||
assert_eq!(rows[5], "+30 LINE 30", "{diff}");
|
||||
assert_eq!(rows[8], " 33 line 33", "{diff}");
|
||||
assert_eq!(rows[9].trim(), "...", "and everything below it: {diff}");
|
||||
assert_eq!(rows.len(), 10, "nothing else earns a row: {diff}");
|
||||
assert!(!diff.contains("line 20"), "the head of the match is not scenery: {diff}");
|
||||
}
|
||||
|
||||
/// Two changes far apart keep their own context blocks, with the span between them elided.
|
||||
#[test]
|
||||
fn two_distant_changes_keep_their_own_context() {
|
||||
let original = (1..=60).map(|n| format!("line {n}")).collect::<Vec<_>>().join("\n");
|
||||
let diff = edits_diff(&original, &[("line 10", "TEN"), ("line 50", "FIFTY")]);
|
||||
|
||||
assert!(diff.contains("-10 line 10") && diff.contains("+10 TEN"), "{diff}");
|
||||
assert!(diff.contains("-50 line 50") && diff.contains("+50 FIFTY"), "{diff}");
|
||||
assert_eq!(diff.matches("...").count(), 3, "head, middle and tail: {diff}");
|
||||
assert!(!diff.contains("line 20"), "the span between them is not drawn: {diff}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn added_lines_numbers_every_line() {
|
||||
let out = added_lines("fn main() {}\n// note");
|
||||
assert!(out.contains("+1 fn main() {}"), "{out}");
|
||||
assert!(out.contains("+2 // note"), "{out}");
|
||||
}
|
||||
477
crates/luxe-tools/src/edit.rs
Normal file
477
crates/luxe-tools/src/edit.rs
Normal file
@@ -0,0 +1,477 @@
|
||||
//! `edit` tool — search/replace with a read guard, atomic multi-edit, and a tolerant edge.
|
||||
//!
|
||||
//! The tool is a UX for a model, and the model only ever sees the schema and the errors. Four
|
||||
//! things follow from that, and they are what this module is shaped around:
|
||||
//!
|
||||
//! - **The advertised spelling is `oldText`/`newText`**, and which spelling is advertised matters
|
||||
//! more than everything else here combined. See `args`.
|
||||
//! - **Argument dialects are accepted** (`args`). Rejecting `old_string` because the schema says
|
||||
//! `oldText` costs a turn and teaches nothing.
|
||||
//! - **Near misses are tolerated, and named** (`locate`). Whitespace and indentation are how a
|
||||
//! model's copy of a block differs from the file's; neither changes which code was meant. Every
|
||||
//! relaxation still demands a unique match.
|
||||
//! - **Failures are correctable from their own text**: what arrived, what was expected, and where
|
||||
//! the closest thing actually is.
|
||||
//!
|
||||
//! What stays strict: uniqueness (unless `replaceAll`), read-before-edit, staleness, and
|
||||
//! atomicity — all edits land or none do.
|
||||
|
||||
mod args;
|
||||
mod locate;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use luxe_core::read_tracker::{ReadStatus, ReadTracker};
|
||||
use luxe_core::tool::guards::{CHANGED_ON_DISK, READ_BEFORE_EDIT};
|
||||
use luxe_core::{ContentBlock, Tool, ToolContext, ToolResultData, ToolSchema};
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use args::{normalize, EditSpec};
|
||||
use locate::{line_of, locate, LocateError, MatchKind};
|
||||
|
||||
/// JSON-schema for the edit tool arguments.
|
||||
///
|
||||
/// Advertises exactly one spelling. The tolerated aliases are a recovery path, not a second
|
||||
/// contract — documenting them would invite their use and make every one of them permanent.
|
||||
fn edit_schema() -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: "edit".to_string(),
|
||||
description: "Edit a file by replacing exact text. Each edit's `oldText` must match a \
|
||||
UNIQUE region of the current file — include enough surrounding context to \
|
||||
disambiguate, or set `replaceAll` to change every occurrence. Multiple \
|
||||
edits apply atomically (all-or-nothing) and must not overlap. Trailing \
|
||||
whitespace and a uniformly shifted indent are tolerated and reported. You \
|
||||
must have seen the file in this Luxe run — with `read`, lines of it from \
|
||||
`grep`, or printed by `cat`, `sed -n` or a search in `bash` — and it must \
|
||||
not have changed \
|
||||
on disk since (read-before-edit + staleness guards); otherwise read it \
|
||||
again and retry. The `12: ` numbers `read` puts on each line are not part of \
|
||||
the file: leave them out of `oldText` and `newText`."
|
||||
.to_string(),
|
||||
parameters: json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Path to the file to edit (relative to cwd)"
|
||||
},
|
||||
"edits": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"oldText": {
|
||||
"type": "string",
|
||||
"description": "Exact text to find"
|
||||
},
|
||||
"newText": {
|
||||
"type": "string",
|
||||
"description": "Replacement text (empty string deletes)"
|
||||
},
|
||||
"replaceAll": {
|
||||
"type": "boolean",
|
||||
"description": "Replace every occurrence instead of requiring a unique match (default false)"
|
||||
}
|
||||
},
|
||||
"required": ["oldText", "newText"]
|
||||
},
|
||||
"description": "Array of edit operations to apply atomically"
|
||||
}
|
||||
},
|
||||
"required": ["path", "edits"]
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `edit` tool implementation.
|
||||
#[derive(Default)]
|
||||
pub struct EditTool {
|
||||
/// Shared read tracker enforcing read-before-edit + staleness (guards skipped when absent).
|
||||
tracker: Option<Arc<ReadTracker>>,
|
||||
}
|
||||
|
||||
impl EditTool {
|
||||
/// Create a new edit tool instance.
|
||||
pub fn new() -> Self {
|
||||
Self { tracker: None }
|
||||
}
|
||||
|
||||
/// Attach the shared read tracker so edits are gated on a prior, still-current read.
|
||||
pub fn with_tracker(mut self, tracker: Arc<ReadTracker>) -> Self {
|
||||
self.tracker = Some(tracker);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// One edit resolved against the file: where it lands, and what to write.
|
||||
struct Planned {
|
||||
ranges: Vec<std::ops::Range<usize>>,
|
||||
replacement: String,
|
||||
kind: MatchKind,
|
||||
}
|
||||
|
||||
/// Resolves every edit against `content`, or explains the first one that cannot be placed.
|
||||
///
|
||||
/// Every edit is located against the **original** text, so their uniqueness checks all describe
|
||||
/// the same file. Applying them is a separate step, and applies by offset in reverse — the
|
||||
/// previous implementation validated uniqueness up front and then ran `str::replace` in sequence,
|
||||
/// so an earlier edit whose replacement happened to contain a later edit's search text quietly
|
||||
/// changed both.
|
||||
fn plan(content: &str, edits: &[EditSpec]) -> Result<Vec<Planned>, String> {
|
||||
let mut planned: Vec<Planned> = Vec::with_capacity(edits.len());
|
||||
for (index, edit) in edits.iter().enumerate() {
|
||||
match locate(content, &edit.old_text, &edit.new_text, edit.replace_all) {
|
||||
Ok(found) if writes_back_what_is_there(content, &found.ranges, &found.replacement) => {
|
||||
return Err(format!(
|
||||
"Error: edit[{index}] would write back exactly the text it matched, so it \
|
||||
changes nothing. Check that `newText` really differs from `oldText` — an \
|
||||
escape or an invisible character surviving the round trip unchanged is the \
|
||||
usual cause, and so is an edit that was already applied. Nothing was written."
|
||||
))
|
||||
}
|
||||
Ok(found) => planned.push(Planned {
|
||||
ranges: found.ranges,
|
||||
replacement: found.replacement,
|
||||
kind: found.kind,
|
||||
}),
|
||||
Err(LocateError::NotFound { nearest }) => {
|
||||
let mut message = format!(
|
||||
"Error: edit[{index}] 'oldText' not found in the file. It must match the \
|
||||
current contents exactly (trailing whitespace and a uniform indent shift are \
|
||||
tolerated)."
|
||||
);
|
||||
if let Some(nearest) = nearest {
|
||||
message.push_str(&format!(
|
||||
"\nClosest match is line {}:\n have: {}\n want: {}",
|
||||
nearest.line,
|
||||
nearest.text.trim_end(),
|
||||
edit.old_text.lines().next().unwrap_or_default().trim_end()
|
||||
));
|
||||
}
|
||||
message.push_str("\nNothing was written. Re-read the file and retry.");
|
||||
return Err(message);
|
||||
}
|
||||
Err(LocateError::Ambiguous { lines }) => {
|
||||
let places = lines.iter().map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(format!(
|
||||
"Error: edit[{index}] 'oldText' matched {} times (lines {places}). Add \
|
||||
surrounding context to make it unique, or set `replaceAll: true` to change \
|
||||
every occurrence. Nothing was written.",
|
||||
lines.len()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(clash) = overlap(&planned) {
|
||||
return Err(clash);
|
||||
}
|
||||
Ok(planned)
|
||||
}
|
||||
|
||||
/// The edits again with `read`'s `12: ` line numbers taken off, planned, when that is unmistakably
|
||||
/// what went wrong.
|
||||
///
|
||||
/// A model copies the numbered lines `read` returned straight into `oldText` often enough to be
|
||||
/// worth catching, and the alternative is a refusal it has to puzzle out. Strict on purpose, so it
|
||||
/// can never change what an edit means: it runs only when the edits failed as written, only on an
|
||||
/// `oldText` whose every line carries a number counting up by one, and the result stands only if
|
||||
/// each stripped edit is found at exactly the line its first number names.
|
||||
fn plan_without_read_numbers(content: &str, edits: &[EditSpec]) -> Option<Vec<Planned>> {
|
||||
let mut stripped = Vec::with_capacity(edits.len());
|
||||
let mut expected_lines = Vec::with_capacity(edits.len());
|
||||
let mut any = false;
|
||||
for edit in edits {
|
||||
match strip_read_numbers(&edit.old_text, true) {
|
||||
Some((first, old_text)) if !edit.replace_all => {
|
||||
let new_text = strip_read_numbers(&edit.new_text, false)
|
||||
.map_or_else(|| edit.new_text.clone(), |(_, text)| text);
|
||||
stripped.push(EditSpec { old_text, new_text, replace_all: false });
|
||||
expected_lines.push(Some(first));
|
||||
any = true;
|
||||
}
|
||||
_ => {
|
||||
stripped.push(edit.clone());
|
||||
expected_lines.push(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !any {
|
||||
return None;
|
||||
}
|
||||
let planned = plan(content, &stripped).ok()?;
|
||||
let lands_where_numbered = planned.iter().zip(&expected_lines).all(|(plan, expected)| {
|
||||
expected.is_none_or(|line| {
|
||||
plan.ranges.first().is_some_and(|range| line_of(content, range.start) == line)
|
||||
})
|
||||
});
|
||||
lands_where_numbered.then_some(planned)
|
||||
}
|
||||
|
||||
/// `text` without a `12: ` prefix on each line, and the first line's number, when every line has
|
||||
/// one. `consecutive` also requires the numbers to count up by one, as `read` writes them.
|
||||
fn strip_read_numbers(text: &str, consecutive: bool) -> Option<(usize, String)> {
|
||||
let (body, trailing_newline) = match text.strip_suffix('\n') {
|
||||
Some(body) => (body, true),
|
||||
None => (text, false),
|
||||
};
|
||||
let mut first = None;
|
||||
let mut lines = Vec::new();
|
||||
for (index, line) in body.split('\n').enumerate() {
|
||||
let (number, rest) = line.split_once(':')?;
|
||||
if number.is_empty() || !number.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let number: usize = number.parse().ok()?;
|
||||
let first_number = *first.get_or_insert(number);
|
||||
if consecutive && number != first_number + index {
|
||||
return None;
|
||||
}
|
||||
// `read` writes `N: text`, and an empty line as `N: `, which a model may trim to `N:`
|
||||
lines.push(rest.strip_prefix(' ').unwrap_or(rest));
|
||||
}
|
||||
let mut out = lines.join("\n");
|
||||
if trailing_newline {
|
||||
out.push('\n');
|
||||
}
|
||||
Some((first?, out))
|
||||
}
|
||||
|
||||
/// Whether every place this edit lands already holds exactly what it would write.
|
||||
///
|
||||
/// Compared against the file's own bytes rather than `oldText` against `newText`, because the two
|
||||
/// are not the same question: a relaxed match re-indents the replacement, and line endings are
|
||||
/// normalized on both sides before this runs, so an edit can arrive looking like a change and
|
||||
/// resolve to none. What matters is whether the file moves.
|
||||
fn writes_back_what_is_there(
|
||||
content: &str,
|
||||
ranges: &[std::ops::Range<usize>],
|
||||
replacement: &str,
|
||||
) -> bool {
|
||||
ranges.iter().all(|range| content.get(range.clone()) == Some(replacement))
|
||||
}
|
||||
|
||||
/// The first pair of edits that would write over each other, as an error.
|
||||
fn overlap(planned: &[Planned]) -> Option<String> {
|
||||
let mut spans: Vec<(usize, std::ops::Range<usize>)> = planned
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(index, plan)| plan.ranges.iter().cloned().map(move |range| (index, range)))
|
||||
.collect();
|
||||
spans.sort_by_key(|(_, range)| range.start);
|
||||
spans.windows(2).find_map(|pair| {
|
||||
let ((left, first), (right, second)) = (&pair[0], &pair[1]);
|
||||
(first.end > second.start).then(|| {
|
||||
format!(
|
||||
"Error: edit[{left}] and edit[{right}] cover the same text, so applying both \
|
||||
would corrupt it. Nothing was written — split them or widen one so they \
|
||||
do not overlap."
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies planned edits by byte offset, last first, so earlier offsets stay valid.
|
||||
fn apply(content: &str, planned: &[Planned]) -> String {
|
||||
let mut spans: Vec<(&std::ops::Range<usize>, &str)> = planned
|
||||
.iter()
|
||||
.flat_map(|plan| plan.ranges.iter().map(move |range| (range, plan.replacement.as_str())))
|
||||
.collect();
|
||||
spans.sort_by_key(|(range, _)| std::cmp::Reverse(range.start));
|
||||
let mut result = content.to_string();
|
||||
for (range, replacement) in spans {
|
||||
result.replace_range(range.clone(), replacement);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
impl EditTool {
|
||||
/// Read-before-edit and the staleness guard, when a tracker is wired.
|
||||
///
|
||||
/// Recoverable by design: the model reads (or re-reads) the file and retries.
|
||||
fn check_read_guard(
|
||||
&self,
|
||||
cx: &ToolContext,
|
||||
full_path: &Path,
|
||||
shown: &str,
|
||||
) -> Result<(), ToolResultData> {
|
||||
let Some(tracker) = &self.tracker else { return Ok(()) };
|
||||
match tracker.status(&cx.session_id, full_path) {
|
||||
ReadStatus::Unseen => Err(ToolResultData::error(format!(
|
||||
"Error: no read of '{shown}' is on record for this Luxe run \
|
||||
({READ_BEFORE_EDIT}). The record is per process, so a resumed \
|
||||
session starts empty even where the transcript shows an earlier read. \
|
||||
Use the `read` tool, then retry — nothing was written."
|
||||
))),
|
||||
ReadStatus::Stale => Err(ToolResultData::error(format!(
|
||||
"Error: '{shown}' {CHANGED_ON_DISK} you last read it (a formatter, \
|
||||
another tool, or an external edit). Re-read it, then retry the edit — \
|
||||
nothing was written."
|
||||
))),
|
||||
ReadStatus::Current => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the edit says it did: the count, any tolerated matches, and what the model should know
|
||||
/// before its next edit.
|
||||
fn render_summary(
|
||||
planned: &[Planned],
|
||||
content: &str,
|
||||
shown_path: String,
|
||||
reformatted: bool,
|
||||
unnumbered: bool,
|
||||
) -> String {
|
||||
let occurrences: usize = planned.iter().map(|plan| plan.ranges.len()).sum();
|
||||
let mut summary = format!(
|
||||
"Applied {} edit(s){} to '{shown_path}'",
|
||||
planned.len(),
|
||||
match occurrences.saturating_sub(planned.len()) {
|
||||
0 => String::new(),
|
||||
extra => format!(" ({extra} extra occurrence(s) via replaceAll)"),
|
||||
},
|
||||
);
|
||||
if reformatted {
|
||||
summary.push_str(
|
||||
"\n Format-on-save then reformatted the file; the diff shows it as it is now.",
|
||||
);
|
||||
}
|
||||
// A tolerated match is never a silent one: the model asked for text that is not what is
|
||||
// in the file, and it needs to know which of the two the next edit should be based on.
|
||||
for (index, plan) in planned.iter().enumerate() {
|
||||
if let Some(note) = plan.kind.note() {
|
||||
let line = plan.ranges.first().map_or(0, |range| line_of(content, range.start));
|
||||
summary.push_str(&format!("\n edit[{index}] at line {line}: {note}"));
|
||||
}
|
||||
}
|
||||
if unnumbered {
|
||||
summary.push_str(
|
||||
"\n The `12: ` line numbers `read` shows were left out: they are not part of the \
|
||||
file, so leave them out of the next edit.",
|
||||
);
|
||||
}
|
||||
summary
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for EditTool {
|
||||
fn name(&self) -> &str {
|
||||
"edit"
|
||||
}
|
||||
|
||||
fn argument_aliases(&self) -> &'static [&'static str] {
|
||||
&args::ALIASES
|
||||
}
|
||||
|
||||
fn schema(&self) -> ToolSchema {
|
||||
edit_schema()
|
||||
}
|
||||
|
||||
async fn run(&self, arguments: serde_json::Value, cx: &ToolContext) -> ToolResultData {
|
||||
let request = match normalize(&arguments) {
|
||||
Ok(request) => request,
|
||||
Err(problem) => return ToolResultData::error(problem.message()),
|
||||
};
|
||||
|
||||
let full_path = cx.cwd.join(&request.path);
|
||||
|
||||
if let Err(refusal) = self.check_read_guard(cx, &full_path, &request.path) {
|
||||
return refusal;
|
||||
}
|
||||
|
||||
debug!(path = %full_path.display(), edits = request.edits.len(), "editing file");
|
||||
|
||||
let content = match std::fs::read_to_string(&full_path) {
|
||||
Ok(content) => content,
|
||||
Err(problem) => {
|
||||
warn!(path = %full_path.display(), error = %problem, "failed to read file for edit");
|
||||
return ToolResultData::error(format!(
|
||||
"Error reading file '{}': {problem}",
|
||||
luxe_core::paths::display(&full_path)
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
// Speak the file's line endings on both sides. The whole-line relaxation trims a stray `\r`
|
||||
// and would match a CRLF checkout anyway, then write LF back — the edited lines become the
|
||||
// only LF lines in the file and git reports the whole thing as changed.
|
||||
let ending = crate::line_endings::detect(&content);
|
||||
let edits: Vec<EditSpec> = request
|
||||
.edits
|
||||
.iter()
|
||||
.map(|edit| EditSpec {
|
||||
old_text: crate::line_endings::normalize(&edit.old_text, ending),
|
||||
new_text: crate::line_endings::normalize(&edit.new_text, ending),
|
||||
replace_all: edit.replace_all,
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Plan everything against the original text before writing anything: atomicity is the
|
||||
// promise that a rejected call leaves the file exactly as the model last read it.
|
||||
let (planned, unnumbered) = match plan(&content, &edits) {
|
||||
Ok(planned) => (planned, false),
|
||||
Err(message) => match plan_without_read_numbers(&content, &edits) {
|
||||
Some(planned) => (planned, true),
|
||||
None => return ToolResultData::error(message),
|
||||
},
|
||||
};
|
||||
// Previewed from the resolved ranges, not by re-finding the search text: a tolerated
|
||||
// match is not a substring of the file, and a `replaceAll` has several homes. Built
|
||||
// against the pre-edit content, so the line numbers match the file the model read.
|
||||
let preview: Vec<(std::ops::Range<usize>, &str)> = planned
|
||||
.iter()
|
||||
.flat_map(|plan| {
|
||||
plan.ranges.iter().map(move |range| (range.clone(), plan.replacement.as_str()))
|
||||
})
|
||||
.collect();
|
||||
let diff = crate::diff_preview::ranges_diff(&content, &preview);
|
||||
let result = apply(&content, &planned);
|
||||
|
||||
if let Err(problem) = luxe_core::fs_atomic::replace(&full_path, result.as_bytes()) {
|
||||
warn!(path = %full_path.display(), error = %problem, "failed to write edited file");
|
||||
return ToolResultData::error(format!(
|
||||
"Error writing file '{}': {problem}",
|
||||
luxe_core::paths::display(&full_path)
|
||||
));
|
||||
}
|
||||
debug!(path = %full_path.display(), edits = planned.len(), "file edited successfully");
|
||||
|
||||
// format-on-save and diagnostics run here, before the fingerprint below
|
||||
let injected = cx.file_changed(&full_path, "edit").await;
|
||||
|
||||
// Format-on-save may have rewritten what was just written, and the next edit is matched
|
||||
// against the file, not against the call: preview what is there now
|
||||
let formatted = std::fs::read_to_string(&full_path).ok().filter(|now| *now != result);
|
||||
let diff = match &formatted {
|
||||
Some(now) => crate::diff_preview::texts_diff(&content, now),
|
||||
None => diff,
|
||||
};
|
||||
|
||||
// Refresh the fingerprint AFTER format-on-save so a follow-up edit to the same file
|
||||
// doesn't false-trip the staleness guard on the formatter's own change.
|
||||
if let Some(tracker) = &self.tracker {
|
||||
tracker.record(&cx.session_id, &full_path);
|
||||
}
|
||||
|
||||
let summary = render_summary(
|
||||
&planned,
|
||||
&content,
|
||||
luxe_core::paths::display(full_path.strip_prefix(&cx.cwd).unwrap_or(&full_path)),
|
||||
formatted.is_some(),
|
||||
unnumbered,
|
||||
);
|
||||
|
||||
let mut blocks = vec![ContentBlock::Text(format!("{summary}\n\n{diff}"))];
|
||||
if let Some(context) = injected {
|
||||
blocks.push(ContentBlock::Text(format!("\n--- Diagnostics ---\n{context}")));
|
||||
}
|
||||
ToolResultData { content: blocks, is_error: false }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod ergonomics_tests;
|
||||
386
crates/luxe-tools/src/edit/args.rs
Normal file
386
crates/luxe-tools/src/edit/args.rs
Normal file
@@ -0,0 +1,386 @@
|
||||
//! Argument normalization for `edit` — permissive at the edge, strict in the core.
|
||||
//!
|
||||
//! The tool's real invariants are uniqueness, atomicity and the read guard. The *spelling* of its
|
||||
//! arguments is not one of them, and enforcing it costs a turn every time: Claude Code trained a
|
||||
//! generation of models on `file_path`/`old_string`/`new_string`, OpenCode on
|
||||
//! `filePath`/`oldString`/`newString`, and rejecting either teaches nothing, because the reply that
|
||||
//! comes back is a retry, not a correction. So: accept the dialects, normalize once, then be strict
|
||||
//! about what actually matters. The schema still advertises exactly one spelling, so nothing here
|
||||
//! is a second contract to keep.
|
||||
//!
|
||||
//! # Why the advertised spelling is `oldText`, not `old_text`
|
||||
//!
|
||||
//! Advertised as `old_text`/`new_text`, a large share of Sonnet's edit calls arrive with `edits` as
|
||||
//! a mangled *string* beginning `[{"new_text">`: a separator emitted as `">` instead of `": "`
|
||||
//! right after a key ending in `_text`, and nowhere else. The camelCase spelling all but removes
|
||||
//! it. The provider's tolerant JSON finalizer then cannot parse the array, so it stringifies it up
|
||||
//! to the point it can resync and *promotes the surviving object members into the outer arguments
|
||||
//! object*: `{"edits": "[{\"new_text\">…", "old_text": "…", "path": "…"}`, one field swallowed,
|
||||
//! its sibling hoisted, and `path` present only when the model happened to emit it first.
|
||||
//!
|
||||
//! So the aliases below are a *recovery* path, not a fix: the corruption happens before any of
|
||||
//! this code runs. The error messages speak the advertised spelling, because they are what
|
||||
//! re-primes the format, and a call after a clean one is far likelier to garble than the retry
|
||||
//! after a refusal. And every failure quotes what arrived: a model sees only the arguments it meant
|
||||
//! to send, so an error naming keys is useless once the *value* is what went wrong.
|
||||
//!
|
||||
//! # The one garble that is read rather than refused
|
||||
//!
|
||||
//! `oldText` is not immune. claude-sonnet-5-5 and claude-haiku-5-5 emit `[{"oldText">` too, and
|
||||
//! with Anthropic validating the arguments the result is always the same shape: `edits` is the
|
||||
//! string `[{"oldText">` followed by the search text, whole, and `newText` is hoisted beside it,
|
||||
//! whole, and retrying mostly reproduces it. Both halves arrive intact, so [`recover_hoisted`]
|
||||
//! reads that one shape as the single edit it was, and nothing else: anything missing either half
|
||||
//! is still refused. It writes no guess, since the search text must still match the file exactly
|
||||
//! and only once.
|
||||
//!
|
||||
//! Two rarer forms of the same slip come back whole too, and are read the same way: the opener
|
||||
//! written as the model's own `<parameter name="oldText">`, and the whole array kept inside the
|
||||
//! string with only the separators garbled ([`repair_separators`]).
|
||||
|
||||
use serde_json::Value;
|
||||
use std::borrow::Cow;
|
||||
|
||||
/// One normalized replacement.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct EditSpec {
|
||||
/// Text to find.
|
||||
pub(crate) old_text: String,
|
||||
/// Text to put in its place.
|
||||
pub(crate) new_text: String,
|
||||
/// Replace every occurrence rather than requiring exactly one.
|
||||
pub(crate) replace_all: bool,
|
||||
}
|
||||
|
||||
/// A normalized `edit` call.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct EditRequest {
|
||||
/// File to edit, as given.
|
||||
pub(crate) path: String,
|
||||
/// Replacements, in call order.
|
||||
pub(crate) edits: Vec<EditSpec>,
|
||||
}
|
||||
|
||||
/// Why a call could not be understood, with enough detail to fix it in one move.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum ArgsError {
|
||||
/// No recognizable path key.
|
||||
MissingPath { received: Vec<String> },
|
||||
/// No recognizable edits, and no single top-level edit either.
|
||||
MissingEdits { received: Vec<String> },
|
||||
/// `edits` was present but empty.
|
||||
EmptyEdits,
|
||||
/// `edits` arrived as something no edit can be read out of.
|
||||
///
|
||||
/// Args: `(key as spelled, JSON type that arrived, head of the value)`.
|
||||
UnusableEdits { key: &'static str, found: &'static str, excerpt: String },
|
||||
/// One edit lacked a find or replace value. `index` is `None` for a top-level single edit.
|
||||
EditField { index: Option<usize>, field: &'static str, received: Vec<String> },
|
||||
}
|
||||
|
||||
impl ArgsError {
|
||||
/// A message that names what arrived, what was expected, and the shape to send.
|
||||
pub(super) fn message(&self) -> String {
|
||||
match self {
|
||||
Self::MissingPath { received } => format!(
|
||||
"Error: no file path. Received keys: {}. Use `path` (aliases: `file_path`, \
|
||||
`filePath`, `file`).\n{USAGE}",
|
||||
render_keys(received)
|
||||
),
|
||||
Self::MissingEdits { received } => format!(
|
||||
"Error: no edits. Received keys: {}. Pass `edits` as an array of \
|
||||
{{oldText, newText}}, or a single `oldText`/`newText` pair at the top \
|
||||
level.\n{USAGE}",
|
||||
render_keys(received)
|
||||
),
|
||||
Self::EmptyEdits => {
|
||||
format!("Error: `edits` was empty — there is nothing to apply.\n{USAGE}")
|
||||
}
|
||||
Self::UnusableEdits { key, found, excerpt } => format!(
|
||||
"Error: `{key}` arrived as {found}, not an array of {{oldText, newText}}, so no \
|
||||
edit could be read out of it. It begins:\n {excerpt}\nSend `{key}` as a real \
|
||||
JSON array — a quoted one is accepted only when the whole array parses. Nothing \
|
||||
was written.\n{USAGE}"
|
||||
),
|
||||
Self::EditField { index: Some(index), field, received } => format!(
|
||||
"Error: edit[{index}] has no `{field}`. Received keys: {}.\n{USAGE}",
|
||||
render_keys(received)
|
||||
),
|
||||
// Named apart from the indexed case because the two are corrected differently, and a
|
||||
// model told `edit[0]` is missing a field it can see at the top level starts guessing
|
||||
// at key order instead.
|
||||
Self::EditField { index: None, field, received } => format!(
|
||||
"Error: this call passed one edit at the top level rather than an `edits` array, \
|
||||
and it has no `{field}`. Received keys: {}.\n{USAGE}",
|
||||
render_keys(received)
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The canonical shape, repeated on every failure so a correction needs no second look.
|
||||
///
|
||||
/// This string is not decoration. It is the demonstration that re-primes the format for the next
|
||||
/// turn, so it has to spell every field the way [`super::edit_schema`] advertises it;
|
||||
/// `the_shape_a_refusal_shows_is_the_shape_the_schema_asks_for` holds the two together.
|
||||
const USAGE: &str = "Expected: {\"path\": \"src/lib.rs\", \"edits\": [{\"oldText\": \"…\", \
|
||||
\"newText\": \"…\", \"replaceAll\": false}]}";
|
||||
|
||||
/// Keys accepted for the file path, canonical first.
|
||||
const PATH_KEYS: [&str; 4] = ["path", "file_path", "filePath", "file"];
|
||||
/// Keys accepted for the text being replaced, canonical first.
|
||||
const OLD_KEYS: [&str; 6] = ["oldText", "old_text", "old_string", "oldString", "old", "search"];
|
||||
/// Keys accepted for the replacement text, canonical first.
|
||||
const NEW_KEYS: [&str; 6] = ["newText", "new_text", "new_string", "newString", "new", "replace"];
|
||||
/// Keys accepted for the replace-every-occurrence flag, canonical first.
|
||||
const ALL_KEYS: [&str; 3] = ["replaceAll", "replace_all", "all"];
|
||||
/// Keys accepted for the list of edits.
|
||||
const EDITS_KEYS: [&str; 3] = ["edits", "replacements", "changes"];
|
||||
|
||||
/// Every spelling [`normalize`] reads, for [`luxe_core::Tool::argument_aliases`].
|
||||
pub(super) const ALIASES: [&str; 22] = [
|
||||
"path",
|
||||
"file_path",
|
||||
"filePath",
|
||||
"file",
|
||||
"oldText",
|
||||
"old_text",
|
||||
"old_string",
|
||||
"oldString",
|
||||
"old",
|
||||
"search",
|
||||
"newText",
|
||||
"new_text",
|
||||
"new_string",
|
||||
"newString",
|
||||
"new",
|
||||
"replace",
|
||||
"replaceAll",
|
||||
"replace_all",
|
||||
"all",
|
||||
"edits",
|
||||
"replacements",
|
||||
"changes",
|
||||
];
|
||||
|
||||
/// Normalizes whatever dialect arrived into one [`EditRequest`].
|
||||
pub(crate) fn normalize(args: &Value) -> Result<EditRequest, ArgsError> {
|
||||
let keys = keys_of(args);
|
||||
let path = first_string(args, &PATH_KEYS)
|
||||
.ok_or_else(|| ArgsError::MissingPath { received: keys.clone() })?;
|
||||
if let Some(edit) = recover_hoisted(args) {
|
||||
return Ok(EditRequest { path, edits: vec![edit] });
|
||||
}
|
||||
|
||||
// `edits` as an array is the documented shape; a lone object is the same call with one edit,
|
||||
// and a top-level `oldText`/`newText` pair is how a single-edit tool would have been called.
|
||||
let listed = listed_edits(args)?;
|
||||
let flat = OLD_KEYS.iter().any(|key| args.get(*key).is_some());
|
||||
|
||||
// Paired with the array index the entry came from. `None` marks the pair passed at the top
|
||||
// level, which is corrected differently and so is never reported as `edit[n]`.
|
||||
let mut entries: Vec<(Option<usize>, &Value)> = match listed.as_deref() {
|
||||
Some(Value::Array(items)) => {
|
||||
items.iter().enumerate().map(|(at, e)| (Some(at), e)).collect()
|
||||
}
|
||||
Some(object) => vec![(Some(0), object)],
|
||||
None if flat => vec![(None, args)],
|
||||
// The key was there and carried nothing. Saying "no edits" while listing `edits` among the
|
||||
// keys received is the kind of contradiction a model argues with instead of fixing.
|
||||
None if EDITS_KEYS.iter().any(|key| args.get(*key).is_some()) => {
|
||||
return Err(ArgsError::EmptyEdits)
|
||||
}
|
||||
None => return Err(ArgsError::MissingEdits { received: keys }),
|
||||
};
|
||||
// A pair at the top level *beside* a usable array is one more edit, not a restatement of one.
|
||||
// Ignoring it applied fewer edits than were asked for and reported success anyway, which is
|
||||
// the one outcome worse than a refusal. Appending is safe because two edits over the same
|
||||
// text is exactly what `super::plan`'s overlap check exists to catch.
|
||||
if listed.is_some() && flat {
|
||||
entries.push((None, args));
|
||||
}
|
||||
if entries.is_empty() {
|
||||
return Err(ArgsError::EmptyEdits);
|
||||
}
|
||||
|
||||
let mut edits = Vec::with_capacity(entries.len());
|
||||
for (at, entry) in entries {
|
||||
let received = keys_of(entry);
|
||||
let old_text = first_string(entry, &OLD_KEYS).ok_or(ArgsError::EditField {
|
||||
index: at,
|
||||
field: "oldText",
|
||||
received: received.clone(),
|
||||
})?;
|
||||
// An empty replacement is a deletion, so `newText: ""` is legitimate — but a *missing*
|
||||
// one is a truncated call, and applying it would silently delete the match.
|
||||
let new_text = first_string_allowing_empty(entry, &NEW_KEYS)
|
||||
.ok_or(ArgsError::EditField { index: at, field: "newText", received })?;
|
||||
let replace_all = ALL_KEYS
|
||||
.iter()
|
||||
.find_map(|key| entry.get(*key))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
edits.push(EditSpec { old_text, new_text, replace_all });
|
||||
}
|
||||
Ok(EditRequest { path, edits })
|
||||
}
|
||||
|
||||
/// The `edits` value as JSON, recovering the quoted form and refusing the rest *by name*.
|
||||
///
|
||||
/// The refusal is load-bearing rather than pedantic: the mangled string this rejects arrives with
|
||||
/// its sibling field hoisted beside it (see the module docs), and a partial reconstruction would
|
||||
/// write a guess at the replacement into a real file.
|
||||
///
|
||||
/// A JSON-encoded string is not a dialect — it is the documented array with one accidental layer of
|
||||
/// quoting, which every model produces eventually, so it is unwrapped and used. Anything else is
|
||||
/// refused here rather than left to fall through to the single-edit path, which would read the
|
||||
/// *whole call* as `edit[0]` and report a field missing from it: true, and useless while the
|
||||
/// corruption sits in `edits`.
|
||||
///
|
||||
/// A garbled string is read only where nothing has to be guessed: a whole array with garbled
|
||||
/// separators ([`repair_separators`]), and the hoisted shape, read before this runs
|
||||
/// ([`recover_hoisted`]). Anything else would write a guess at the caller's meaning into a file.
|
||||
fn listed_edits(args: &Value) -> Result<Option<Cow<'_, Value>>, ArgsError> {
|
||||
let Some((key, value)) = EDITS_KEYS.iter().find_map(|key| args.get(*key).map(|v| (*key, v)))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
match value {
|
||||
Value::Array(_) | Value::Object(_) => Ok(Some(Cow::Borrowed(value))),
|
||||
// Absent in all but spelling.
|
||||
Value::Null => Ok(None),
|
||||
Value::String(text) if text.trim().is_empty() => Ok(None),
|
||||
Value::String(text) => match serde_json::from_str::<Value>(text.trim()) {
|
||||
Ok(parsed @ (Value::Array(_) | Value::Object(_))) => Ok(Some(Cow::Owned(parsed))),
|
||||
_ => match repair_separators(text) {
|
||||
Some(parsed) => Ok(Some(Cow::Owned(parsed))),
|
||||
None => {
|
||||
Err(ArgsError::UnusableEdits { key, found: "a string", excerpt: excerpt(text) })
|
||||
}
|
||||
},
|
||||
},
|
||||
other => Err(ArgsError::UnusableEdits {
|
||||
key,
|
||||
found: json_kind(other),
|
||||
excerpt: excerpt(&other.to_string()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The single edit inside the provider's mangling of `[{"oldText">…`, or `None` for anything else.
|
||||
///
|
||||
/// The shape is exact: `edits` a string opening with a search key and `">`, the rest of it the
|
||||
/// search text, and the replacement under its own key at the top level. The mirror image, with the
|
||||
/// replacement swallowed and the search text hoisted, is read the same way.
|
||||
fn recover_hoisted(args: &Value) -> Option<EditSpec> {
|
||||
let garbled = EDITS_KEYS.iter().find_map(|key| args.get(*key)).and_then(Value::as_str)?;
|
||||
let (key, swallowed) = garbled_opener(garbled)?;
|
||||
let (old_text, new_text) = if OLD_KEYS.contains(&key) {
|
||||
(swallowed.to_string(), first_string_allowing_empty(args, &NEW_KEYS)?)
|
||||
} else if NEW_KEYS.contains(&key) {
|
||||
(first_string(args, &OLD_KEYS)?, swallowed.to_string())
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
// An empty search would match everywhere, the same rule `normalize` holds
|
||||
(!old_text.is_empty()).then(|| EditSpec {
|
||||
old_text,
|
||||
new_text,
|
||||
replace_all: ALL_KEYS
|
||||
.iter()
|
||||
.find_map(|key| args.get(*key))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false),
|
||||
})
|
||||
}
|
||||
|
||||
/// The key a garbled `edits` string opens with and everything after it: `[{"oldText">…` or the
|
||||
/// model's own `<parameter name="oldText">…`.
|
||||
fn garbled_opener(garbled: &str) -> Option<(&str, &str)> {
|
||||
let start = garbled.trim_start();
|
||||
if let Some(tagged) = start.strip_prefix("<parameter name=\"") {
|
||||
return tagged.split_once("\">");
|
||||
}
|
||||
let opened = start.strip_prefix('[').unwrap_or(start);
|
||||
opened.trim_start().strip_prefix('{')?.trim_start().strip_prefix('"')?.split_once("\">")
|
||||
}
|
||||
|
||||
/// A JSON array or object kept whole inside an `edits` string, its separators written as `">`
|
||||
/// after a search or replacement key, read with those separators put back.
|
||||
///
|
||||
/// Only the separator right after one of those keys is touched, and the result must then parse as
|
||||
/// JSON, so anything else garbled is still refused. Raw line breaks inside the strings are escaped
|
||||
/// first, because the same slip writes them unescaped.
|
||||
fn repair_separators(text: &str) -> Option<Value> {
|
||||
let mut repaired = text.replace('\n', "\\n").replace('\t', "\\t");
|
||||
let mut touched = false;
|
||||
for key in OLD_KEYS.iter().chain(NEW_KEYS.iter()) {
|
||||
let garbled = format!("\"{key}\">");
|
||||
if repaired.contains(&garbled) {
|
||||
repaired = repaired.replace(&garbled, &format!("\"{key}\":\""));
|
||||
touched = true;
|
||||
}
|
||||
}
|
||||
let parsed = serde_json::from_str::<Value>(repaired.trim()).ok().filter(|_| touched)?;
|
||||
matches!(parsed, Value::Array(_) | Value::Object(_)).then_some(parsed)
|
||||
}
|
||||
|
||||
/// The JSON type that arrived, spelled the way an error message wants to read.
|
||||
fn json_kind(value: &Value) -> &'static str {
|
||||
match value {
|
||||
Value::Null => "null",
|
||||
Value::Bool(_) => "a boolean",
|
||||
Value::Number(_) => "a number",
|
||||
Value::String(_) => "a string",
|
||||
Value::Array(_) => "an array",
|
||||
Value::Object(_) => "an object",
|
||||
}
|
||||
}
|
||||
|
||||
/// The head of a value that could not be used, as one line.
|
||||
///
|
||||
/// The load-bearing part of an unusable-value error: the sender is working from what it *meant* to
|
||||
/// send, so the only thing that ends the retry loop is seeing the corruption itself.
|
||||
fn excerpt(text: &str) -> String {
|
||||
const MAX_CHARS: usize = 80;
|
||||
let trimmed = text.trim_start();
|
||||
let first_line = trimmed.lines().next().unwrap_or_default();
|
||||
let mut head: String = first_line.chars().take(MAX_CHARS).collect();
|
||||
if head.len() < trimmed.len() {
|
||||
head.push('…');
|
||||
}
|
||||
head
|
||||
}
|
||||
|
||||
fn keys_of(value: &Value) -> Vec<String> {
|
||||
value.as_object().map(|map| map.keys().cloned().collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn render_keys(keys: &[String]) -> String {
|
||||
if keys.is_empty() {
|
||||
return "(none)".to_string();
|
||||
}
|
||||
keys.join(", ")
|
||||
}
|
||||
|
||||
/// The first alias present and non-empty.
|
||||
///
|
||||
/// The non-empty part is load-bearing for `oldText`, and not merely tidiness: an empty needle
|
||||
/// matches at *every* byte boundary in the file (`"abc".match_indices("")` yields four hits), so an
|
||||
/// edit that reached [`crate::edit::locate`] with one and `replaceAll` set would interleave the
|
||||
/// replacement between every character and write back a file orders of magnitude larger than the
|
||||
/// one it read. Rejecting it here as a missing field is what keeps that unreachable.
|
||||
fn first_string(value: &Value, keys: &[&str]) -> Option<String> {
|
||||
keys.iter()
|
||||
.find_map(|key| value.get(*key).and_then(Value::as_str))
|
||||
.filter(|text| !text.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
/// The first alias present, empty string included.
|
||||
fn first_string_allowing_empty(value: &Value, keys: &[&str]) -> Option<String> {
|
||||
keys.iter().find_map(|key| value.get(*key).and_then(Value::as_str)).map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
338
crates/luxe-tools/src/edit/args/tests.rs
Normal file
338
crates/luxe-tools/src/edit/args/tests.rs
Normal file
@@ -0,0 +1,338 @@
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
/// The shapes the major harnesses trained models on all arrive here eventually.
|
||||
#[test]
|
||||
fn every_dialect_normalizes_to_the_same_request() {
|
||||
let luxe = json!({"path": "a.rs", "edits": [{"oldText": "x", "newText": "y"}]});
|
||||
let claude_code =
|
||||
json!({"file_path": "a.rs", "edits": [{"old_string": "x", "new_string": "y"}]});
|
||||
let opencode = json!({"filePath": "a.rs", "edits": [{"oldString": "x", "newString": "y"}]});
|
||||
let snake = json!({"path": "a.rs", "edits": [{"old_text": "x", "new_text": "y"}]});
|
||||
|
||||
let expected = EditRequest {
|
||||
path: "a.rs".into(),
|
||||
edits: vec![EditSpec { old_text: "x".into(), new_text: "y".into(), replace_all: false }],
|
||||
};
|
||||
for args in [luxe, claude_code, opencode, snake] {
|
||||
assert_eq!(normalize(&args).expect("normalizes"), expected, "{args}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The rename is only free because the spelling it replaced still normalizes.
|
||||
///
|
||||
/// `old_text`/`new_text` was the advertised shape for long enough to be in every transcript a
|
||||
/// session resumes from, so dropping it from [`OLD_KEYS`]/[`NEW_KEYS`] as "dead" would break
|
||||
/// exactly the calls the rename was meant to stop costing turns.
|
||||
#[test]
|
||||
fn the_spelling_the_schema_used_to_advertise_is_still_accepted() {
|
||||
let request = normalize(&json!({
|
||||
"path": "a.rs",
|
||||
"edits": [{"old_text": "x", "new_text": "y", "replace_all": true}],
|
||||
}))
|
||||
.expect("the retired spelling still normalizes");
|
||||
assert_eq!(request.edits[0].old_text, "x");
|
||||
assert_eq!(request.edits[0].new_text, "y");
|
||||
assert!(request.edits[0].replace_all);
|
||||
}
|
||||
|
||||
/// Canonical first, so a call mixing dialects resolves to the spelling the schema advertises.
|
||||
#[test]
|
||||
fn the_canonical_spelling_wins_when_two_dialects_arrive_together() {
|
||||
let request = normalize(&json!({
|
||||
"path": "a.rs",
|
||||
"edits": [{"oldText": "canonical", "old_string": "alias", "newText": "y"}],
|
||||
}))
|
||||
.expect("normalizes");
|
||||
assert_eq!(request.edits[0].old_text, "canonical");
|
||||
}
|
||||
|
||||
/// A single-edit call is the same call. Claude Code's `Edit` takes exactly one.
|
||||
#[test]
|
||||
fn a_single_edit_may_be_passed_at_the_top_level_or_as_a_lone_object() {
|
||||
let flat = json!({"file_path": "a.rs", "old_string": "x", "new_string": "y"});
|
||||
let object = json!({"path": "a.rs", "edits": {"old_text": "x", "new_text": "y"}});
|
||||
for args in [flat, object] {
|
||||
let request = normalize(&args).expect("normalizes");
|
||||
assert_eq!(request.edits.len(), 1);
|
||||
assert_eq!(request.edits[0].old_text, "x");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_all_is_read_from_any_of_its_spellings_and_defaults_off() {
|
||||
for key in ["replaceAll", "replace_all", "all"] {
|
||||
let args = json!({"path": "a.rs", "oldText": "x", "newText": "y", key: true});
|
||||
assert!(normalize(&args).expect("normalizes").edits[0].replace_all, "{key}");
|
||||
}
|
||||
let args = json!({"path": "a.rs", "oldText": "x", "newText": "y"});
|
||||
assert!(!normalize(&args).expect("normalizes").edits[0].replace_all);
|
||||
}
|
||||
|
||||
/// Deleting text is `newText: ""`; *omitting* it is a truncated call, and applying that
|
||||
/// would silently delete the match.
|
||||
#[test]
|
||||
fn an_empty_replacement_deletes_but_a_missing_one_is_an_error() {
|
||||
let deletion = json!({"path": "a.rs", "oldText": "x", "newText": ""});
|
||||
assert_eq!(normalize(&deletion).expect("normalizes").edits[0].new_text, "");
|
||||
|
||||
let truncated = json!({"path": "a.rs", "oldText": "x"});
|
||||
assert!(matches!(normalize(&truncated), Err(ArgsError::EditField { field: "newText", .. })));
|
||||
}
|
||||
|
||||
/// An empty `oldText` is refused, and the asymmetry with `newText` is deliberate.
|
||||
///
|
||||
/// An empty needle matches at every byte boundary, so `replaceAll` over one would interleave
|
||||
/// the replacement between every character in the file — a 300 KB source becomes hundreds of
|
||||
/// megabytes of garbage, and the tool reports success. Making the two fields symmetric is the
|
||||
/// one-line "cleanup" that turns `edit` into a shredder, so the refusal is pinned rather than
|
||||
/// left to the helper it happens to live in.
|
||||
#[test]
|
||||
fn an_empty_search_is_refused_because_it_would_match_everywhere() {
|
||||
assert_eq!(
|
||||
"abc".match_indices("").count(),
|
||||
4,
|
||||
"the primitive this guards against: an empty needle hits every boundary"
|
||||
);
|
||||
|
||||
for key in OLD_KEYS {
|
||||
let args = json!({"path": "a.rs", key: "", "newText": "y"});
|
||||
assert!(
|
||||
matches!(normalize(&args), Err(ArgsError::EditField { field: "oldText", .. })),
|
||||
"{key} accepted an empty search"
|
||||
);
|
||||
}
|
||||
|
||||
// Even with the flag that would apply it everywhere.
|
||||
let args = json!({"path": "a.rs", "oldText": "", "newText": "y", "replaceAll": true});
|
||||
assert!(matches!(normalize(&args), Err(ArgsError::EditField { field: "oldText", .. })));
|
||||
}
|
||||
|
||||
/// One accidental layer of quoting is the same call, and models add it constantly.
|
||||
#[test]
|
||||
fn a_json_encoded_edits_array_is_unwrapped_rather_than_refused() {
|
||||
let quoted = json!({
|
||||
"path": "a.rs",
|
||||
"edits": r#"[{"oldText": "x", "newText": "y", "replaceAll": true}]"#,
|
||||
});
|
||||
let request = normalize("ed).expect("a quoted array still parses");
|
||||
assert_eq!(
|
||||
request.edits,
|
||||
vec![EditSpec { old_text: "x".into(), new_text: "y".into(), replace_all: true }]
|
||||
);
|
||||
|
||||
// A lone quoted object is a quoted single edit.
|
||||
let object = json!({"path": "a.rs", "edits": r#"{"oldText": "x", "newText": "y"}"#});
|
||||
assert_eq!(normalize(&object).expect("a quoted object too").edits.len(), 1);
|
||||
}
|
||||
|
||||
/// The failure a real session lost six turns to, minus the hoisted sibling that now lets the
|
||||
/// whole shape be read.
|
||||
///
|
||||
/// The model emitted `edits` as a truncated string (`[{"new_text">…`). `edits` being unusable
|
||||
/// was the whole story, and neither error it got said so: one claimed there were no edits while
|
||||
/// listing `edits` among the keys, the other blamed `edit[0]` for a field missing from it. It
|
||||
/// concluded the tool cared about argument *order* and started permuting keys.
|
||||
#[test]
|
||||
fn an_unusable_edits_value_is_named_and_quoted_rather_than_blamed_on_a_sibling() {
|
||||
// The same corruption with its sibling missing: neither half to pair it with
|
||||
let garbled = json!({
|
||||
"path": "src/main.rs",
|
||||
"edits": "[{\"new_text\"> tracing::trace!(?key.code);",
|
||||
});
|
||||
let error = normalize(&garbled).expect_err("nothing can be read out of that");
|
||||
assert!(
|
||||
matches!(error, ArgsError::UnusableEdits { key: "edits", found: "a string", .. }),
|
||||
"the unusable value is what failed, not the sibling: {error:?}"
|
||||
);
|
||||
|
||||
let message = error.message();
|
||||
assert!(message.contains("`edits` arrived as a string"), "{message}");
|
||||
assert!(message.contains(r#"[{"new_text">"#), "quotes what arrived: {message}");
|
||||
assert!(message.contains("Nothing was written"), "{message}");
|
||||
assert!(!message.contains("edit[0]"), "never blames an edit that was never sent: {message}");
|
||||
}
|
||||
|
||||
/// Every other type `edits` can arrive as fails the same way, by name.
|
||||
/// Copied from a claude-sonnet-5-5 run: the search text swallowed into `edits`, the
|
||||
/// replacement hoisted beside it. Both halves are whole, so it is read as the edit it was.
|
||||
#[test]
|
||||
fn the_hoisted_garble_is_read_as_the_one_edit_it_was() {
|
||||
let garbled = json!({
|
||||
"path": "django/forms/fields.py",
|
||||
"edits": "[{\"oldText\"> result.validators = self.validators[:]\n return result",
|
||||
"newText": " result.validators = self.validators[:]\n result.error_messages = self.error_messages.copy()\n return result",
|
||||
});
|
||||
let request = normalize(&garbled).expect("both halves arrived");
|
||||
assert_eq!(request.edits.len(), 1);
|
||||
assert_eq!(
|
||||
request.edits[0].old_text,
|
||||
" result.validators = self.validators[:]\n return result"
|
||||
);
|
||||
assert!(request.edits[0].new_text.contains("error_messages.copy()"));
|
||||
|
||||
// The mirror image, and a key that is no search or replacement at all
|
||||
let mirrored = json!({"path": "a.rs", "edits": "[{\"newText\">y", "oldText": "x"});
|
||||
let mirrored = normalize(&mirrored).expect("mirror image");
|
||||
assert_eq!(
|
||||
(mirrored.edits[0].old_text.as_str(), mirrored.edits[0].new_text.as_str()),
|
||||
("x", "y")
|
||||
);
|
||||
let stranger = json!({"path": "a.rs", "edits": "[{\"path\">x", "newText": "y"});
|
||||
assert!(normalize(&stranger).is_err(), "only the search and replacement keys are read");
|
||||
}
|
||||
|
||||
/// Copied from the claude-sonnet-5-5 and claude-haiku-5-5 runs that confirmed the fix above:
|
||||
/// the opener in the model's own tag form, and the whole array kept in the string with one or
|
||||
/// both separators garbled and a raw line break in it.
|
||||
#[test]
|
||||
fn the_rarer_forms_of_the_same_garble_are_read_too() {
|
||||
let tagged = json!({
|
||||
"path": "django/contrib/admindocs/utils.py",
|
||||
"edits": "\n<parameter name=\"oldText\"> indent = min(len(line)",
|
||||
"newText": " indent = min(len(line) # fixed",
|
||||
});
|
||||
let tagged = normalize(&tagged).expect("tag form");
|
||||
assert_eq!(tagged.edits[0].old_text, " indent = min(len(line)");
|
||||
|
||||
let kept = json!({
|
||||
"path": "django/db/models/query.py",
|
||||
"edits": "[{\"oldText\"> batch_size = 1\",\"newText\":\" a = 1\\n b = 2\"}]",
|
||||
});
|
||||
let kept = normalize(&kept).expect("one separator garbled");
|
||||
assert_eq!(kept.edits[0].old_text, " batch_size = 1");
|
||||
assert_eq!(kept.edits[0].new_text, " a = 1\n b = 2");
|
||||
|
||||
let both = json!({
|
||||
"path": "django/contrib/auth/forms.py",
|
||||
"edits": "[{\"oldText\"> x = 254\n\",\"newText\"> y = 254\n\"}]",
|
||||
});
|
||||
let both = normalize(&both).expect("both separators garbled, a raw line break inside");
|
||||
assert_eq!(both.edits[0].old_text, " x = 254\n");
|
||||
assert_eq!(both.edits[0].new_text, " y = 254\n");
|
||||
|
||||
// A string that is garbled some other way is still refused
|
||||
let other = json!({"path": "a.rs", "edits": "[{\"oldText\": \"x\", \"newText"});
|
||||
assert!(normalize(&other).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_array_edits_value_names_the_type_that_arrived() {
|
||||
for (value, found) in
|
||||
[(json!(7), "a number"), (json!(true), "a boolean"), (json!("not json at all"), "a string")]
|
||||
{
|
||||
let args = json!({"path": "a.rs", "edits": value, "oldText": "x", "newText": "y"});
|
||||
let error = normalize(&args).expect_err("unusable");
|
||||
assert!(
|
||||
matches!(&error, ArgsError::UnusableEdits { found: got, .. } if *got == found),
|
||||
"{value} should report {found}: {error:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A long or multi-line value is quoted as one bounded line — an error is not a diff.
|
||||
#[test]
|
||||
fn the_excerpt_is_one_bounded_line() {
|
||||
let long = format!("[{{\"oldText\">{}\nsecond line", "x".repeat(200));
|
||||
let args = json!({"path": "a.rs", "edits": long});
|
||||
let message = normalize(&args).expect_err("unusable").message();
|
||||
let quoted = message.lines().find(|line| line.trim_start().starts_with("[{")).unwrap();
|
||||
assert!(quoted.chars().count() <= 84, "bounded: {quoted}");
|
||||
assert!(quoted.ends_with('\u{2026}'), "elided: {quoted}");
|
||||
assert!(!message.contains("second line"), "one line only: {message}");
|
||||
}
|
||||
|
||||
/// `edits` present but carrying nothing is empty, not missing — the distinction the old
|
||||
/// message got wrong by listing the key it said had not arrived.
|
||||
#[test]
|
||||
fn an_edits_key_that_carries_nothing_is_reported_as_empty_not_missing() {
|
||||
for value in [json!([]), json!(null), json!(" ")] {
|
||||
let args = json!({"path": "a.rs", "edits": value});
|
||||
assert!(matches!(normalize(&args), Err(ArgsError::EmptyEdits)), "{value}");
|
||||
}
|
||||
// And a blank one does not block the single edit spelled beside it, whichever way it is
|
||||
// blank: `[]` used to return early and lose the pair that `null` kept.
|
||||
for blank in [json!(null), json!([]), json!(" ")] {
|
||||
let beside = json!({"path": "a.rs", "edits": blank, "oldText": "x", "newText": "y"});
|
||||
assert_eq!(
|
||||
normalize(&beside).expect("the top-level pair still reads").edits.len(),
|
||||
1,
|
||||
"{blank}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A pair beside a *usable* array is one more edit, not one to drop on the floor.
|
||||
///
|
||||
/// Ignoring it applied fewer edits than were asked for and reported success, which reads to
|
||||
/// the caller as "done" — the one outcome worse than a refusal. Two edits over the same text
|
||||
/// is a different problem, and `super::plan`'s overlap check is what refuses that.
|
||||
#[test]
|
||||
fn a_top_level_pair_beside_an_array_is_appended_rather_than_dropped() {
|
||||
let request = normalize(&json!({
|
||||
"path": "a.rs",
|
||||
"edits": [{"oldText": "a", "newText": "1"}],
|
||||
"oldText": "b",
|
||||
"newText": "2",
|
||||
}))
|
||||
.expect("normalizes");
|
||||
assert_eq!(request.edits.len(), 2, "both edits survive: {:?}", request.edits);
|
||||
assert_eq!(request.edits[1].old_text, "b");
|
||||
assert_eq!(request.edits[1].new_text, "2");
|
||||
}
|
||||
|
||||
/// A top-level single edit is not `edit[0]`, and saying so is what stops the key-order hunt.
|
||||
#[test]
|
||||
fn a_top_level_single_edit_is_not_reported_as_an_indexed_one() {
|
||||
let message =
|
||||
normalize(&json!({"path": "a.rs", "oldText": "x"})).expect_err("no newText").message();
|
||||
assert!(message.contains("top level"), "{message}");
|
||||
assert!(!message.contains("edit[0]"), "{message}");
|
||||
|
||||
let message = normalize(&json!({"path": "a.rs", "edits": [{"oldText": "x"}]}))
|
||||
.expect_err("no newText")
|
||||
.message();
|
||||
assert!(message.contains("edit[0]"), "an array entry keeps its index: {message}");
|
||||
}
|
||||
|
||||
/// An error has to be correctable from its own text: what arrived, and what was expected.
|
||||
#[test]
|
||||
fn errors_name_the_keys_received_and_the_shape_expected() {
|
||||
let message = normalize(&json!({"filename": "a.rs"})).expect_err("no path").message();
|
||||
assert!(message.contains("filename"), "names what arrived: {message}");
|
||||
assert!(message.contains("`path`"), "and what to use: {message}");
|
||||
assert!(message.contains("\"oldText\""), "and the whole shape: {message}");
|
||||
|
||||
let message =
|
||||
normalize(&json!({"path": "a.rs", "edits": []})).expect_err("empty edits").message();
|
||||
assert!(message.contains("empty"));
|
||||
}
|
||||
|
||||
/// Every refusal has to demonstrate the spelling the schema asks for.
|
||||
///
|
||||
/// The error text is the last thing the model reads before it writes the retry, and it is
|
||||
/// measurably what re-primes the format. An error still saying `old_text` while the schema
|
||||
/// says `oldText` would hand back the spelling the rename exists to stop, on the one turn the
|
||||
/// model is most likely to copy verbatim. So no message may name a retired alias at all.
|
||||
#[test]
|
||||
fn no_error_message_names_a_retired_alias() {
|
||||
let refusals = [
|
||||
normalize(&json!({"filename": "a.rs"})),
|
||||
normalize(&json!({"path": "a.rs", "patch": "…"})),
|
||||
normalize(&json!({"path": "a.rs", "edits": []})),
|
||||
normalize(&json!({"path": "a.rs", "edits": "[{\"newText\">x"})),
|
||||
normalize(&json!({"path": "a.rs", "edits": [{"oldText": "x"}]})),
|
||||
normalize(&json!({"path": "a.rs", "oldText": "x"})),
|
||||
];
|
||||
let retired = ["old_text", "new_text", "replace_all", "old_string", "new_string"];
|
||||
for refusal in refusals {
|
||||
let message = refusal.expect_err("a refusal").message();
|
||||
for alias in retired {
|
||||
assert!(
|
||||
!message.contains(alias),
|
||||
"a refusal offered `{alias}` back to the model:\n{message}"
|
||||
);
|
||||
}
|
||||
assert!(message.contains("oldText"), "and every one shows the shape:\n{message}");
|
||||
}
|
||||
}
|
||||
387
crates/luxe-tools/src/edit/ergonomics_tests.rs
Normal file
387
crates/luxe-tools/src/edit/ergonomics_tests.rs
Normal file
@@ -0,0 +1,387 @@
|
||||
//! Ergonomics — what a mistaken edit says back.
|
||||
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
fn context(root: &std::path::Path) -> ToolContext {
|
||||
let (event_tx, _event_rx) = mpsc::channel(64);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
ToolContext {
|
||||
cwd: root.to_path_buf(),
|
||||
session_id: "test-session".to_string(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(root: &TempDir, args: serde_json::Value) -> ToolResultData {
|
||||
EditTool::new().run(args, &context(root.path())).await
|
||||
}
|
||||
|
||||
fn text_of(result: &ToolResultData) -> String {
|
||||
result
|
||||
.content
|
||||
.iter()
|
||||
.filter_map(|block| match block {
|
||||
ContentBlock::Text(text) => Some(text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn project(contents: &str) -> TempDir {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
std::fs::write(dir.path().join("a.rs"), contents).expect("write");
|
||||
dir
|
||||
}
|
||||
|
||||
/// A Windows checkout is CRLF, the model writes LF, and the edit used to land anyway — the
|
||||
/// whole-line relaxation trims the stray `\r` — but wrote LF back, leaving the four edited
|
||||
/// lines as the only LF lines in the file. `git diff` then reports every line as changed.
|
||||
#[tokio::test]
|
||||
async fn an_edit_to_a_crlf_file_keeps_the_file_crlf() {
|
||||
let dir = project("fn main() {\r\n let x = 1;\r\n go();\r\n}\r\n");
|
||||
let result = run(
|
||||
&dir,
|
||||
json!({"path": "a.rs",
|
||||
"oldText": " let x = 1;\n go();",
|
||||
"newText": " let x = 2;\n go_twice();"}),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(!result.is_error, "{}", text_of(&result));
|
||||
let after = std::fs::read_to_string(dir.path().join("a.rs")).unwrap();
|
||||
assert_eq!(after, "fn main() {\r\n let x = 2;\r\n go_twice();\r\n}\r\n");
|
||||
assert_eq!(after.matches('\n').count(), after.matches("\r\n").count(), "no mixed endings");
|
||||
}
|
||||
|
||||
/// And the converse: a unix file stays unix even if the model sends CRLF (some do, having read
|
||||
/// a Windows file earlier in the same session).
|
||||
#[tokio::test]
|
||||
async fn an_edit_carrying_crlf_does_not_convert_a_unix_file() {
|
||||
let dir = project("a();\nb();\n");
|
||||
let result =
|
||||
run(&dir, json!({"path": "a.rs", "oldText": "a();\r\nb();", "newText": "c();\r\nd();"}))
|
||||
.await;
|
||||
|
||||
assert!(!result.is_error, "{}", text_of(&result));
|
||||
assert_eq!(std::fs::read_to_string(dir.path().join("a.rs")).unwrap(), "c();\nd();\n");
|
||||
}
|
||||
|
||||
/// The reported failure: Sonnet reached for Claude Code's argument names and was rejected.
|
||||
#[tokio::test]
|
||||
async fn a_call_in_another_harness_dialect_still_applies() {
|
||||
let dir = project("let x = 1;\n");
|
||||
let result = run(
|
||||
&dir,
|
||||
json!({"file_path": "a.rs", "old_string": "let x = 1;", "new_string": "let x = 2;"}),
|
||||
)
|
||||
.await;
|
||||
assert!(!result.is_error, "{}", text_of(&result));
|
||||
assert_eq!(std::fs::read_to_string(dir.path().join("a.rs")).unwrap(), "let x = 2;\n");
|
||||
}
|
||||
|
||||
/// The spelling is the fix, so it is pinned rather than left to a consistency pass.
|
||||
///
|
||||
/// `old_text`/`new_text` cost roughly two in five Sonnet edit calls: the separator after a key
|
||||
/// ending in `_text` came back as `">` instead of `": "`, which the provider's JSON repair
|
||||
/// turns into a stringified `edits` with its sibling field hoisted to the top level. Nothing
|
||||
/// downstream can recover that without guessing at file content, and no wording of the error
|
||||
/// prevents it — only the name does. The snake_case spellings stay *accepted* (see
|
||||
/// [`args`]); what must never come back is advertising one.
|
||||
#[test]
|
||||
fn the_schema_advertises_no_argument_whose_name_ends_in_text() {
|
||||
let schema = edit_schema();
|
||||
let item = &schema.parameters["properties"]["edits"]["items"];
|
||||
// `serde_json` preserves insertion order here, so this is both the order the provider is
|
||||
// sent *and* the order it was written in — which is the order a model fills them in.
|
||||
let advertised: Vec<&str> = item["properties"]
|
||||
.as_object()
|
||||
.expect("item properties")
|
||||
.keys()
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
|
||||
assert_eq!(
|
||||
advertised,
|
||||
["oldText", "newText", "replaceAll"],
|
||||
"the advertised spelling is the whole fix, and it reads in the order it is applied"
|
||||
);
|
||||
assert_eq!(item["required"], json!(["oldText", "newText"]));
|
||||
|
||||
let text = serde_json::to_string(&schema.parameters).expect("serializes");
|
||||
for poisoned in ["old_text", "new_text"] {
|
||||
assert!(!text.contains(poisoned), "the schema still names `{poisoned}`: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The refusal has to demonstrate the same shape the schema asks for.
|
||||
///
|
||||
/// A model that gets the spelling wrong reads the error and retries, and the retry copies
|
||||
/// whatever the error showed it — measurably so. Letting the two drift means one of them is
|
||||
/// teaching the shape that fails.
|
||||
#[tokio::test]
|
||||
async fn the_shape_a_refusal_shows_is_the_shape_the_schema_asks_for() {
|
||||
let dir = project("x\n");
|
||||
let refusal = text_of(&run(&dir, json!({"filename": "a.rs"})).await);
|
||||
|
||||
let schema = edit_schema();
|
||||
let advertised = schema.parameters["properties"]["edits"]["items"]["properties"]
|
||||
.as_object()
|
||||
.expect("item properties");
|
||||
for name in advertised.keys() {
|
||||
assert!(refusal.contains(name), "the refusal never shows `{name}`:\n{refusal}");
|
||||
}
|
||||
assert!(refusal.contains("\"path\""), "{refusal}");
|
||||
}
|
||||
|
||||
/// The corruption this rewrite exists to prevent.
|
||||
///
|
||||
/// Uniqueness was validated against the *original* text and the edits then applied in sequence
|
||||
/// with `str::replace`, so an earlier replacement whose output contained a later edit's search
|
||||
/// text changed both — silently, and reported as success.
|
||||
#[tokio::test]
|
||||
async fn an_edit_never_rewrites_text_an_earlier_edit_produced() {
|
||||
let dir = project("alpha\nomega\n");
|
||||
let result = run(
|
||||
&dir,
|
||||
json!({"path": "a.rs", "edits": [
|
||||
{"oldText": "alpha", "newText": "omega"},
|
||||
{"oldText": "omega", "newText": "final"},
|
||||
]}),
|
||||
)
|
||||
.await;
|
||||
assert!(!result.is_error, "{}", text_of(&result));
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.path().join("a.rs")).unwrap(),
|
||||
"omega\nfinal\n",
|
||||
"each edit applies to the text it matched, not to the previous edit's output"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn overlapping_edits_are_refused_before_anything_is_written() {
|
||||
let dir = project("one two three\n");
|
||||
let result = run(
|
||||
&dir,
|
||||
json!({"path": "a.rs", "edits": [
|
||||
{"oldText": "one two", "newText": "1 2"},
|
||||
{"oldText": "two three", "newText": "2 3"},
|
||||
]}),
|
||||
)
|
||||
.await;
|
||||
assert!(result.is_error);
|
||||
let message = text_of(&result);
|
||||
assert!(message.contains("same text"), "{message}");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.path().join("a.rs")).unwrap(),
|
||||
"one two three\n",
|
||||
"nothing was written"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn replace_all_changes_every_occurrence_and_says_how_many() {
|
||||
let dir = project("go();\ngo();\ngo();\n");
|
||||
let result = run(
|
||||
&dir,
|
||||
json!({"path": "a.rs", "edits": [
|
||||
{"oldText": "go();", "newText": "stop();", "replaceAll": true},
|
||||
]}),
|
||||
)
|
||||
.await;
|
||||
assert!(!result.is_error, "{}", text_of(&result));
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.path().join("a.rs")).unwrap(),
|
||||
"stop();\nstop();\nstop();\n"
|
||||
);
|
||||
assert!(text_of(&result).contains("replaceAll"), "the extra occurrences are reported");
|
||||
}
|
||||
|
||||
/// An edit that changes nothing is refused, because "applied" is a claim the model acts on.
|
||||
///
|
||||
/// It reported success and wrote the file back byte-identical, so the agent moved on believing
|
||||
/// the change was in — marked the todo done, ran the gate against unmodified code, wrote it up
|
||||
/// in the journal. A refusal costs one turn; a false success costs everything downstream of it.
|
||||
#[tokio::test]
|
||||
async fn an_edit_that_would_change_nothing_is_refused_rather_than_reported_as_applied() {
|
||||
let dir = project("let x = 1;\n");
|
||||
let result =
|
||||
run(&dir, json!({"path": "a.rs", "oldText": "let x = 1;", "newText": "let x = 1;"})).await;
|
||||
|
||||
assert!(result.is_error, "{}", text_of(&result));
|
||||
let message = text_of(&result);
|
||||
assert!(message.contains("changes nothing"), "{message}");
|
||||
assert!(message.contains("Nothing was written"), "{message}");
|
||||
assert_eq!(std::fs::read_to_string(dir.path().join("a.rs")).unwrap(), "let x = 1;\n");
|
||||
}
|
||||
|
||||
/// The check asks whether the *file* moves, which is not the same as `oldText != newText`.
|
||||
///
|
||||
/// Line endings are normalized on both sides before an edit is placed, so a call that differs
|
||||
/// only in `\r\n` versus `\n` resolves to writing back what is already there. That reads as a
|
||||
/// change in the arguments and is none on disk.
|
||||
#[tokio::test]
|
||||
async fn an_edit_that_only_changes_line_endings_is_the_same_no_op() {
|
||||
let dir = project("a();\nb();\n");
|
||||
let result =
|
||||
run(&dir, json!({"path": "a.rs", "oldText": "a();\nb();", "newText": "a();\r\nb();"}))
|
||||
.await;
|
||||
|
||||
assert!(result.is_error, "{}", text_of(&result));
|
||||
assert!(text_of(&result).contains("changes nothing"), "{}", text_of(&result));
|
||||
}
|
||||
|
||||
/// One dead edit in a batch is still refused, and the whole batch stays unwritten.
|
||||
///
|
||||
/// A whole-file comparison after applying would miss this: edit[0] moves the file, so the file
|
||||
/// moved, so nothing looks wrong — and edit[1] is silently counted among the "2 edit(s)
|
||||
/// applied". Placing the check per edit is what makes the count honest.
|
||||
#[tokio::test]
|
||||
async fn a_no_op_beside_a_real_edit_is_named_by_its_index_and_neither_lands() {
|
||||
let dir = project("alpha\nbeta\n");
|
||||
let result = run(
|
||||
&dir,
|
||||
json!({"path": "a.rs", "edits": [
|
||||
{"oldText": "alpha", "newText": "gamma"},
|
||||
{"oldText": "beta", "newText": "beta"},
|
||||
]}),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(result.is_error, "{}", text_of(&result));
|
||||
assert!(text_of(&result).contains("edit[1]"), "names which one: {}", text_of(&result));
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.path().join("a.rs")).unwrap(),
|
||||
"alpha\nbeta\n",
|
||||
"atomic: the real edit beside it did not land either"
|
||||
);
|
||||
}
|
||||
|
||||
/// Deleting text is a change, and the no-op check must not read an empty replacement as one.
|
||||
#[tokio::test]
|
||||
async fn an_empty_replacement_still_deletes() {
|
||||
let dir = project("keep();\ndrop();\n");
|
||||
let result = run(&dir, json!({"path": "a.rs", "oldText": "drop();\n", "newText": ""})).await;
|
||||
|
||||
assert!(!result.is_error, "{}", text_of(&result));
|
||||
assert_eq!(std::fs::read_to_string(dir.path().join("a.rs")).unwrap(), "keep();\n");
|
||||
}
|
||||
|
||||
/// An ambiguity error has to say where, or "add more context" is advice with no target.
|
||||
#[tokio::test]
|
||||
async fn an_ambiguous_edit_names_the_lines_it_matched() {
|
||||
let dir = project("go();\nwait();\ngo();\n");
|
||||
let result = run(&dir, json!({"path": "a.rs", "oldText": "go();", "newText": "stop();"})).await;
|
||||
assert!(result.is_error);
|
||||
let message = text_of(&result);
|
||||
assert!(message.contains("matched 2 times"), "{message}");
|
||||
assert!(message.contains("lines 1, 3"), "and where: {message}");
|
||||
assert!(message.contains("replaceAll"), "and the way out: {message}");
|
||||
}
|
||||
|
||||
/// "not found" alone is undiagnosable — a typo, a stale read and the wrong file all look the
|
||||
/// same. Pointing at the closest line makes the next attempt a correction.
|
||||
#[tokio::test]
|
||||
async fn numbers_copied_from_read_are_left_out_and_said_so() {
|
||||
let dir = project("fn main() {\n let total = 1;\n go();\n}\n");
|
||||
let result = run(
|
||||
&dir,
|
||||
json!({"path": "a.rs", "edits": [{
|
||||
"oldText": "2: let total = 1;\n3: go();",
|
||||
"newText": "2: let total = 2;\n3: go_twice();"
|
||||
}]}),
|
||||
)
|
||||
.await;
|
||||
assert!(!result.is_error, "{}", text_of(&result));
|
||||
assert!(text_of(&result).contains("line numbers `read` shows were left out"));
|
||||
let after = std::fs::read_to_string(dir.path().join("a.rs")).unwrap();
|
||||
assert_eq!(after, "fn main() {\n let total = 2;\n go_twice();\n}\n");
|
||||
}
|
||||
|
||||
/// The numbers have to be the real ones: text that matches elsewhere, numbers that skip, or a
|
||||
/// match that is still ambiguous is an edit the caller did not mean, and is refused as written.
|
||||
#[tokio::test]
|
||||
async fn numbers_that_do_not_name_the_matched_lines_are_not_stripped() {
|
||||
let source = "fn main() {\n go();\n go();\n}\n";
|
||||
for old_text in ["9: go();", "2: go();\n4: go();", "x2: go();"] {
|
||||
let dir = project(source);
|
||||
let result = run(
|
||||
&dir,
|
||||
json!({"path": "a.rs", "edits": [{"oldText": old_text, "newText": "stop();"}]}),
|
||||
)
|
||||
.await;
|
||||
assert!(result.is_error, "{old_text}: {}", text_of(&result));
|
||||
assert_eq!(std::fs::read_to_string(dir.path().join("a.rs")).unwrap(), source);
|
||||
}
|
||||
// a prefix `read` never writes, and a number naming one line beside `replaceAll`
|
||||
let single = "fn main() {\n let total = 1;\n}\n";
|
||||
for edit in [
|
||||
json!({"oldText": "+2: let total = 1;", "newText": " let total = 2;"}),
|
||||
json!({"oldText": "2: let total = 1;", "newText": " let total = 2;", "replaceAll": true}),
|
||||
] {
|
||||
let dir = project(single);
|
||||
let result = run(&dir, json!({"path": "a.rs", "edits": [edit.clone()]})).await;
|
||||
assert!(result.is_error, "{edit}: {}", text_of(&result));
|
||||
assert_eq!(std::fs::read_to_string(dir.path().join("a.rs")).unwrap(), single);
|
||||
}
|
||||
// and a number does not make an ambiguous match unique: that stays the caller's to fix
|
||||
let dir = project(source);
|
||||
let result = run(
|
||||
&dir,
|
||||
json!({"path": "a.rs", "edits": [{"oldText": "3: go();", "newText": " stop();"}]}),
|
||||
)
|
||||
.await;
|
||||
assert!(result.is_error, "{}", text_of(&result));
|
||||
assert_eq!(std::fs::read_to_string(dir.path().join("a.rs")).unwrap(), source);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_near_miss_reports_what_is_actually_there() {
|
||||
let dir = project("fn main() {\n let total = 1;\n}\n");
|
||||
let result =
|
||||
run(&dir, json!({"path": "a.rs", "oldText": " let total = 2;", "newText": "x"})).await;
|
||||
assert!(result.is_error);
|
||||
let message = text_of(&result);
|
||||
assert!(message.contains("Closest match is line 2"), "{message}");
|
||||
assert!(message.contains("let total = 1;"), "and what is there: {message}");
|
||||
assert!(message.contains("Nothing was written"), "{message}");
|
||||
}
|
||||
|
||||
/// A tolerated match is never a silent one.
|
||||
#[tokio::test]
|
||||
async fn a_relaxed_match_applies_and_is_reported() {
|
||||
let dir = project("impl T {\n fn go() {\n work();\n }\n}\n");
|
||||
let result = run(
|
||||
&dir,
|
||||
json!({"path": "a.rs", "edits": [{
|
||||
"oldText": "fn go() {\n work();\n}",
|
||||
"newText": "fn go() {\n work_twice();\n}",
|
||||
}]}),
|
||||
)
|
||||
.await;
|
||||
assert!(!result.is_error, "{}", text_of(&result));
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.path().join("a.rs")).unwrap(),
|
||||
"impl T {\n fn go() {\n work_twice();\n }\n}\n",
|
||||
"the replacement is re-indented to the file's depth"
|
||||
);
|
||||
assert!(text_of(&result).contains("re-indenting"), "and the tolerance is declared");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_call_that_cannot_be_understood_says_what_arrived_and_what_was_expected() {
|
||||
let dir = project("x\n");
|
||||
let result = run(&dir, json!({"filename": "a.rs", "patch": "…"})).await;
|
||||
assert!(result.is_error);
|
||||
let message = text_of(&result);
|
||||
assert!(message.contains("filename"), "names the keys it got: {message}");
|
||||
assert!(message.contains("`path`"), "names the one to use: {message}");
|
||||
assert!(message.contains("\"oldText\""), "and shows the whole shape: {message}");
|
||||
}
|
||||
368
crates/luxe-tools/src/edit/locate.rs
Normal file
368
crates/luxe-tools/src/edit/locate.rs
Normal file
@@ -0,0 +1,368 @@
|
||||
//! Locating an edit's target — exact first, then two bounded relaxations.
|
||||
//!
|
||||
//! Reproducing a block of code byte-for-byte is the single most common way a model's edit fails,
|
||||
//! and the two ways it fails are boring: trailing whitespace it could not see, and indentation it
|
||||
//! re-derived. Neither changes which code was meant. So the match is tried three times, from
|
||||
//! strictest to loosest, and **every** attempt still demands a unique match — tolerance here buys
|
||||
//! the model a retry, never a guess about which of two places it meant.
|
||||
//!
|
||||
//! The relaxations are line-oriented, because that is the shape of the mistake: they only apply
|
||||
//! when the search text is whole lines, and the indentation pass only accepts a window whose lines
|
||||
//! are *uniformly* shifted, then re-indents the replacement by the same amount. A window where
|
||||
//! each line drifted differently is a different block of code, not a mis-indented one.
|
||||
|
||||
use std::ops::Range;
|
||||
|
||||
/// How a match was found — reported to the model so a tolerated edit is never a silent one.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum MatchKind {
|
||||
/// Byte-for-byte.
|
||||
Exact,
|
||||
/// Identical once trailing whitespace was ignored.
|
||||
TrailingWhitespace,
|
||||
/// Identical once a uniform indentation shift was applied.
|
||||
Indentation { spaces: i64 },
|
||||
}
|
||||
|
||||
impl MatchKind {
|
||||
/// A short note for the tool result, or `None` when the match was exact and needs no comment.
|
||||
pub(super) fn note(self) -> Option<String> {
|
||||
match self {
|
||||
Self::Exact => None,
|
||||
Self::TrailingWhitespace => Some("matched ignoring trailing whitespace".to_string()),
|
||||
Self::Indentation { spaces } => Some(format!(
|
||||
"matched after re-indenting by {} space{}",
|
||||
spaces.abs(),
|
||||
if spaces.abs() == 1 { "" } else { "s" }
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where an edit applies, and what to write there.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct Located {
|
||||
/// Byte ranges to replace, in ascending order.
|
||||
pub(crate) ranges: Vec<Range<usize>>,
|
||||
/// The replacement, adjusted when the match required one.
|
||||
pub(crate) replacement: String,
|
||||
/// How it was found.
|
||||
pub(crate) kind: MatchKind,
|
||||
}
|
||||
|
||||
/// Why an edit could not be placed.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum LocateError {
|
||||
/// Nothing matched, with the closest thing in the file when there is one.
|
||||
NotFound { nearest: Option<Nearest> },
|
||||
/// Several places matched and the caller did not ask for all of them.
|
||||
Ambiguous { lines: Vec<usize> },
|
||||
}
|
||||
|
||||
/// The closest region in the file to what was searched for.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct Nearest {
|
||||
/// 1-based line the region starts at.
|
||||
pub(crate) line: usize,
|
||||
/// What is actually there.
|
||||
pub(crate) text: String,
|
||||
}
|
||||
|
||||
/// Finds every place `old_text` applies, relaxing only as far as it must.
|
||||
///
|
||||
/// `old_text` must be non-empty; [`super::args::normalize`] refuses an empty one as a missing field
|
||||
/// and pins that. An empty needle matches at every byte boundary, so it is a precondition here
|
||||
/// rather than a case to handle — there is no sensible place to apply an edit that matches
|
||||
/// everywhere.
|
||||
pub(crate) fn locate(
|
||||
content: &str,
|
||||
old_text: &str,
|
||||
new_text: &str,
|
||||
replace_all: bool,
|
||||
) -> Result<Located, LocateError> {
|
||||
let exact: Vec<Range<usize>> =
|
||||
content.match_indices(old_text).map(|(at, text)| at..at + text.len()).collect();
|
||||
if !exact.is_empty() {
|
||||
return finish(content, exact, new_text.to_string(), MatchKind::Exact, replace_all);
|
||||
}
|
||||
if let Some(found) = line_window(content, old_text, Relax::TrailingWhitespace) {
|
||||
return finish(
|
||||
content,
|
||||
found.ranges,
|
||||
new_text.to_string(),
|
||||
MatchKind::TrailingWhitespace,
|
||||
replace_all,
|
||||
);
|
||||
}
|
||||
if let Some(found) = line_window(content, old_text, Relax::Indentation) {
|
||||
let spaces = found.shift;
|
||||
return finish(
|
||||
content,
|
||||
found.ranges,
|
||||
reindent(new_text, spaces),
|
||||
MatchKind::Indentation { spaces },
|
||||
replace_all,
|
||||
);
|
||||
}
|
||||
Err(LocateError::NotFound { nearest: nearest_region(content, old_text) })
|
||||
}
|
||||
|
||||
fn finish(
|
||||
content: &str,
|
||||
ranges: Vec<Range<usize>>,
|
||||
replacement: String,
|
||||
kind: MatchKind,
|
||||
replace_all: bool,
|
||||
) -> Result<Located, LocateError> {
|
||||
if ranges.len() > 1 && !replace_all {
|
||||
return Err(LocateError::Ambiguous {
|
||||
lines: ranges.iter().map(|range| line_of(content, range.start)).collect(),
|
||||
});
|
||||
}
|
||||
let ranges = if replace_all { ranges } else { vec![ranges[0].clone()] };
|
||||
Ok(Located { ranges, replacement, kind })
|
||||
}
|
||||
|
||||
/// Which difference a line-window pass is willing to overlook.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Relax {
|
||||
TrailingWhitespace,
|
||||
Indentation,
|
||||
}
|
||||
|
||||
struct WindowMatch {
|
||||
ranges: Vec<Range<usize>>,
|
||||
/// Spaces the file's copy is indented by, relative to the search text.
|
||||
shift: i64,
|
||||
}
|
||||
|
||||
/// Slides `needle`'s lines over the file's, comparing under `relax`.
|
||||
///
|
||||
/// Only for whole-line searches. A search that starts or ends mid-line is describing a fragment,
|
||||
/// and replacing the lines around it would rewrite code the caller never mentioned.
|
||||
fn line_window(content: &str, needle: &str, relax: Relax) -> Option<WindowMatch> {
|
||||
if needle.is_empty() || needle.contains('\n') && !needle.ends_with('\n') && false {
|
||||
return None;
|
||||
}
|
||||
let needle_lines: Vec<&str> = needle.trim_end_matches('\n').split('\n').collect();
|
||||
if needle_lines.iter().all(|line| line.trim().is_empty()) {
|
||||
return None;
|
||||
}
|
||||
let starts = line_starts(content);
|
||||
let file_lines: Vec<&str> = content.split('\n').collect();
|
||||
if needle_lines.len() > file_lines.len() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut ranges = Vec::new();
|
||||
let mut shift = None;
|
||||
for index in 0..=file_lines.len() - needle_lines.len() {
|
||||
let window = &file_lines[index..index + needle_lines.len()];
|
||||
let Some(window_shift) = window_matches(window, &needle_lines, relax) else {
|
||||
continue;
|
||||
};
|
||||
// Every occurrence must agree about the shift, or the replacement cannot be re-indented
|
||||
// for all of them at once.
|
||||
match shift {
|
||||
Some(previous) if previous != window_shift => return None,
|
||||
_ => shift = Some(window_shift),
|
||||
}
|
||||
let start = starts[index];
|
||||
let last = index + needle_lines.len() - 1;
|
||||
let end = starts[last] + window[window.len() - 1].len();
|
||||
ranges.push(start..end);
|
||||
}
|
||||
(!ranges.is_empty()).then(|| WindowMatch { ranges, shift: shift.unwrap_or(0) })
|
||||
}
|
||||
|
||||
/// The uniform indentation shift that makes `window` equal `needle`, if one exists.
|
||||
fn window_matches(window: &[&str], needle: &[&str], relax: Relax) -> Option<i64> {
|
||||
let mut shift: Option<i64> = None;
|
||||
for (actual, wanted) in window.iter().zip(needle) {
|
||||
match relax {
|
||||
Relax::TrailingWhitespace => {
|
||||
if actual.trim_end() != wanted.trim_end() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Relax::Indentation => {
|
||||
if actual.trim() != wanted.trim() {
|
||||
return None;
|
||||
}
|
||||
// A blank line carries no indentation to compare, so it constrains nothing.
|
||||
if actual.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let delta = indent_width(actual) - indent_width(wanted);
|
||||
match shift {
|
||||
Some(previous) if previous != delta => return None,
|
||||
_ => shift = Some(delta),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(shift.unwrap_or(0))
|
||||
}
|
||||
|
||||
/// Leading spaces, counting a tab as one unit — the comparison only needs to be self-consistent.
|
||||
fn indent_width(line: &str) -> i64 {
|
||||
line.chars().take_while(|character| character.is_whitespace()).count() as i64
|
||||
}
|
||||
|
||||
/// Shifts every non-blank line of `text` by `spaces`.
|
||||
fn reindent(text: &str, spaces: i64) -> String {
|
||||
if spaces == 0 {
|
||||
return text.to_string();
|
||||
}
|
||||
text.split('\n')
|
||||
.map(|line| {
|
||||
if line.trim().is_empty() {
|
||||
return line.to_string();
|
||||
}
|
||||
match spaces.cmp(&0) {
|
||||
std::cmp::Ordering::Greater => format!("{}{line}", " ".repeat(spaces as usize)),
|
||||
std::cmp::Ordering::Less => {
|
||||
let drop = (-spaces) as usize;
|
||||
let removable =
|
||||
line.chars().take(drop).take_while(|c| *c == ' ' || *c == '\t').count();
|
||||
line.chars().skip(removable).collect()
|
||||
}
|
||||
std::cmp::Ordering::Equal => line.to_string(),
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
/// Byte offset of every line start.
|
||||
fn line_starts(content: &str) -> Vec<usize> {
|
||||
let mut starts = vec![0];
|
||||
starts.extend(content.match_indices('\n').map(|(at, _)| at + 1));
|
||||
starts
|
||||
}
|
||||
|
||||
/// 1-based line number of a byte offset.
|
||||
pub(crate) fn line_of(content: &str, offset: usize) -> usize {
|
||||
content[..offset.min(content.len())].matches('\n').count() + 1
|
||||
}
|
||||
|
||||
/// The region of the file that most resembles the search text.
|
||||
///
|
||||
/// "not found" on its own is undiagnosable: the model cannot tell a typo from a stale read from a
|
||||
/// file it never opened. Pointing at the closest thing turns the next attempt into a correction.
|
||||
fn nearest_region(content: &str, needle: &str) -> Option<Nearest> {
|
||||
let anchor = needle.lines().find(|line| !line.trim().is_empty())?.trim();
|
||||
if anchor.len() < 4 {
|
||||
return None;
|
||||
}
|
||||
let mut best: Option<(usize, usize)> = None;
|
||||
for (index, line) in content.lines().enumerate() {
|
||||
let score = similarity(line.trim(), anchor);
|
||||
if score > 0 && best.is_none_or(|(previous, _)| score > previous) {
|
||||
best = Some((score, index));
|
||||
}
|
||||
}
|
||||
let (score, index) = best?;
|
||||
// Below roughly half the anchor's length it is not a near miss, it is a coincidence.
|
||||
if score * 2 < anchor.len() {
|
||||
return None;
|
||||
}
|
||||
let text = content.lines().nth(index)?.to_string();
|
||||
Some(Nearest { line: index + 1, text })
|
||||
}
|
||||
|
||||
/// Length of the longest shared prefix, as a cheap stand-in for edit distance.
|
||||
fn similarity(left: &str, right: &str) -> usize {
|
||||
left.chars().zip(right.chars()).take_while(|(a, b)| a == b).count()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const FILE: &str = "fn main() {\n let x = 1;\n println!(\"{x}\");\n}\n";
|
||||
|
||||
#[test]
|
||||
fn an_exact_match_is_found_and_reported_as_exact() {
|
||||
let found = locate(FILE, " let x = 1;", " let x = 2;", false).expect("found");
|
||||
assert_eq!(found.kind, MatchKind::Exact);
|
||||
assert_eq!(found.ranges.len(), 1);
|
||||
assert_eq!(found.kind.note(), None, "an exact match needs no explanation");
|
||||
}
|
||||
|
||||
/// The most common near-miss there is: whitespace the model could not see. It only bites on a
|
||||
/// multi-line search, where the invisible characters sit *inside* the block being matched.
|
||||
#[test]
|
||||
fn trailing_whitespace_is_forgiven_and_said_out_loud() {
|
||||
let file = "fn main() {\n let x = 1; \n go();\n}\n";
|
||||
let found = locate(file, " let x = 1;\n go();", " let x = 2;\n go();", false)
|
||||
.expect("found");
|
||||
assert_eq!(found.kind, MatchKind::TrailingWhitespace);
|
||||
assert!(found.kind.note().expect("a note").contains("trailing whitespace"));
|
||||
assert_eq!(found.ranges.len(), 1);
|
||||
}
|
||||
|
||||
/// A uniformly re-indented block is the same block; the replacement moves with it.
|
||||
#[test]
|
||||
fn a_uniform_indentation_shift_is_forgiven_and_applied_to_the_replacement() {
|
||||
let file = "impl T {\n fn go(&self) {\n work();\n }\n}\n";
|
||||
let found = locate(
|
||||
file,
|
||||
"fn go(&self) {\n work();\n}",
|
||||
"fn go(&self) {\n work_twice();\n}",
|
||||
false,
|
||||
)
|
||||
.expect("found");
|
||||
assert_eq!(found.kind, MatchKind::Indentation { spaces: 8 });
|
||||
assert_eq!(
|
||||
found.replacement, " fn go(&self) {\n work_twice();\n }",
|
||||
"the replacement is re-indented to match the file, not the search text"
|
||||
);
|
||||
}
|
||||
|
||||
/// Lines that drifted *differently* are a different block, not a mis-indented one.
|
||||
#[test]
|
||||
fn a_non_uniform_shift_is_not_treated_as_indentation() {
|
||||
let file = "impl T {\n fn go(&self) {\n work();\n }\n}\n";
|
||||
let error = locate(file, "fn go(&self) {\n work();\n}", "x", false).expect_err("no");
|
||||
assert!(matches!(error, LocateError::NotFound { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn several_matches_are_ambiguous_unless_replace_all_was_asked_for() {
|
||||
let file = "a();\nb();\na();\n";
|
||||
let error = locate(file, "a();", "c();", false).expect_err("ambiguous");
|
||||
let LocateError::Ambiguous { lines } = error else { panic!("expected ambiguity") };
|
||||
assert_eq!(lines, vec![1, 3], "and it says where, so the fix is to add context");
|
||||
|
||||
let found = locate(file, "a();", "c();", true).expect("replace_all takes them all");
|
||||
assert_eq!(found.ranges.len(), 2);
|
||||
}
|
||||
|
||||
/// "not found" alone cannot be acted on; the closest line can.
|
||||
#[test]
|
||||
fn a_near_miss_reports_the_closest_line() {
|
||||
let error =
|
||||
locate(FILE, " let x = 11;", "y", false).expect_err("no exact or relaxed match");
|
||||
let LocateError::NotFound { nearest } = error else { panic!("expected not-found") };
|
||||
let nearest = nearest.expect("a near miss in the same file");
|
||||
assert_eq!(nearest.line, 2);
|
||||
assert!(nearest.text.contains("let x = 1;"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unrelated_search_reports_no_near_miss_rather_than_a_coincidence() {
|
||||
let error = locate(FILE, "quantum_flux_capacitor()", "y", false).expect_err("no match");
|
||||
assert_eq!(error, LocateError::NotFound { nearest: None });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dedent_removes_only_whitespace() {
|
||||
assert_eq!(
|
||||
reindent(" deep();\n\n more();", -4),
|
||||
" deep();\n\n more();"
|
||||
);
|
||||
// Never eats real characters when the line is shallower than the shift asks for.
|
||||
assert_eq!(reindent(" x();", -8), "x();");
|
||||
}
|
||||
}
|
||||
230
crates/luxe-tools/src/edit/tests.rs
Normal file
230
crates/luxe-tools/src/edit/tests.rs
Normal file
@@ -0,0 +1,230 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
fn test_context(tmp_dir: &std::path::Path) -> ToolContext {
|
||||
let (event_tx, _event_rx) = mpsc::channel(64);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
ToolContext {
|
||||
cwd: tmp_dir.to_path_buf(),
|
||||
session_id: "test-session".to_string(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A stand-in formatter: on `FileChanged` it rewrites the file the way rustfmt would.
|
||||
struct Spacer;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl luxe_core::hook::Hook for Spacer {
|
||||
fn name(&self) -> &'static str {
|
||||
"spacer"
|
||||
}
|
||||
fn interest(&self) -> &[luxe_core::hook::HookPoint] {
|
||||
&[luxe_core::hook::HookPoint::FileChanged]
|
||||
}
|
||||
async fn on(
|
||||
&self,
|
||||
_: luxe_core::hook::HookPoint,
|
||||
ev: &luxe_core::hook::HookEvent,
|
||||
_: &luxe_core::hook::HookCtx,
|
||||
) -> luxe_core::hook::HookOutcome {
|
||||
if let luxe_core::hook::HookEvent::FileChanged { path, .. } = ev {
|
||||
let text = std::fs::read_to_string(path).unwrap();
|
||||
std::fs::write(path, text.replace("a:i32", "a: i32")).unwrap();
|
||||
}
|
||||
luxe_core::hook::HookOutcome::Continue
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn formatting_context(tmp_dir: &std::path::Path) -> ToolContext {
|
||||
let mut hook_registry = luxe_core::hook::HookRegistry::new();
|
||||
hook_registry.register(Arc::new(Spacer));
|
||||
let mut cx = test_context(tmp_dir);
|
||||
cx.hook_ctx = Some(luxe_core::hook::HookCtx {
|
||||
session_id: cx.session_id.clone(),
|
||||
event_tx: cx.event_tx.clone(),
|
||||
hook_registry,
|
||||
});
|
||||
cx
|
||||
}
|
||||
|
||||
/// When format-on-save rewrites the edit, the result shows the file as it now is and says so,
|
||||
/// because the next edit is matched against that text and not the text the call sent.
|
||||
#[tokio::test]
|
||||
async fn a_reformatted_edit_shows_the_file_as_it_is_now() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("lib.rs"), "fn a() {}\nfn sub() {}\n").unwrap();
|
||||
let args = json!({"path": "lib.rs", "edits": [
|
||||
{"oldText": "fn sub() {}", "newText": "fn sub(a:i32) {}"}
|
||||
]});
|
||||
let result = EditTool::new().run(args, &formatting_context(dir.path())).await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.starts_with("Applied 1 edit(s) to 'lib.rs'"), "named from the project: {text}");
|
||||
assert!(text.contains("Format-on-save then reformatted the file"), "{text}");
|
||||
assert!(text.contains("+2 fn sub(a: i32) {}"), "the formatted line: {text}");
|
||||
assert!(!text.contains("a:i32"), "not the line as sent: {text}");
|
||||
|
||||
// a formatter with nothing to change says nothing
|
||||
let args = json!({"path": "lib.rs", "edits": [{"oldText": "fn a()", "newText": "fn b()"}]});
|
||||
let result = EditTool::new().run(args, &formatting_context(dir.path())).await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(!text.contains("Format-on-save"), "{text}");
|
||||
assert!(text.contains("+1 fn b() {}"), "{text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn edit_tool_basic() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let tmp_dir = tmp_dir_guard.path().to_path_buf();
|
||||
std::fs::write(tmp_dir.join("test.txt"), "Hello, World!").unwrap();
|
||||
|
||||
let tool = EditTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({
|
||||
"path": "test.txt",
|
||||
"edits": [
|
||||
{
|
||||
"oldText": "World",
|
||||
"newText": "Rust"
|
||||
}
|
||||
]
|
||||
});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(!result.is_error);
|
||||
if let ContentBlock::Text(text) = &result.content[0] {
|
||||
assert!(text.contains("Applied 1 edit(s)"));
|
||||
// The preview shows whole numbered lines, not just the replaced fragment.
|
||||
assert!(
|
||||
text.contains("-1 Hello, World!") && text.contains("+1 Hello, Rust!"),
|
||||
"shows the line-numbered diff: {text}"
|
||||
);
|
||||
} else {
|
||||
panic!("expected Text block");
|
||||
}
|
||||
|
||||
// Verify file was edited.
|
||||
let content = std::fs::read_to_string(tmp_dir.join("test.txt")).unwrap();
|
||||
assert_eq!(content, "Hello, Rust!");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn edit_tool_multi_edit() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let tmp_dir = tmp_dir_guard.path().to_path_buf();
|
||||
std::fs::write(tmp_dir.join("test.txt"), "line1\nline2\nline3").unwrap();
|
||||
|
||||
let tool = EditTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({
|
||||
"path": "test.txt",
|
||||
"edits": [
|
||||
{
|
||||
"oldText": "line1",
|
||||
"newText": "first"
|
||||
},
|
||||
{
|
||||
"oldText": "line3",
|
||||
"newText": "third"
|
||||
}
|
||||
]
|
||||
});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(!result.is_error);
|
||||
|
||||
// Verify file was edited.
|
||||
let content = std::fs::read_to_string(tmp_dir.join("test.txt")).unwrap();
|
||||
assert_eq!(content, "first\nline2\nthird");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn edit_tool_not_found() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let tmp_dir = tmp_dir_guard.path().to_path_buf();
|
||||
std::fs::write(tmp_dir.join("test.txt"), "Hello, World!").unwrap();
|
||||
|
||||
let tool = EditTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({
|
||||
"path": "test.txt",
|
||||
"edits": [
|
||||
{
|
||||
"oldText": "nonexistent",
|
||||
"newText": "replacement"
|
||||
}
|
||||
]
|
||||
});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(result.is_error);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn edit_tool_ambiguous_match() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let tmp_dir = tmp_dir_guard.path().to_path_buf();
|
||||
std::fs::write(tmp_dir.join("test.txt"), "line\nline\nline").unwrap();
|
||||
|
||||
let tool = EditTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({
|
||||
"path": "test.txt",
|
||||
"edits": [
|
||||
{
|
||||
"oldText": "line",
|
||||
"newText": "LINE"
|
||||
}
|
||||
]
|
||||
});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(result.is_error);
|
||||
if let ContentBlock::Text(text) = &result.content[0] {
|
||||
assert!(text.contains("matched 3 times"));
|
||||
} else {
|
||||
panic!("expected Text block");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn edit_tool_atomic_failure() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let tmp_dir = tmp_dir_guard.path().to_path_buf();
|
||||
std::fs::write(tmp_dir.join("test.txt"), "line1\nline2").unwrap();
|
||||
|
||||
let tool = EditTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
// First edit succeeds, second fails — should be atomic (no changes).
|
||||
let args = json!({
|
||||
"path": "test.txt",
|
||||
"edits": [
|
||||
{
|
||||
"oldText": "line1",
|
||||
"newText": "first"
|
||||
},
|
||||
{
|
||||
"oldText": "nonexistent",
|
||||
"newText": "second"
|
||||
}
|
||||
]
|
||||
});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(result.is_error);
|
||||
|
||||
// Verify file was NOT edited (atomic failure).
|
||||
let content = std::fs::read_to_string(tmp_dir.join("test.txt")).unwrap();
|
||||
assert_eq!(content, "line1\nline2");
|
||||
}
|
||||
229
crates/luxe-tools/src/exa.rs
Normal file
229
crates/luxe-tools/src/exa.rs
Normal file
@@ -0,0 +1,229 @@
|
||||
//! Exa — the keyed REST endpoint, for an account that has one.
|
||||
//!
|
||||
//! [`crate::exa_mcp`] is the same vendor's keyless MCP surface and the default when nothing is
|
||||
//! configured; this is what a paid key buys, and the two return the same normalized hits.
|
||||
//!
|
||||
//! Two things about Exa's schema are easy to get wrong and silent when you do: the field is
|
||||
//! `numResults`, not `num_results`, and a result carries no page text unless `contents` asks for
|
||||
//! it. Getting either wrong still answers 200 — with Exa's own default result count, and with
|
||||
//! nothing in the snippet.
|
||||
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::web::{SearchBackend, SearchHit, SearchOptions, WebError};
|
||||
|
||||
/// Longest highlight payload requested per result, matching the keyless backend's budget.
|
||||
const HIGHLIGHT_CHARS: u32 = 1_200;
|
||||
|
||||
/// Fallback clip when a result carries raw text but no extracted highlight.
|
||||
const SNIPPET_CHARS: usize = 600;
|
||||
|
||||
/// Exa Search API request.
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ExaRequest {
|
||||
query: String,
|
||||
num_results: usize,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
include_domains: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
exclude_domains: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
start_published_date: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
contents: Option<ExaContents>,
|
||||
}
|
||||
|
||||
/// What Exa should extract from each result page.
|
||||
#[derive(Debug, Serialize)]
|
||||
struct ExaContents {
|
||||
text: ExaText,
|
||||
highlights: ExaHighlights,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ExaText {
|
||||
max_characters: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ExaHighlights {
|
||||
num_sentences: u32,
|
||||
highlights_per_url: u32,
|
||||
}
|
||||
|
||||
/// Exa Search API response.
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ExaResponse {
|
||||
results: Option<Vec<ExaResult>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ExaResult {
|
||||
title: Option<String>,
|
||||
url: Option<String>,
|
||||
text: Option<String>,
|
||||
#[serde(default)]
|
||||
highlights: Vec<String>,
|
||||
}
|
||||
|
||||
impl ExaResult {
|
||||
/// The passage to show: the matched highlights when Exa extracted any, else a clip of the page.
|
||||
fn snippet(&self) -> String {
|
||||
if !self.highlights.is_empty() {
|
||||
return self.highlights.join(" … ");
|
||||
}
|
||||
let text = self.text.clone().unwrap_or_default();
|
||||
match text.chars().count() > SNIPPET_CHARS {
|
||||
true => text.chars().take(SNIPPET_CHARS).collect::<String>() + "…",
|
||||
false => text,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Exa search backend.
|
||||
pub struct ExaBackend {
|
||||
api_key: String,
|
||||
base_url: String,
|
||||
}
|
||||
|
||||
impl ExaBackend {
|
||||
/// A backend against Exa's public endpoint.
|
||||
pub fn new(api_key: String) -> Self {
|
||||
Self { api_key, base_url: "https://api.exa.ai/search".to_string() }
|
||||
}
|
||||
|
||||
/// Point the backend at a stand-in endpoint (tests, a proxy).
|
||||
pub fn with_base_url(api_key: String, base_url: impl Into<String>) -> Self {
|
||||
Self { api_key, base_url: base_url.into() }
|
||||
}
|
||||
|
||||
/// The body for one search.
|
||||
fn request_body(&self, query: &str, n: usize, options: &SearchOptions) -> ExaRequest {
|
||||
ExaRequest {
|
||||
query: query.to_string(),
|
||||
num_results: n.max(1),
|
||||
include_domains: options.include_domains.clone(),
|
||||
exclude_domains: options.exclude_domains.clone(),
|
||||
start_published_date: options.recency.map(|recency| recency.since()),
|
||||
contents: options.include_content.then_some(ExaContents {
|
||||
text: ExaText { max_characters: HIGHLIGHT_CHARS },
|
||||
highlights: ExaHighlights { num_sentences: 3, highlights_per_url: 2 },
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl SearchBackend for ExaBackend {
|
||||
async fn search(
|
||||
&self,
|
||||
query: &str,
|
||||
n: usize,
|
||||
options: &SearchOptions,
|
||||
) -> Result<Vec<SearchHit>, WebError> {
|
||||
let response = reqwest::Client::new()
|
||||
.post(&self.base_url)
|
||||
.header("Content-Type", "application/json")
|
||||
.header("x-api-key", &self.api_key)
|
||||
.json(&self.request_body(query, n, options))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| WebError::Network(e.to_string()))?;
|
||||
|
||||
let status = response.status();
|
||||
let body = response.text().await.map_err(|e| WebError::Network(e.to_string()))?;
|
||||
if !status.is_success() {
|
||||
return Err(WebError::Http(format!("Exa returned {status}: {}", body.trim())));
|
||||
}
|
||||
|
||||
let parsed: ExaResponse =
|
||||
serde_json::from_str(&body).map_err(|e| WebError::Parse(e.to_string()))?;
|
||||
Ok(parsed
|
||||
.results
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|result| SearchHit {
|
||||
title: result.title.clone().unwrap_or_default(),
|
||||
url: result.url.clone().unwrap_or_default(),
|
||||
snippet: result.snippet(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn body(options: &SearchOptions) -> serde_json::Value {
|
||||
let backend = ExaBackend::new("test-key".to_string());
|
||||
serde_json::to_value(backend.request_body("tokio", 3, options)).expect("serializes")
|
||||
}
|
||||
|
||||
/// Exa's schema is camelCase and it ignores what it does not recognize, so `num_results` was
|
||||
/// accepted, dropped, and answered with Exa's own default page size instead of the one asked
|
||||
/// for. Nothing about that shows up in the response.
|
||||
#[test]
|
||||
fn the_result_count_uses_the_field_name_exa_actually_reads() {
|
||||
let body = body(&SearchOptions::default());
|
||||
assert_eq!(body["numResults"], 3);
|
||||
assert!(body.get("num_results").is_none(), "{body}");
|
||||
}
|
||||
|
||||
/// A result carries no page text unless `contents` asks, so a backend that never asks returns
|
||||
/// bare links — while the tool that called it advertises passages.
|
||||
#[test]
|
||||
fn content_is_requested_only_when_the_caller_wants_it() {
|
||||
let with = body(&SearchOptions { include_content: true, ..Default::default() });
|
||||
assert_eq!(with["contents"]["text"]["maxCharacters"], HIGHLIGHT_CHARS);
|
||||
assert_eq!(with["contents"]["highlights"]["numSentences"], 3);
|
||||
assert!(body(&SearchOptions::default()).get("contents").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn domain_and_recency_filters_use_exas_spellings() {
|
||||
let body = body(&SearchOptions {
|
||||
include_domains: vec!["docs.rs".to_string()],
|
||||
exclude_domains: vec!["reddit.com".to_string()],
|
||||
recency: Some(crate::web::Recency::Month),
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(body["includeDomains"][0], "docs.rs");
|
||||
assert_eq!(body["excludeDomains"][0], "reddit.com");
|
||||
let since = body["startPublishedDate"].as_str().expect("a date");
|
||||
assert_eq!(since.len(), 10, "an ISO date, which is what Exa parses: {since}");
|
||||
}
|
||||
|
||||
/// Highlights are the matched passage and beat a clip of the page's opening, which is usually
|
||||
/// navigation. A page with neither returns nothing rather than a panic.
|
||||
#[test]
|
||||
fn the_matched_passage_outranks_a_clip_of_the_page() {
|
||||
let highlighted = ExaResult {
|
||||
title: None,
|
||||
url: None,
|
||||
text: Some("boilerplate".repeat(200)),
|
||||
highlights: vec!["the matched sentence".to_string()],
|
||||
};
|
||||
assert_eq!(highlighted.snippet(), "the matched sentence");
|
||||
|
||||
let clipped = ExaResult {
|
||||
title: None,
|
||||
url: None,
|
||||
text: Some("x".repeat(SNIPPET_CHARS + 50)),
|
||||
highlights: Vec::new(),
|
||||
};
|
||||
assert_eq!(
|
||||
clipped.snippet().chars().count(),
|
||||
SNIPPET_CHARS + 1,
|
||||
"clipped plus the ellipsis"
|
||||
);
|
||||
|
||||
let empty = ExaResult { title: None, url: None, text: None, highlights: Vec::new() };
|
||||
assert!(empty.snippet().is_empty());
|
||||
}
|
||||
}
|
||||
440
crates/luxe-tools/src/exa_mcp.rs
Normal file
440
crates/luxe-tools/src/exa_mcp.rs
Normal file
@@ -0,0 +1,440 @@
|
||||
//! Exa MCP — web search that works with no account, no key, and no configuration.
|
||||
//!
|
||||
//! Exa hosts a public MCP endpoint that answers `tools/call` over JSON-RPC with no credential.
|
||||
//! That is what makes search a *default capability* rather than a setup step: a user installs
|
||||
//! Luxe and the model can research immediately. A configured `BRAVE_API_KEY`/`TAVILY_API_KEY`/
|
||||
//! `EXA_API_KEY` still wins, since an explicit choice outranks the fallback, but having none does
|
||||
//! not mean having no web search.
|
||||
//!
|
||||
//! The endpoint also carries the whole feature set worth having: several query variations in one
|
||||
//! call, domain include/exclude, a published-after date, and extracted highlights. That last one is
|
||||
//! the point. Returning titles and snippets forces the model into one `web_fetch` per result — a
|
||||
//! research question becomes six round-trips. Returning the passages *with* the results answers it
|
||||
//! in one.
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::web::{SearchBackend, SearchHit, SearchOptions, WebError};
|
||||
|
||||
/// Exa's keyless MCP endpoint.
|
||||
const MCP_URL: &str = "https://mcp.exa.ai/mcp";
|
||||
|
||||
/// The MCP tool that exposes filters, extra queries, and highlight extraction.
|
||||
const ADVANCED_TOOL: &str = "web_search_advanced_exa";
|
||||
|
||||
/// Identifies Luxe to Exa, so the endpoint's operators can see who its traffic is.
|
||||
const SOURCE_HEADER: &str = "luxe";
|
||||
|
||||
/// Longest highlight payload requested per result. Enough to answer from, short enough that ten
|
||||
/// results stay inside a reasonable slice of the context window.
|
||||
const HIGHLIGHT_CHARS: u32 = 1_200;
|
||||
|
||||
/// Fallback clip when a result has no extracted highlights and only raw page text.
|
||||
const SNIPPET_CHARS: usize = 600;
|
||||
|
||||
/// Search backed by Exa's public MCP endpoint.
|
||||
pub struct ExaMcpBackend {
|
||||
url: String,
|
||||
}
|
||||
|
||||
impl Default for ExaMcpBackend {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ExaMcpBackend {
|
||||
pub fn new() -> Self {
|
||||
Self { url: MCP_URL.to_string() }
|
||||
}
|
||||
|
||||
/// Point the backend at a stand-in endpoint (tests, a self-hosted proxy).
|
||||
pub fn with_url(url: impl Into<String>) -> Self {
|
||||
Self { url: url.into() }
|
||||
}
|
||||
|
||||
/// Run one search, with options.
|
||||
pub async fn search_with(
|
||||
&self,
|
||||
query: &str,
|
||||
n: usize,
|
||||
options: &SearchOptions,
|
||||
) -> Result<Vec<SearchHit>, WebError> {
|
||||
let arguments = build_arguments(query, n, options);
|
||||
let body = serde_json::json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "tools/call",
|
||||
"params": { "name": ADVANCED_TOOL, "arguments": arguments },
|
||||
});
|
||||
|
||||
let response = reqwest::Client::new()
|
||||
.post(format!("{}?tools={ADVANCED_TOOL}", self.url))
|
||||
.header("Content-Type", "application/json")
|
||||
// The endpoint answers JSON-RPC as a single SSE `message` event, so both are accepted.
|
||||
.header("Accept", "application/json, text/event-stream")
|
||||
.header("x-exa-source", SOURCE_HEADER)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| WebError::Network(e.to_string()))?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(WebError::Backend(format!("exa mcp returned {}", response.status())));
|
||||
}
|
||||
let text = response.text().await.map_err(|e| WebError::Network(e.to_string()))?;
|
||||
parse_response(&text, n)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl SearchBackend for ExaMcpBackend {
|
||||
async fn search(
|
||||
&self,
|
||||
query: &str,
|
||||
n: usize,
|
||||
options: &SearchOptions,
|
||||
) -> Result<Vec<SearchHit>, WebError> {
|
||||
self.search_with(query, n, options).await
|
||||
}
|
||||
|
||||
/// Exa's advanced tool takes every phrasing as one call, which is the whole reason it is the
|
||||
/// default: one round-trip covers the angles a caller would otherwise pay for separately.
|
||||
fn batches_queries(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Map Luxe's options onto Exa's argument names.
|
||||
fn build_arguments(query: &str, n: usize, options: &SearchOptions) -> serde_json::Value {
|
||||
let mut arguments = serde_json::json!({
|
||||
"query": query,
|
||||
"numResults": n.clamp(1, 25),
|
||||
"type": "auto",
|
||||
});
|
||||
let map = arguments.as_object_mut().expect("object literal");
|
||||
if !options.also.is_empty() {
|
||||
map.insert("additionalQueries".into(), serde_json::json!(options.also));
|
||||
}
|
||||
if !options.include_domains.is_empty() {
|
||||
map.insert("includeDomains".into(), serde_json::json!(options.include_domains));
|
||||
}
|
||||
if !options.exclude_domains.is_empty() {
|
||||
map.insert("excludeDomains".into(), serde_json::json!(options.exclude_domains));
|
||||
}
|
||||
if let Some(recency) = options.recency {
|
||||
map.insert("startPublishedDate".into(), serde_json::json!(recency.since()));
|
||||
}
|
||||
if options.include_content {
|
||||
map.insert("enableHighlights".into(), serde_json::json!(true));
|
||||
map.insert("highlightsMaxCharacters".into(), serde_json::json!(HIGHLIGHT_CHARS));
|
||||
map.insert("highlightsQuery".into(), serde_json::json!(query));
|
||||
}
|
||||
arguments
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RpcEnvelope {
|
||||
#[serde(default)]
|
||||
result: Option<RpcResult>,
|
||||
#[serde(default)]
|
||||
error: Option<RpcError>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RpcResult {
|
||||
#[serde(default)]
|
||||
content: Vec<RpcContent>,
|
||||
#[serde(default, rename = "isError")]
|
||||
is_error: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RpcContent {
|
||||
#[serde(default)]
|
||||
text: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RpcError {
|
||||
#[serde(default)]
|
||||
message: String,
|
||||
}
|
||||
|
||||
/// Pull the JSON-RPC envelope out of a plain or SSE-framed body, then the hits out of that.
|
||||
fn parse_response(body: &str, n: usize) -> Result<Vec<SearchHit>, WebError> {
|
||||
let envelope = json_payload(body)
|
||||
.ok_or_else(|| WebError::Backend("exa mcp returned no JSON payload".to_string()))?;
|
||||
let envelope: RpcEnvelope = serde_json::from_str(&envelope)
|
||||
.map_err(|e| WebError::Backend(format!("exa mcp response not understood: {e}")))?;
|
||||
if let Some(error) = envelope.error {
|
||||
return Err(WebError::Backend(format!("exa mcp: {}", error.message)));
|
||||
}
|
||||
let result = envelope
|
||||
.result
|
||||
.ok_or_else(|| WebError::Backend("exa mcp returned no result".to_string()))?;
|
||||
if result.is_error {
|
||||
let detail = result.content.first().map(|c| c.text.as_str()).unwrap_or("unknown error");
|
||||
return Err(WebError::Backend(format!("exa mcp: {detail}")));
|
||||
}
|
||||
let joined = result.content.iter().map(|c| c.text.as_str()).collect::<Vec<_>>().join("\n");
|
||||
// The advanced tool answers with a JSON envelope; the basic one answers with prose. Try the
|
||||
// structured shape first and fall back, so either tool parses.
|
||||
let hits = parse_json_hits(&joined).unwrap_or_else(|| parse_hits(&joined));
|
||||
Ok(hits.into_iter().take(n).collect())
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ExaResults {
|
||||
results: Vec<ExaResult>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ExaResult {
|
||||
#[serde(default)]
|
||||
title: String,
|
||||
#[serde(default)]
|
||||
url: String,
|
||||
#[serde(default)]
|
||||
text: String,
|
||||
#[serde(default)]
|
||||
highlights: Vec<String>,
|
||||
}
|
||||
|
||||
/// Parse the advanced tool's JSON envelope, or `None` when the payload is not that shape.
|
||||
///
|
||||
/// Highlights are the passages that answer the query, so they lead. Falling back to the head of the
|
||||
/// page text keeps a result useful when highlight extraction returns nothing.
|
||||
fn parse_json_hits(text: &str) -> Option<Vec<SearchHit>> {
|
||||
let parsed: ExaResults = serde_json::from_str(text.trim()).ok()?;
|
||||
Some(
|
||||
parsed
|
||||
.results
|
||||
.into_iter()
|
||||
.filter(|result| !result.url.is_empty())
|
||||
.map(|result| {
|
||||
let snippet = if result.highlights.is_empty() {
|
||||
collapse(&result.text, SNIPPET_CHARS)
|
||||
} else {
|
||||
collapse(&result.highlights.join(" … "), HIGHLIGHT_CHARS as usize)
|
||||
};
|
||||
SearchHit { title: result.title, url: result.url, snippet }
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Squash whitespace and clip to `max` characters — page text arrives with heavy newline padding.
|
||||
fn collapse(text: &str, max: usize) -> String {
|
||||
let flat = text.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
match flat.char_indices().nth(max) {
|
||||
Some((at, _)) => format!("{}…", &flat[..at]),
|
||||
None => flat,
|
||||
}
|
||||
}
|
||||
|
||||
/// The JSON object in an SSE-framed (`data: {...}`) or bare body.
|
||||
fn json_payload(body: &str) -> Option<String> {
|
||||
for line in body.lines() {
|
||||
let candidate = line.strip_prefix("data:").unwrap_or(line).trim();
|
||||
if candidate.starts_with('{') {
|
||||
return Some(candidate.to_string());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Split Exa's `Title:` / `URL:` / `Highlights:` text blocks into normalized hits.
|
||||
///
|
||||
/// The endpoint returns model-readable prose rather than structured results, so this is a parse of
|
||||
/// a documented shape: a `Title:` line opens each record and `URL:` identifies it. Anything else
|
||||
/// under a record becomes its snippet, which is where the highlights land.
|
||||
fn parse_hits(text: &str) -> Vec<SearchHit> {
|
||||
let mut hits: Vec<SearchHit> = Vec::new();
|
||||
let mut snippet = String::new();
|
||||
for line in text.lines() {
|
||||
let trimmed = line.trim();
|
||||
if let Some(title) = trimmed.strip_prefix("Title:") {
|
||||
flush(&mut hits, &mut snippet);
|
||||
hits.push(SearchHit {
|
||||
title: title.trim().to_string(),
|
||||
url: String::new(),
|
||||
snippet: String::new(),
|
||||
});
|
||||
} else if let Some(url) = trimmed.strip_prefix("URL:") {
|
||||
if let Some(last) = hits.last_mut() {
|
||||
last.url = url.trim().to_string();
|
||||
}
|
||||
} else if !trimmed.is_empty()
|
||||
&& !trimmed.starts_with("Published:")
|
||||
&& !trimmed.starts_with("Author:")
|
||||
&& trimmed != "Highlights:"
|
||||
&& trimmed != "..."
|
||||
{
|
||||
if !snippet.is_empty() {
|
||||
snippet.push(' ');
|
||||
}
|
||||
snippet.push_str(trimmed);
|
||||
}
|
||||
}
|
||||
flush(&mut hits, &mut snippet);
|
||||
hits.retain(|hit| !hit.url.is_empty());
|
||||
hits
|
||||
}
|
||||
|
||||
fn flush(hits: &mut [SearchHit], snippet: &mut String) {
|
||||
if let Some(last) = hits.last_mut() {
|
||||
last.snippet = std::mem::take(snippet);
|
||||
} else {
|
||||
snippet.clear();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The exact shape the live endpoint returned during development.
|
||||
const SAMPLE: &str = "event: message\n\
|
||||
data: {\"result\":{\"content\":[{\"type\":\"text\",\"text\":\"Title: select in tokio - Rust\\nURL: https://docs.rs/tokio/latest/tokio/macro.select.html\\nPublished: N/A\\nAuthor: N/A\\nHighlights:\\n## Cancellation safety\\n...\\nCancellation safety describes what happens when a future is dropped.\\nTitle: Second Result\\nURL: https://example.com/two\\nHighlights:\\nSomething else entirely.\"}]}}\n";
|
||||
|
||||
#[test]
|
||||
fn an_sse_framed_response_parses_into_hits_with_content() {
|
||||
let hits = parse_response(SAMPLE, 10).expect("parses");
|
||||
assert_eq!(hits.len(), 2);
|
||||
assert_eq!(hits[0].title, "select in tokio - Rust");
|
||||
assert_eq!(hits[0].url, "https://docs.rs/tokio/latest/tokio/macro.select.html");
|
||||
assert!(
|
||||
hits[0].snippet.contains("Cancellation safety describes"),
|
||||
"the extracted passage rides along, so no follow-up fetch is needed: {:?}",
|
||||
hits[0].snippet
|
||||
);
|
||||
assert!(!hits[0].snippet.contains("N/A"), "metadata noise is dropped");
|
||||
assert_eq!(hits[1].url, "https://example.com/two");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_result_count_is_honored() {
|
||||
assert_eq!(parse_response(SAMPLE, 1).expect("parses").len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_json_body_parses_too() {
|
||||
let bare =
|
||||
r#"{"result":{"content":[{"type":"text","text":"Title: A\nURL: https://a.test"}]}}"#;
|
||||
assert_eq!(parse_response(bare, 5).expect("parses")[0].url, "https://a.test");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_rpc_error_surfaces_instead_of_an_empty_result() {
|
||||
let body = r#"{"error":{"code":-32602,"message":"bad arguments"}}"#;
|
||||
let error = parse_response(body, 5).expect_err("must not look like zero results");
|
||||
assert!(error.to_string().contains("bad arguments"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tool_level_error_surfaces_too() {
|
||||
let body =
|
||||
r#"{"result":{"isError":true,"content":[{"type":"text","text":"rate limited"}]}}"#;
|
||||
let error = parse_response(body, 5).expect_err("isError must not be silently empty");
|
||||
assert!(error.to_string().contains("rate limited"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_is_an_error_not_a_panic() {
|
||||
assert!(parse_response("not json at all", 5).is_err());
|
||||
assert!(parse_response("", 5).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_map_onto_exas_argument_names() {
|
||||
let options = SearchOptions {
|
||||
also: vec!["second phrasing".into()],
|
||||
include_domains: vec!["arxiv.org".into()],
|
||||
exclude_domains: vec!["spam.example".into()],
|
||||
recency: Some(crate::web::Recency::Month),
|
||||
include_content: true,
|
||||
};
|
||||
let args = build_arguments("tokio cancellation", 7, &options);
|
||||
|
||||
assert_eq!(args["query"], "tokio cancellation");
|
||||
assert_eq!(args["numResults"], 7);
|
||||
assert_eq!(args["additionalQueries"][0], "second phrasing");
|
||||
assert_eq!(args["includeDomains"][0], "arxiv.org");
|
||||
assert_eq!(args["excludeDomains"][0], "spam.example");
|
||||
assert_eq!(args["startPublishedDate"].as_str().expect("a date").len(), 10);
|
||||
assert_eq!(args["enableHighlights"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_stay_off_the_wire_and_the_count_is_clamped() {
|
||||
let args = build_arguments("q", 999, &SearchOptions::default());
|
||||
assert_eq!(args["numResults"], 25, "clamped to Exa's practical ceiling");
|
||||
for absent in [
|
||||
"additionalQueries",
|
||||
"includeDomains",
|
||||
"excludeDomains",
|
||||
"startPublishedDate",
|
||||
"enableHighlights",
|
||||
] {
|
||||
assert!(args.get(absent).is_none(), "{absent} must not be sent by default");
|
||||
}
|
||||
}
|
||||
|
||||
/// The advanced tool answers with a JSON envelope, not the basic tool's prose. Parsing only the
|
||||
/// prose form meant every advanced search reported "No results" while the endpoint was
|
||||
/// returning perfectly good ones.
|
||||
#[test]
|
||||
fn the_advanced_tools_json_envelope_parses() {
|
||||
let inner = serde_json::json!({
|
||||
"requestId": "abc",
|
||||
"results": [
|
||||
{
|
||||
"id": "https://tokio.rs/x",
|
||||
"url": "https://tokio.rs/x",
|
||||
"title": "Select | Tokio",
|
||||
"text": "Select | Tokio\n\n# Select\n\nSo far...",
|
||||
"highlights": ["Futures can implement Drop to clean up.", "oneshot is cancel safe."],
|
||||
"publishedDate": "2026-03-18T00:00:00.000Z"
|
||||
},
|
||||
{ "url": "", "title": "dropped: no url" }
|
||||
]
|
||||
})
|
||||
.to_string();
|
||||
let body = serde_json::json!({
|
||||
"result": { "content": [{ "type": "text", "text": inner }] }
|
||||
})
|
||||
.to_string();
|
||||
|
||||
let hits = parse_response(&body, 10).expect("parses");
|
||||
assert_eq!(hits.len(), 1, "a result with no url is not a result");
|
||||
assert_eq!(hits[0].title, "Select | Tokio");
|
||||
assert_eq!(hits[0].url, "https://tokio.rs/x");
|
||||
assert!(hits[0].snippet.contains("cancel safe"), "highlights lead: {:?}", hits[0].snippet);
|
||||
assert!(!hits[0].snippet.contains('\n'), "whitespace is collapsed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_result_without_highlights_falls_back_to_its_text() {
|
||||
let inner = serde_json::json!({
|
||||
"results": [{ "url": "https://a.test", "title": "A", "text": " body text here " }]
|
||||
})
|
||||
.to_string();
|
||||
let body = serde_json::json!({ "result": { "content": [{ "text": inner }] } }).to_string();
|
||||
let hits = parse_response(&body, 5).expect("parses");
|
||||
assert_eq!(hits[0].snippet, "body text here");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_snippet_is_clipped() {
|
||||
let long = "word ".repeat(400);
|
||||
let inner = serde_json::json!({
|
||||
"results": [{ "url": "https://a.test", "title": "A", "text": long }]
|
||||
})
|
||||
.to_string();
|
||||
let body = serde_json::json!({ "result": { "content": [{ "text": inner }] } }).to_string();
|
||||
let hits = parse_response(&body, 5).expect("parses");
|
||||
assert!(hits[0].snippet.chars().count() <= SNIPPET_CHARS + 1, "clipped");
|
||||
assert!(hits[0].snippet.ends_with('…'));
|
||||
}
|
||||
}
|
||||
275
crates/luxe-tools/src/firecrawl.rs
Normal file
275
crates/luxe-tools/src/firecrawl.rs
Normal file
@@ -0,0 +1,275 @@
|
||||
//! Firecrawl — a search index and, more usefully here, a renderer of pages that refuse to be read.
|
||||
//!
|
||||
//! It earns a place for the second of those. `web_fetch` already retries a refusal behind a
|
||||
//! browser user-agent, which gets past a check on the header and nothing more; a page that builds
|
||||
//! itself in JavaScript, or sits behind a real bot check, comes back as an empty shell or a
|
||||
//! challenge. Firecrawl runs an actual browser and returns the rendered article as markdown, so it
|
||||
//! is the last thing `web_fetch` tries before giving up — and only when a key says it may.
|
||||
//!
|
||||
//! Search is the same option set as everyone else's, with domain filters and a `tbs` recency
|
||||
//! window that Firecrawl passes upstream.
|
||||
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::web::{SearchBackend, SearchHit, SearchOptions, WebError};
|
||||
|
||||
/// Firecrawl's API root, without the endpoint segment.
|
||||
const API_ROOT: &str = "https://api.firecrawl.dev/v2";
|
||||
|
||||
/// How long Firecrawl may spend rendering one page, in milliseconds. Under `web_fetch`'s own
|
||||
/// network bound, so the tool reports a Firecrawl timeout rather than being killed mid-retry.
|
||||
const SCRAPE_TIMEOUT_MS: u32 = 45_000;
|
||||
|
||||
/// Firecrawl search request.
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct SearchRequest {
|
||||
query: String,
|
||||
limit: usize,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
include_domains: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
exclude_domains: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
tbs: Option<&'static str>,
|
||||
}
|
||||
|
||||
/// Firecrawl wraps every payload in `{success, data}`.
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SearchResponse {
|
||||
#[serde(default)]
|
||||
data: Option<SearchData>,
|
||||
#[serde(default)]
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SearchData {
|
||||
#[serde(default)]
|
||||
web: Vec<WebResult>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct WebResult {
|
||||
title: Option<String>,
|
||||
url: Option<String>,
|
||||
description: Option<String>,
|
||||
}
|
||||
|
||||
/// Firecrawl scrape request — markdown of the article, not the chrome around it.
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ScrapeRequest<'a> {
|
||||
url: &'a str,
|
||||
formats: [&'static str; 1],
|
||||
only_main_content: bool,
|
||||
timeout: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ScrapeResponse {
|
||||
#[serde(default)]
|
||||
data: Option<ScrapeData>,
|
||||
#[serde(default)]
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ScrapeData {
|
||||
#[serde(default)]
|
||||
markdown: Option<String>,
|
||||
#[serde(default)]
|
||||
metadata: Option<ScrapeMetadata>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ScrapeMetadata {
|
||||
#[serde(default)]
|
||||
title: Option<String>,
|
||||
/// What the *origin* answered. Firecrawl reports its own call as 200 and puts the upstream
|
||||
/// status here, so a 404 arrives looking like a success with a stub page attached.
|
||||
#[serde(default)]
|
||||
status_code: Option<u16>,
|
||||
}
|
||||
|
||||
/// Firecrawl backend: web search, and a browser for pages that need one.
|
||||
pub struct FirecrawlBackend {
|
||||
api_key: String,
|
||||
api_root: String,
|
||||
}
|
||||
|
||||
impl FirecrawlBackend {
|
||||
/// A backend against Firecrawl's public API.
|
||||
pub fn new(api_key: String) -> Self {
|
||||
Self { api_key, api_root: API_ROOT.to_string() }
|
||||
}
|
||||
|
||||
/// Point the backend at a stand-in endpoint (tests, a self-hosted Firecrawl).
|
||||
pub fn with_api_root(api_key: String, api_root: impl Into<String>) -> Self {
|
||||
Self { api_key, api_root: api_root.into() }
|
||||
}
|
||||
|
||||
fn endpoint(&self, path: &str) -> String {
|
||||
format!("{}/{path}", self.api_root.trim_end_matches('/'))
|
||||
}
|
||||
|
||||
/// The body for one search.
|
||||
fn search_body(&self, query: &str, n: usize, options: &SearchOptions) -> SearchRequest {
|
||||
SearchRequest {
|
||||
query: query.to_string(),
|
||||
limit: n.max(1),
|
||||
include_domains: options.include_domains.clone(),
|
||||
exclude_domains: options.exclude_domains.clone(),
|
||||
tbs: options.recency.map(|recency| recency.tbs()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Render `url` in a real browser and return the article as markdown.
|
||||
///
|
||||
/// An upstream 404 or 403 is an error here even though Firecrawl answered 200: the caller is
|
||||
/// deciding whether the page was readable, and a stub saying "Not Found" would otherwise be
|
||||
/// reported as the page's content.
|
||||
pub async fn scrape(&self, url: &str) -> Result<String, WebError> {
|
||||
let body = ScrapeRequest {
|
||||
url,
|
||||
formats: ["markdown"],
|
||||
only_main_content: true,
|
||||
timeout: SCRAPE_TIMEOUT_MS,
|
||||
};
|
||||
let response = reqwest::Client::new()
|
||||
.post(self.endpoint("scrape"))
|
||||
.header("Content-Type", "application/json")
|
||||
.bearer_auth(&self.api_key)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| WebError::Network(e.to_string()))?;
|
||||
|
||||
let parsed: ScrapeResponse = decode(response, "scrape").await?;
|
||||
if let Some(error) = parsed.error {
|
||||
return Err(WebError::Backend(format!("Firecrawl: {error}")));
|
||||
}
|
||||
let data =
|
||||
parsed.data.ok_or_else(|| WebError::Parse("Firecrawl returned no page".into()))?;
|
||||
let upstream = data.metadata.as_ref().and_then(|meta| meta.status_code).unwrap_or(200);
|
||||
if !(200..300).contains(&upstream) {
|
||||
return Err(WebError::Http(format!("the page itself answered {upstream}")));
|
||||
}
|
||||
let markdown = data.markdown.unwrap_or_default();
|
||||
if markdown.trim().is_empty() {
|
||||
return Err(WebError::Parse("Firecrawl rendered the page but found no text".into()));
|
||||
}
|
||||
Ok(
|
||||
match data.metadata.and_then(|meta| meta.title).filter(|title| !title.trim().is_empty())
|
||||
{
|
||||
Some(title) => format!("# {}\n\n{markdown}", title.trim()),
|
||||
None => markdown,
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a Firecrawl response, turning a non-2xx into an error that names what it was doing.
|
||||
async fn decode<T: serde::de::DeserializeOwned>(
|
||||
response: reqwest::Response,
|
||||
what: &str,
|
||||
) -> Result<T, WebError> {
|
||||
let status = response.status();
|
||||
let body = response.text().await.map_err(|e| WebError::Network(e.to_string()))?;
|
||||
if !status.is_success() {
|
||||
return Err(WebError::Http(format!("Firecrawl {what} returned {status}: {}", body.trim())));
|
||||
}
|
||||
serde_json::from_str(&body).map_err(|e| WebError::Parse(e.to_string()))
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl SearchBackend for FirecrawlBackend {
|
||||
async fn search(
|
||||
&self,
|
||||
query: &str,
|
||||
n: usize,
|
||||
options: &SearchOptions,
|
||||
) -> Result<Vec<SearchHit>, WebError> {
|
||||
let response = reqwest::Client::new()
|
||||
.post(self.endpoint("search"))
|
||||
.header("Content-Type", "application/json")
|
||||
.bearer_auth(&self.api_key)
|
||||
.json(&self.search_body(query, n, options))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| WebError::Network(e.to_string()))?;
|
||||
|
||||
let parsed: SearchResponse = decode(response, "search").await?;
|
||||
if let Some(error) = parsed.error {
|
||||
return Err(WebError::Backend(format!("Firecrawl: {error}")));
|
||||
}
|
||||
Ok(parsed
|
||||
.data
|
||||
.map(|data| data.web)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|result| SearchHit {
|
||||
title: result.title.unwrap_or_default(),
|
||||
url: result.url.unwrap_or_default(),
|
||||
snippet: result.description.unwrap_or_default(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn backend() -> FirecrawlBackend {
|
||||
FirecrawlBackend::new("fc-test".to_string())
|
||||
}
|
||||
|
||||
fn body(options: &SearchOptions) -> serde_json::Value {
|
||||
serde_json::to_value(backend().search_body("tokio", 3, options)).expect("serializes")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_advertised_filters_reach_the_request_in_firecrawls_spellings() {
|
||||
let body = body(&SearchOptions {
|
||||
include_domains: vec!["docs.rs".to_string()],
|
||||
exclude_domains: vec!["reddit.com".to_string()],
|
||||
recency: Some(crate::web::Recency::Week),
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(body["query"], "tokio");
|
||||
assert_eq!(body["limit"], 3);
|
||||
assert_eq!(body["includeDomains"][0], "docs.rs");
|
||||
assert_eq!(body["excludeDomains"][0], "reddit.com");
|
||||
assert_eq!(body["tbs"], "qdr:w");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unset_filters_are_left_out_of_the_body() {
|
||||
let body = body(&SearchOptions::default());
|
||||
assert!(body.get("includeDomains").is_none());
|
||||
assert!(body.get("excludeDomains").is_none());
|
||||
assert!(body.get("tbs").is_none());
|
||||
}
|
||||
|
||||
/// Firecrawl's payload is camelCase throughout, and a field name that misses reads as absent
|
||||
/// rather than as an error — which turned an upstream 404 back into a page.
|
||||
#[test]
|
||||
fn the_upstream_status_is_read_off_the_field_firecrawl_actually_sends() {
|
||||
let metadata: ScrapeMetadata =
|
||||
serde_json::from_str(r#"{"title":"Not Found","statusCode":404}"#).expect("parses");
|
||||
assert_eq!(metadata.status_code, Some(404));
|
||||
assert_eq!(metadata.title.as_deref(), Some("Not Found"));
|
||||
}
|
||||
|
||||
/// A self-hosted Firecrawl is reached by root, and the two endpoints hang off it.
|
||||
#[test]
|
||||
fn endpoints_hang_off_a_configurable_root() {
|
||||
let hosted = FirecrawlBackend::with_api_root("k".into(), "http://localhost:3002/v2/");
|
||||
assert_eq!(hosted.endpoint("search"), "http://localhost:3002/v2/search");
|
||||
assert_eq!(backend().endpoint("scrape"), "https://api.firecrawl.dev/v2/scrape");
|
||||
}
|
||||
}
|
||||
392
crates/luxe-tools/src/git.rs
Normal file
392
crates/luxe-tools/src/git.rs
Normal file
@@ -0,0 +1,392 @@
|
||||
//! Git — the repository operations the schema lists, and `gh`-backed pull requests, issues and CI
|
||||
//! checks.
|
||||
//!
|
||||
//! One `action` picks the operation and `args` carries git's own flags for it. A commit message is
|
||||
//! its own argument rather than another flag in that list, because the one thing a commit cannot be
|
||||
//! spelled without should not be the thing a caller has to guess at. [`args`] does the accepting;
|
||||
//! this module plans each action and tells its answer, and `run` does the running.
|
||||
|
||||
mod args;
|
||||
mod checks;
|
||||
mod failure;
|
||||
mod run;
|
||||
|
||||
use args::{commit_args, gh_args, is_pr_create, stash_args};
|
||||
use async_trait::async_trait;
|
||||
use failure::explain_gh_failure;
|
||||
use luxe_core::provider::ToolSchema;
|
||||
use luxe_core::tool::{Tool, ToolContext, ToolResultData};
|
||||
use std::path::Path;
|
||||
|
||||
/// Max lines of `gh pr` output returned before the result is capped.
|
||||
///
|
||||
/// `pr list` in a busy repository is unbounded, and a `pr view` carries a whole PR body written by
|
||||
/// somebody who likes templates. Neither is worth the context it would otherwise take.
|
||||
const GH_OUTPUT_MAX_LINES: usize = 120;
|
||||
|
||||
/// Max `git diff` lines returned before the result is capped (the guided review is the full view).
|
||||
const GIT_DIFF_MAX_LINES: usize = 400;
|
||||
/// Max `git log` lines returned before the result is capped.
|
||||
const GIT_LOG_MAX_LINES: usize = 200;
|
||||
|
||||
/// Commits a bare `log` shows, most recent first.
|
||||
const LOG_DEFAULT_COUNT: usize = 10;
|
||||
|
||||
/// Git: the actions the schema lists, with `gh` behind the pull request, issue and CI ones.
|
||||
///
|
||||
/// Stateless: whether `gh` can run is a question about the machine, asked at the call, not a flag
|
||||
/// held on the tool.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct GitTool;
|
||||
|
||||
impl GitTool {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for GitTool {
|
||||
fn name(&self) -> &str {
|
||||
"git"
|
||||
}
|
||||
|
||||
fn schema(&self) -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: "git".to_string(),
|
||||
description: "Git repository operations with bounded output: status, diff, log, \
|
||||
show (a commit, or a file at a revision: [\"<rev>:<path>\"]), add, \
|
||||
commit, branch, checkout, stash, `gh`-backed pull requests and issues \
|
||||
(reading one with its comments is `issue` with [\"view\", \"12\", \
|
||||
\"--comments\"]), and \
|
||||
`checks`: why CI fails on the branch's pull request, with each failing \
|
||||
step's log tail. A commit's message goes in `message`, not `args`. Use \
|
||||
`bash` for git subcommands this does not cover."
|
||||
.to_string(),
|
||||
parameters: serde_json::json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["status", "diff", "log", "show", "add", "commit", "branch", "checkout", "stash", "pr", "issue", "checks"],
|
||||
"description": "Git action to perform"
|
||||
},
|
||||
"message": {
|
||||
"type": "string",
|
||||
"description": "Commit message, subject line first. Required for `commit` unless `args` already say where the message comes from (--amend --no-edit, -F, -C, --fixup)."
|
||||
},
|
||||
"args": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "What the action operates on: paths for `add`, a branch for `checkout`, a subcommand for `stash`, a `gh pr` command line for `pr` (e.g. [\"create\", \"--title\", \"...\", \"--body\", \"...\"]; the branch is pushed for you if it has no upstream), a `gh issue` command line for `issue` (e.g. [\"view\", \"12\", \"--comments\"]), a PR number for `checks` (default: this branch's), otherwise git's own flags. Never the commit message."
|
||||
}
|
||||
},
|
||||
"required": ["action"]
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(&self, args: serde_json::Value, cx: &ToolContext) -> ToolResultData {
|
||||
let action = match args.get("action") {
|
||||
Some(v) => v.as_str().unwrap_or(""),
|
||||
None => {
|
||||
return ToolResultData::error("Error: 'action' argument is required");
|
||||
}
|
||||
};
|
||||
let Some(action) = GitAction::parse(action) else {
|
||||
return ToolResultData::error(format!(
|
||||
"Unknown action: {action}. Valid actions: {}",
|
||||
GitAction::ALL.map(GitAction::name).join(", ")
|
||||
));
|
||||
};
|
||||
let request: Vec<String> = args
|
||||
.get("args")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|arr| arr.iter().filter_map(|v| v.as_str().map(String::from)).collect())
|
||||
.unwrap_or_default();
|
||||
|
||||
match action {
|
||||
GitAction::Checks => {
|
||||
let github = luxe_core::github::GhCli::new();
|
||||
match checks::checks(&github, &cx.cwd, &request).await {
|
||||
Ok(report) => ToolResultData::text(report),
|
||||
Err(reason) => ToolResultData::error(format!("Error: {reason}")),
|
||||
}
|
||||
}
|
||||
GitAction::Pr | GitAction::Issue => self.run_github(action, &request, &cx.cwd).await,
|
||||
_ => {
|
||||
let plan = match plan(action, &args, &request) {
|
||||
Ok(plan) => plan,
|
||||
Err(refusal) => return refusal,
|
||||
};
|
||||
let argv: Vec<&str> = plan.argv.iter().map(String::as_str).collect();
|
||||
finish(action, self.run_git(&cx.cwd, &argv).await, plan.shape)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GitTool {
|
||||
/// `pr` and `issue`: the `gh` command line, with the branch published first when a pull request
|
||||
/// is being opened.
|
||||
async fn run_github(
|
||||
&self,
|
||||
action: GitAction,
|
||||
request: &[String],
|
||||
cwd: &Path,
|
||||
) -> ToolResultData {
|
||||
// Asked of the machine, not of a config flag: `gh` is an external program the user
|
||||
// installs, the same as a language server or a debug adapter, and the useful answer
|
||||
// names it rather than an internal switch.
|
||||
if !luxe_core::program::is_available("gh") {
|
||||
return ToolResultData::error(
|
||||
"Error: the GitHub CLI (`gh`) is not on PATH. Install it and run \
|
||||
`gh auth login`, or drive it through `bash` yourself.",
|
||||
);
|
||||
}
|
||||
|
||||
// Opening a pull request needs a published branch; reading about one does not.
|
||||
let mut preamble = None;
|
||||
if action == GitAction::Pr && is_pr_create(request) {
|
||||
match self.ready_branch_for_pr(cwd).await {
|
||||
Ok(note) => preamble = note,
|
||||
Err(e) => {
|
||||
return ToolResultData::error(format!("Cannot open a pull request: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let args = gh_args(action.name(), request);
|
||||
let refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
|
||||
match self.run_gh(cwd, &refs).await {
|
||||
Ok(output) => {
|
||||
let body = crate::output_limit::cap_lines(
|
||||
output.trim(),
|
||||
GH_OUTPUT_MAX_LINES,
|
||||
"lines of gh output",
|
||||
"narrow it with gh's own flags (--limit, --json)",
|
||||
);
|
||||
let text = match preamble {
|
||||
Some(note) => format!("{note}\n{body}"),
|
||||
None => body,
|
||||
};
|
||||
ToolResultData::text(or_else_message(&text, "gh reported nothing"))
|
||||
}
|
||||
Err(e) => {
|
||||
let reported = e.to_string();
|
||||
let name = action.name();
|
||||
ToolResultData::error(match explain_gh_failure(&reported) {
|
||||
Some(explanation) => format!("gh {name} failed: {explanation}"),
|
||||
None => format!("gh {name} failed: {reported}"),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the tool can be asked to do: the `action` enum of the schema, and nothing else.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum GitAction {
|
||||
Status,
|
||||
Diff,
|
||||
Log,
|
||||
Show,
|
||||
Add,
|
||||
Commit,
|
||||
Branch,
|
||||
Checkout,
|
||||
Stash,
|
||||
Pr,
|
||||
Issue,
|
||||
Checks,
|
||||
}
|
||||
|
||||
impl GitAction {
|
||||
/// Every action, in the order the schema lists them.
|
||||
const ALL: [Self; 12] = [
|
||||
Self::Status,
|
||||
Self::Diff,
|
||||
Self::Log,
|
||||
Self::Show,
|
||||
Self::Add,
|
||||
Self::Commit,
|
||||
Self::Branch,
|
||||
Self::Checkout,
|
||||
Self::Stash,
|
||||
Self::Pr,
|
||||
Self::Issue,
|
||||
Self::Checks,
|
||||
];
|
||||
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Status => "status",
|
||||
Self::Diff => "diff",
|
||||
Self::Log => "log",
|
||||
Self::Show => "show",
|
||||
Self::Add => "add",
|
||||
Self::Commit => "commit",
|
||||
Self::Branch => "branch",
|
||||
Self::Checkout => "checkout",
|
||||
Self::Stash => "stash",
|
||||
Self::Pr => "pr",
|
||||
Self::Issue => "issue",
|
||||
Self::Checks => "checks",
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(raw: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|action| action.name() == raw)
|
||||
}
|
||||
}
|
||||
|
||||
/// One git invocation and how its answer is told.
|
||||
struct Plan {
|
||||
argv: Vec<String>,
|
||||
shape: Shape,
|
||||
}
|
||||
|
||||
/// How a git command's stdout becomes the result.
|
||||
enum Shape {
|
||||
/// As git printed it
|
||||
Raw,
|
||||
/// Trimmed
|
||||
Trimmed,
|
||||
/// As printed, or this sentence when there was nothing
|
||||
OrMessage(&'static str),
|
||||
/// A fixed sentence: git said nothing worth reading
|
||||
Said(&'static str),
|
||||
/// Capped at `max` lines, naming what was counted and what to do about it
|
||||
Capped { max: usize, noun: &'static str, hint: &'static str, empty: Option<&'static str> },
|
||||
/// The default `log`, which asked for one more than it shows so it can say whether history
|
||||
/// goes on
|
||||
LogDefault,
|
||||
}
|
||||
|
||||
/// The git command line for `action`, or the refusal a caller should see instead.
|
||||
///
|
||||
/// `request` is what the caller put in `args`. Every action here is a git subcommand; `pr`, `issue`
|
||||
/// and `checks` go to `gh` and have their own paths.
|
||||
fn plan(
|
||||
action: GitAction,
|
||||
args: &serde_json::Value,
|
||||
request: &[String],
|
||||
) -> Result<Plan, ToolResultData> {
|
||||
let with = |subcommand: &str, default: &[&str]| {
|
||||
let mut argv = vec![subcommand.to_string()];
|
||||
if request.is_empty() {
|
||||
argv.extend(default.iter().map(|arg| arg.to_string()));
|
||||
} else {
|
||||
argv.extend(request.iter().cloned());
|
||||
}
|
||||
argv
|
||||
};
|
||||
let needs = |what: &str| ToolResultData::error(format!("Error: 'args' must include {what}"));
|
||||
let (argv, shape) = match action {
|
||||
GitAction::Status => (
|
||||
vec!["status".to_string(), "--short".to_string()],
|
||||
Shape::OrMessage("clean — nothing to commit, working tree clean"),
|
||||
),
|
||||
GitAction::Diff => (
|
||||
with("diff", &["--unified=3"]),
|
||||
Shape::Capped {
|
||||
max: GIT_DIFF_MAX_LINES,
|
||||
noun: "diff lines",
|
||||
hint:
|
||||
"Pass a path to scope the diff, or `--stat` first to see which files changed.",
|
||||
empty: Some("no changes — the diff is empty"),
|
||||
},
|
||||
),
|
||||
GitAction::Show => (
|
||||
with("show", &[]),
|
||||
Shape::Capped {
|
||||
max: GIT_DIFF_MAX_LINES,
|
||||
noun: "lines",
|
||||
hint: "Pass `--stat` to see which files a commit changed, then show one \
|
||||
path at a time (`<rev> -- <path>`, or `<rev>:<path>` for the whole \
|
||||
file).",
|
||||
empty: None,
|
||||
},
|
||||
),
|
||||
GitAction::Log if request.is_empty() => {
|
||||
(vec!["log".to_string(), "--oneline".to_string(), "-11".to_string()], Shape::LogDefault)
|
||||
}
|
||||
GitAction::Log => (
|
||||
with("log", &[]),
|
||||
Shape::Capped {
|
||||
max: GIT_LOG_MAX_LINES,
|
||||
noun: "log lines",
|
||||
hint: "Pass a narrower range or -n <count> to see fewer commits.",
|
||||
empty: Some("no commits matched"),
|
||||
},
|
||||
),
|
||||
GitAction::Add if request.is_empty() => return Err(needs("file paths to add")),
|
||||
GitAction::Add => (with("add", &[]), Shape::Said("Files staged.")),
|
||||
GitAction::Commit => match commit_args(args, request) {
|
||||
Ok(argv) => (argv, Shape::Trimmed),
|
||||
Err(error) => return Err(ToolResultData::error(error.message())),
|
||||
},
|
||||
GitAction::Branch => (with("branch", &["-a"]), Shape::Raw),
|
||||
GitAction::Checkout if request.is_empty() => return Err(needs("branch name")),
|
||||
GitAction::Checkout => (with("checkout", &[]), Shape::Trimmed),
|
||||
GitAction::Stash => (stash_args(request), Shape::Trimmed),
|
||||
GitAction::Pr | GitAction::Issue | GitAction::Checks => {
|
||||
return Err(ToolResultData::error(format!(
|
||||
"Error: `{}` goes to `gh`, not to git",
|
||||
action.name()
|
||||
)))
|
||||
}
|
||||
};
|
||||
Ok(Plan { argv, shape })
|
||||
}
|
||||
|
||||
/// The result of running a planned command: its output told as its shape says, or its failure.
|
||||
fn finish(action: GitAction, ran: anyhow::Result<String>, shape: Shape) -> ToolResultData {
|
||||
match ran {
|
||||
Ok(output) => ToolResultData::text(shape.tell(&output)),
|
||||
Err(error) => ToolResultData::error(format!("Git {} failed: {error}", action.name())),
|
||||
}
|
||||
}
|
||||
|
||||
impl Shape {
|
||||
fn tell(&self, output: &str) -> String {
|
||||
match self {
|
||||
Self::Raw => output.to_string(),
|
||||
Self::Trimmed => output.trim().to_string(),
|
||||
Self::OrMessage(fallback) => or_else_message(output, fallback),
|
||||
Self::Said(text) => (*text).to_string(),
|
||||
Self::Capped { max, noun, hint, empty } => match empty {
|
||||
Some(message) if output.trim().is_empty() => (*message).to_string(),
|
||||
_ => crate::output_limit::cap_lines(output, *max, noun, hint),
|
||||
},
|
||||
Self::LogDefault if output.trim().is_empty() => "no commits matched".to_string(),
|
||||
Self::LogDefault if output.lines().count() > LOG_DEFAULT_COUNT => {
|
||||
let shown: Vec<&str> = output.lines().take(LOG_DEFAULT_COUNT).collect();
|
||||
format!(
|
||||
"{}\n… older commits not shown. Pass `-n <count>`, a range such as \
|
||||
`main..HEAD`, or a path for more.",
|
||||
shown.join("\n")
|
||||
)
|
||||
}
|
||||
Self::LogDefault => crate::output_limit::cap_lines(
|
||||
output,
|
||||
GIT_LOG_MAX_LINES,
|
||||
"log lines",
|
||||
"Pass a narrower range or -n <count> to see fewer commits.",
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Use `fallback` when a git command produced nothing: an empty tool result reads as "did this
|
||||
/// even run?" in a transcript.
|
||||
fn or_else_message(output: &str, fallback: &str) -> String {
|
||||
if output.trim().is_empty() {
|
||||
fallback.to_string()
|
||||
} else {
|
||||
output.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
386
crates/luxe-tools/src/git/args.rs
Normal file
386
crates/luxe-tools/src/git/args.rs
Normal file
@@ -0,0 +1,386 @@
|
||||
//! Argument normalization for `git commit` — permissive at the edge, strict in the core.
|
||||
//!
|
||||
//! The tool's real invariant is that git receives a message from somewhere. *Where the caller put
|
||||
//! it* is not one: a model that sends `args: ["-m", "…"]` instead of `message` has said what it
|
||||
//! means, and refusing it costs failed calls and a fallback to `bash`.
|
||||
//!
|
||||
//! So: lift the message out of whichever spelling arrived, then be strict about what actually
|
||||
//! matters. The schema still advertises exactly one spelling, so nothing here is a second contract
|
||||
//! to keep.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// Keys accepted for the commit message, canonical first.
|
||||
const MESSAGE_KEYS: [&str; 4] = ["message", "msg", "commit_message", "commitMessage"];
|
||||
|
||||
/// Flags that hand git a message from somewhere other than `-m`, so a call carrying one needs no
|
||||
/// `message` of its own.
|
||||
///
|
||||
/// Verified against git rather than assumed: each of these commits without `-m`, and combining one
|
||||
/// with `-m` is an error git refuses outright ("Only one of -c/-C/-F/--fixup can be used"), so
|
||||
/// demanding a message unconditionally would put them out of reach.
|
||||
const MESSAGE_SOURCES: [&str; 9] = [
|
||||
"--no-edit",
|
||||
"-F",
|
||||
"--file",
|
||||
"-C",
|
||||
"--reuse-message",
|
||||
"-c",
|
||||
"--reedit-message",
|
||||
"--fixup",
|
||||
"--squash",
|
||||
];
|
||||
|
||||
/// Short `git commit` flags that take no value, and so may cluster ahead of an `m` (`-am`).
|
||||
///
|
||||
/// An allow-list rather than "any letter", because `-F`, `-C`, `-c` and `-S` all take one: reading
|
||||
/// `-Fm` as a message flag would silently reinterpret "take the message from the file named `m`".
|
||||
const CLUSTERABLE: &str = "asnevqoip";
|
||||
|
||||
/// The canonical shape, repeated on every failure so a correction needs no second look.
|
||||
const USAGE: &str = "Expected: {\"action\": \"commit\", \"message\": \"Subject line\\n\\nOptional \
|
||||
body.\"}";
|
||||
|
||||
/// Why a commit call could not be understood, with enough detail to fix it in one move.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum CommitError {
|
||||
/// Nothing in the call carries a message, and no flag supplies one either.
|
||||
NoMessage {
|
||||
/// Top-level keys the call actually arrived with.
|
||||
received: Vec<String>,
|
||||
},
|
||||
/// `--amend` with no new message and no `--no-edit`, which git can only resolve by opening an
|
||||
/// editor there is nobody to type into.
|
||||
AmendNeedsNoEdit,
|
||||
}
|
||||
|
||||
impl CommitError {
|
||||
/// A message that names what arrived, what was expected, and the shape to send.
|
||||
pub(crate) fn message(&self) -> String {
|
||||
match self {
|
||||
Self::NoMessage { received } => format!(
|
||||
"Error: no commit message. Received keys: {}. Pass it as `message` — `args` is for \
|
||||
git's other flags, so a message put there is a flag git does not have.\n{USAGE}\n\
|
||||
A commit that takes its message from elsewhere needs no `message`: \
|
||||
`--amend --no-edit`, `-F <file>`, `-C <commit>`, `--fixup=<commit>`.",
|
||||
render_keys(received)
|
||||
),
|
||||
Self::AmendNeedsNoEdit => format!(
|
||||
"Error: `--amend` with no message. Add `--no-edit` to keep the existing one, or \
|
||||
pass `message` to replace it.\nExpected: {{\"action\": \"commit\", \"args\": \
|
||||
[\"--amend\", \"--no-edit\"]}}\n{USAGE}"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The full argument list for a `commit` call, starting at `commit`.
|
||||
///
|
||||
/// `extra` is the call's `args` array, already extracted.
|
||||
pub(crate) fn commit_args(call: &Value, extra: &[String]) -> Result<Vec<String>, CommitError> {
|
||||
// The advertised spelling wins outright, and `args` then passes through untouched: a second
|
||||
// `-m` there is git's own way of writing a second paragraph, and lifting it out would quietly
|
||||
// drop what the caller asked for.
|
||||
if let Some(message) = first_string(call, &MESSAGE_KEYS) {
|
||||
return Ok(assemble(Some(message), extra.to_vec()));
|
||||
}
|
||||
|
||||
let (lifted, rest) = lift_message_flag(extra);
|
||||
if let Some(message) = lifted {
|
||||
return Ok(assemble(Some(message), rest));
|
||||
}
|
||||
|
||||
// A lone argument that is not a flag can only be the message. Git would read it as a pathspec,
|
||||
// and a pathspec commit with no message anywhere has nowhere to get one from — the editor is
|
||||
// closed — so the reading that lets the call succeed is the only one worth taking.
|
||||
if let [only] = rest.as_slice() {
|
||||
if !only.starts_with('-') {
|
||||
return Ok(assemble(Some(only.clone()), Vec::new()));
|
||||
}
|
||||
}
|
||||
|
||||
if carries_its_own_message(&rest) {
|
||||
return Ok(assemble(None, rest));
|
||||
}
|
||||
if rest.iter().any(|arg| arg == "--amend") {
|
||||
return Err(CommitError::AmendNeedsNoEdit);
|
||||
}
|
||||
Err(CommitError::NoMessage { received: keys_of(call) })
|
||||
}
|
||||
|
||||
/// Put the message where git wants it, ahead of whatever else the caller sent.
|
||||
fn assemble(message: Option<String>, rest: Vec<String>) -> Vec<String> {
|
||||
let mut args = vec!["commit".to_string()];
|
||||
if let Some(message) = message {
|
||||
args.push("-m".to_string());
|
||||
args.push(message);
|
||||
}
|
||||
args.extend(rest);
|
||||
args
|
||||
}
|
||||
|
||||
/// Pull a `-m`/`--message` value out of a raw git argument list, returning it and what is left.
|
||||
///
|
||||
/// Every spelling git itself takes: `-m x`, `-mx`, `-am x`, `--message x`, `--message=x`. Only the
|
||||
/// first is lifted — a later `-m` is a second paragraph and stays where it is.
|
||||
fn lift_message_flag(args: &[String]) -> (Option<String>, Vec<String>) {
|
||||
let mut message: Option<String> = None;
|
||||
let mut rest = Vec::with_capacity(args.len());
|
||||
let mut iter = args.iter();
|
||||
|
||||
while let Some(arg) = iter.next() {
|
||||
if message.is_some() {
|
||||
rest.push(arg.clone());
|
||||
continue;
|
||||
}
|
||||
if arg == "--message" {
|
||||
message = iter.next().cloned();
|
||||
continue;
|
||||
}
|
||||
if let Some(value) = arg.strip_prefix("--message=") {
|
||||
message = Some(value.to_string());
|
||||
continue;
|
||||
}
|
||||
match split_short_message(arg) {
|
||||
Some((companions, attached)) => {
|
||||
if let Some(companions) = companions {
|
||||
rest.push(companions);
|
||||
}
|
||||
message = match attached {
|
||||
Some(value) => Some(value),
|
||||
None => iter.next().cloned(),
|
||||
};
|
||||
}
|
||||
None => rest.push(arg.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
(message, rest)
|
||||
}
|
||||
|
||||
/// Split a short-flag cluster carrying `m` into the flags beside it and any attached value.
|
||||
///
|
||||
/// `-m` → `(None, None)`, `-am` → `(Some("-a"), None)`, `-mwip` → `(None, Some("wip"))`. Anything
|
||||
/// that is not a `git commit` message flag returns `None` and is left alone.
|
||||
fn split_short_message(arg: &str) -> Option<(Option<String>, Option<String>)> {
|
||||
let cluster = arg.strip_prefix('-').filter(|rest| !rest.starts_with('-'))?;
|
||||
let at = cluster.find('m')?;
|
||||
let (companions, attached) = cluster.split_at(at);
|
||||
if !companions.chars().all(|flag| CLUSTERABLE.contains(flag)) {
|
||||
return None;
|
||||
}
|
||||
let attached = attached.strip_prefix('m').filter(|value| !value.is_empty());
|
||||
let companions = (!companions.is_empty()).then(|| format!("-{companions}"));
|
||||
Some((companions, attached.map(ToOwned::to_owned)))
|
||||
}
|
||||
|
||||
/// Whether these arguments already tell git where the message comes from.
|
||||
fn carries_its_own_message(args: &[String]) -> bool {
|
||||
args.iter().any(|arg| {
|
||||
MESSAGE_SOURCES.iter().any(|flag| match flag.strip_prefix("--") {
|
||||
// A long flag attaches its value with `=`: `--fixup=HEAD`.
|
||||
Some(_) => arg == flag || arg.strip_prefix(flag).is_some_and(|v| v.starts_with('=')),
|
||||
// A short one just runs into it: `-CHEAD`. No long flag can be caught here, because a
|
||||
// long flag's second character is always `-` and no short flag's is.
|
||||
None => arg.starts_with(flag),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn keys_of(value: &Value) -> Vec<String> {
|
||||
value.as_object().map(|map| map.keys().cloned().collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn render_keys(keys: &[String]) -> String {
|
||||
if keys.is_empty() {
|
||||
return "(none)".to_string();
|
||||
}
|
||||
keys.join(", ")
|
||||
}
|
||||
|
||||
/// The first alias present and non-blank.
|
||||
///
|
||||
/// Blank is not a message: git refuses an empty one ("Aborting commit due to empty commit
|
||||
/// message"), so accepting it here would only move the failure somewhere less legible.
|
||||
fn first_string(value: &Value, keys: &[&str]) -> Option<String> {
|
||||
keys.iter()
|
||||
.find_map(|key| value.get(*key).and_then(Value::as_str))
|
||||
.filter(|text| !text.trim().is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
/// The full `gh` argument list for a `pr` or `issue` call, defaulting to listing them.
|
||||
///
|
||||
/// Every argument is forwarded: dropping them would send `pr create --title … --body …` to `gh` as
|
||||
/// a bare `gh pr create`, which does not fail loudly but *prompts* for the title it was already
|
||||
/// handed, from behind a TUI that owns the screen.
|
||||
pub(super) fn gh_args(kind: &str, requested: &[String]) -> Vec<String> {
|
||||
let mut args = vec![kind.to_string()];
|
||||
if requested.is_empty() {
|
||||
args.push("list".to_string());
|
||||
} else {
|
||||
args.extend(requested.iter().cloned());
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
/// Whether a `pr` call is trying to open a pull request, as opposed to reading about one.
|
||||
///
|
||||
/// Only `create` has a precondition the caller can get wrong, so only `create` gets the preflight.
|
||||
pub(super) fn is_pr_create(requested: &[String]) -> bool {
|
||||
requested.first().is_some_and(|subaction| subaction == "create")
|
||||
}
|
||||
|
||||
/// The full `git stash` argument list, defaulting to `stash push`.
|
||||
///
|
||||
/// Every argument is forwarded, as in [`gh_args`]: a dropped `-m wip` loses the label that was the
|
||||
/// entire point of naming the stash, and any way to find the entry again.
|
||||
pub(super) fn stash_args(requested: &[String]) -> Vec<String> {
|
||||
let mut args = vec!["stash".to_string()];
|
||||
if requested.is_empty() {
|
||||
args.push("push".to_string());
|
||||
} else {
|
||||
args.extend(requested.iter().cloned());
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn owned(args: &[&str]) -> Vec<String> {
|
||||
args.iter().map(|arg| (*arg).to_string()).collect()
|
||||
}
|
||||
|
||||
/// The shapes a real session produced, all of which were refused.
|
||||
///
|
||||
/// Taken from a transcript, not imagined: the model tried `["-m", msg]`, then `[msg]`, got
|
||||
/// "'message' argument is required for commit" both times, and went to `bash`.
|
||||
#[test]
|
||||
fn every_spelling_a_model_reaches_for_becomes_the_same_commit() {
|
||||
let expected = owned(&["commit", "-m", "Animate the loading spinner"]);
|
||||
let cases = [
|
||||
json!({"action": "commit", "message": "Animate the loading spinner"}),
|
||||
json!({"action": "commit", "args": ["-m", "Animate the loading spinner"]}),
|
||||
json!({"action": "commit", "args": ["Animate the loading spinner"]}),
|
||||
json!({"action": "commit", "args": ["--message", "Animate the loading spinner"]}),
|
||||
json!({"action": "commit", "args": ["--message=Animate the loading spinner"]}),
|
||||
json!({"action": "commit", "args": ["-mAnimate the loading spinner"]}),
|
||||
];
|
||||
for call in cases {
|
||||
let extra = extra_of(&call);
|
||||
assert_eq!(commit_args(&call, &extra).unwrap(), expected, "{call}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A clustered `-am` keeps the flag it was clustered with.
|
||||
#[test]
|
||||
fn a_short_cluster_surrenders_the_message_and_keeps_its_flags() {
|
||||
let call = json!({"action": "commit", "args": ["-am", "wip"]});
|
||||
assert_eq!(
|
||||
commit_args(&call, &extra_of(&call)).unwrap(),
|
||||
owned(&["commit", "-m", "wip", "-a"])
|
||||
);
|
||||
|
||||
// `-F` takes a value, so `-Fm` is the file named `m` and must survive untouched.
|
||||
assert_eq!(split_short_message("-Fm"), None);
|
||||
assert_eq!(split_short_message("-Sm"), None);
|
||||
assert_eq!(split_short_message("--amend"), None);
|
||||
assert_eq!(split_short_message("-a"), None);
|
||||
}
|
||||
|
||||
/// The advertised spelling wins, and a `-m` in `args` stays put rather than being dropped —
|
||||
/// repeated `-m` is how git writes a second paragraph.
|
||||
#[test]
|
||||
fn the_canonical_spelling_wins_without_discarding_the_other() {
|
||||
let call = json!({"action": "commit", "message": "subject", "args": ["-m", "body"]});
|
||||
assert_eq!(
|
||||
commit_args(&call, &extra_of(&call)).unwrap(),
|
||||
owned(&["commit", "-m", "subject", "-m", "body"])
|
||||
);
|
||||
}
|
||||
|
||||
/// Flags git accepts a message *from* need no message of their own. Every one of these was
|
||||
/// unreachable while `message` was unconditionally required.
|
||||
#[test]
|
||||
fn a_commit_that_names_its_own_message_source_needs_no_message() {
|
||||
for args in [
|
||||
vec!["--amend", "--no-edit"],
|
||||
vec!["-F", "msg.txt"],
|
||||
vec!["--file=msg.txt"],
|
||||
vec!["-C", "HEAD"],
|
||||
vec!["--reuse-message=HEAD"],
|
||||
vec!["--fixup=HEAD"],
|
||||
vec!["--squash", "HEAD"],
|
||||
// Attached to the flag, which is how git spells these as often as not.
|
||||
vec!["-Fmsg.txt"],
|
||||
vec!["-CHEAD"],
|
||||
vec!["-cHEAD"],
|
||||
] {
|
||||
let call = json!({"action": "commit", "args": args});
|
||||
let extra = extra_of(&call);
|
||||
let built = commit_args(&call, &extra).unwrap_or_else(|e| panic!("{args:?}: {e:?}"));
|
||||
assert_eq!(built[0], "commit");
|
||||
assert!(!built.contains(&"-m".to_string()), "{args:?} got an -m it did not ask for");
|
||||
}
|
||||
}
|
||||
|
||||
/// `--amend` alone would send git to an editor nobody can reach, so it is refused *here*, where
|
||||
/// the reply can name the two ways out.
|
||||
#[test]
|
||||
fn amending_without_a_message_says_which_two_things_would_work() {
|
||||
let call = json!({"action": "commit", "args": ["--amend"]});
|
||||
let error = commit_args(&call, &extra_of(&call)).unwrap_err();
|
||||
assert_eq!(error, CommitError::AmendNeedsNoEdit);
|
||||
let text = error.message();
|
||||
assert!(text.contains("--no-edit"), "{text}");
|
||||
assert!(text.contains("message"), "{text}");
|
||||
}
|
||||
|
||||
/// The refusal that started this: it named the key and never the shape.
|
||||
#[test]
|
||||
fn a_refusal_shows_the_call_that_would_have_worked() {
|
||||
let call = json!({"action": "commit", "args": ["-a"]});
|
||||
let error = commit_args(&call, &extra_of(&call)).unwrap_err();
|
||||
let text = error.message();
|
||||
|
||||
assert!(text.contains("action, args"), "names what arrived: {text}");
|
||||
assert!(text.contains("\"message\""), "and the shape to send: {text}");
|
||||
assert!(text.contains("--amend --no-edit"), "and the way out that needs none: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blank_message_is_no_message() {
|
||||
for blank in ["", " ", "\n"] {
|
||||
let call = json!({"action": "commit", "message": blank});
|
||||
assert!(commit_args(&call, &[]).is_err(), "{blank:?} is not a commit message");
|
||||
}
|
||||
}
|
||||
|
||||
/// Flags beside the message keep their order and their place after it.
|
||||
#[test]
|
||||
fn other_flags_survive_in_order() {
|
||||
let call = json!({"action": "commit", "message": "m", "args": ["--amend", "--", "a.rs"]});
|
||||
assert_eq!(
|
||||
commit_args(&call, &extra_of(&call)).unwrap(),
|
||||
owned(&["commit", "-m", "m", "--amend", "--", "a.rs"])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_call_reports_no_keys_rather_than_an_empty_list() {
|
||||
let error = commit_args(&json!({}), &[]).unwrap_err();
|
||||
assert!(error.message().contains("(none)"), "{}", error.message());
|
||||
}
|
||||
|
||||
fn extra_of(call: &Value) -> Vec<String> {
|
||||
call.get("args")
|
||||
.and_then(|value| value.as_array())
|
||||
.map(|values| {
|
||||
values.iter().filter_map(|v| v.as_str().map(String::from)).collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
191
crates/luxe-tools/src/git/checks.rs
Normal file
191
crates/luxe-tools/src/git/checks.rs
Normal file
@@ -0,0 +1,191 @@
|
||||
//! `git` `checks` — why CI is failing, bounded.
|
||||
//!
|
||||
//! `gh run view --log-failed` prints every line of every failing step: 3,671 lines for one Clippy
|
||||
//! step on luxe-dev, with the error in the last dozen. This reads the same logs through GitHub
|
||||
//! and keeps the tail of each failing step, says how much it left out, and also lists the failing
|
||||
//! checks that are not Actions jobs at all — a commit status from another CI, which that command
|
||||
//! cannot see. Reading only; re-running a job stays behind the permission engine's `ask`.
|
||||
|
||||
use luxe_core::github::{
|
||||
Branches, CheckLog, Checks, Discovery, FailingCheck, GitHubError, PullRequests,
|
||||
};
|
||||
use std::path::Path;
|
||||
|
||||
/// Lines kept from the end of each failing step's log.
|
||||
pub(super) const LOG_TAIL: usize = 30;
|
||||
|
||||
/// Longest the whole answer may run, in lines, whatever the number of failures.
|
||||
pub(super) const MAX_LINES: usize = 200;
|
||||
|
||||
/// The commit whose checks were read, and how it was chosen.
|
||||
struct Target {
|
||||
/// Tip of what was asked about
|
||||
oid: String,
|
||||
/// What to call it: the pull request, or the commit when there is none
|
||||
name: String,
|
||||
/// Checks still running, when the pull request said
|
||||
pending: Option<usize>,
|
||||
}
|
||||
|
||||
/// Why checks are failing on the branch's pull request, on pull request `#n` when `args` names one,
|
||||
/// or on `HEAD` when the branch has no pull request.
|
||||
pub(super) async fn checks(
|
||||
github: &(impl Discovery + PullRequests + Branches + Checks + ?Sized),
|
||||
cwd: &Path,
|
||||
args: &[String],
|
||||
) -> Result<String, String> {
|
||||
let repository = github.repository(cwd).await.map_err(|error| failure(&error))?;
|
||||
let target = match args.first().map(|arg| arg.trim_start_matches('#')) {
|
||||
Some(number) => {
|
||||
let number: u64 =
|
||||
number.parse().map_err(|_| format!("`{number}` is not a pull request number."))?;
|
||||
let pr = github.pull_request(&repository, number).await.map_err(|e| failure(&e))?;
|
||||
Target {
|
||||
oid: pr.head_oid,
|
||||
name: format!("#{} · {}", pr.number, luxe_core::github::untrusted(&pr.title, 120)),
|
||||
pending: Some(pr.checks.pending),
|
||||
}
|
||||
}
|
||||
None => branch_target(github, cwd, &repository).await?,
|
||||
};
|
||||
let failing = github
|
||||
.failing_checks(&repository, &target.oid, LOG_TAIL)
|
||||
.await
|
||||
.map_err(|error| failure(&error))?;
|
||||
Ok(render(&target, &failing))
|
||||
}
|
||||
|
||||
/// The branch's pull request head, or `HEAD` when there is no pull request to ask about.
|
||||
async fn branch_target(
|
||||
github: &(impl Branches + ?Sized),
|
||||
cwd: &Path,
|
||||
repository: &luxe_core::github::Repository,
|
||||
) -> Result<Target, String> {
|
||||
let head = luxe_core::github::branch_head(cwd).await;
|
||||
if let Some(head) = head {
|
||||
let status = github.branch_status(repository, &head).await.map_err(|e| failure(&e))?;
|
||||
if let Some(pr) = status.pull_request {
|
||||
return Ok(Target {
|
||||
oid: pr.head_oid,
|
||||
name: format!("#{} · {}", pr.number, pr.title),
|
||||
pending: Some(pr.checks.pending),
|
||||
});
|
||||
}
|
||||
}
|
||||
let oid = head_commit(cwd).await.ok_or("This checkout has no commit to read checks for.")?;
|
||||
let name = format!("{} (this branch has no pull request)", short(&oid));
|
||||
Ok(Target { oid, name, pending: None })
|
||||
}
|
||||
|
||||
async fn head_commit(cwd: &Path) -> Option<String> {
|
||||
let program =
|
||||
luxe_core::program::resolve("git").unwrap_or_else(|| std::path::PathBuf::from("git"));
|
||||
let command = luxe_core::program::captured_command(program, &["rev-parse", "HEAD"], cwd);
|
||||
let output =
|
||||
luxe_core::program::run_bounded(command, std::time::Duration::from_secs(10)).await.ok()?;
|
||||
let oid = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
(output.status.success() && !oid.is_empty()).then_some(oid)
|
||||
}
|
||||
|
||||
/// The answer: each failing check, where to read it, and the end of each failing step.
|
||||
fn render(target: &Target, failing: &[FailingCheck]) -> String {
|
||||
let running = match target.pending {
|
||||
Some(0) | None => String::new(),
|
||||
Some(1) => " 1 check is still running.".to_string(),
|
||||
Some(count) => format!(" {count} checks are still running."),
|
||||
};
|
||||
if failing.is_empty() {
|
||||
return format!("No checks are failing on {}.{running}", target.name);
|
||||
}
|
||||
let count = match failing.len() {
|
||||
1 => "1 check".to_string(),
|
||||
count => format!("{count} checks"),
|
||||
};
|
||||
let mut lines =
|
||||
vec![format!("{count} failing on {} ({}).{running}", target.name, short(&target.oid))];
|
||||
for check in failing {
|
||||
lines.push(String::new());
|
||||
let summary = check.summary.as_deref().map(|text| format!(": {text}")).unwrap_or_default();
|
||||
lines.push(format!("{} — {}{summary}", check.name, check.outcome));
|
||||
if !check.url.is_empty() {
|
||||
lines.push(format!(" {}", check.url));
|
||||
}
|
||||
match &check.log {
|
||||
CheckLog::NotActions => {
|
||||
lines.push(
|
||||
" Not a GitHub Actions job, so there is no log here; the link has it.".into(),
|
||||
);
|
||||
}
|
||||
CheckLog::NotRead => lines.push(
|
||||
" Log not read: only the first few failing jobs are. The link, or `gh run view \
|
||||
--job <id> --log-failed`, has it."
|
||||
.into(),
|
||||
),
|
||||
CheckLog::Unreadable(reason) => lines.push(format!(" Log unreadable: {reason}")),
|
||||
CheckLog::Steps(steps) if steps.is_empty() => {
|
||||
lines.push(" No failing step printed a log.".into());
|
||||
}
|
||||
CheckLog::Steps(steps) => {
|
||||
for step in steps {
|
||||
let name = match step.name.as_str() {
|
||||
"UNKNOWN STEP" => "the job's log (gh could not split it by step)".into(),
|
||||
name => format!("step \"{name}\""),
|
||||
};
|
||||
let shown = match (step.omitted, step.after) {
|
||||
(0, 0) => format!(" {name}:"),
|
||||
(omitted, 0) => format!(
|
||||
" {name}, last {} of {} lines:",
|
||||
step.tail.len(),
|
||||
step.tail.len() + omitted
|
||||
),
|
||||
(omitted, after) => format!(
|
||||
" {name}, the {} up to its last error, of {}:",
|
||||
match step.tail.len() {
|
||||
1 => "line".to_string(),
|
||||
count => format!("{count} lines"),
|
||||
},
|
||||
step.tail.len() + omitted + after
|
||||
),
|
||||
};
|
||||
lines.push(shown);
|
||||
lines.extend(step.tail.iter().map(|line| format!(" {line}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::output_limit::cap_lines(
|
||||
&lines.join("\n"),
|
||||
MAX_LINES,
|
||||
"lines of check output",
|
||||
"ask about one pull request at a time, or open a check's link",
|
||||
)
|
||||
}
|
||||
|
||||
/// What went wrong, as the sentence the model acts on.
|
||||
fn failure(error: &GitHubError) -> String {
|
||||
match error {
|
||||
GitHubError::NotInstalled => {
|
||||
"The GitHub CLI (`gh`) is not installed. Install it and run `gh auth login`.".into()
|
||||
}
|
||||
GitHubError::NotAuthenticated { .. } => {
|
||||
"The GitHub CLI is not signed in. The user needs to run `gh auth login`.".into()
|
||||
}
|
||||
GitHubError::NotGitHub => "This repository has no remote on GitHub.".into(),
|
||||
GitHubError::NotFound => {
|
||||
"GitHub has no such pull request or commit that this account can see; \
|
||||
a commit that was never pushed has no checks."
|
||||
.into()
|
||||
}
|
||||
GitHubError::RateLimited => {
|
||||
"GitHub's rate limit for this account is spent; it refills within the hour.".into()
|
||||
}
|
||||
other => format!("Could not read the checks: {other}."),
|
||||
}
|
||||
}
|
||||
|
||||
fn short(oid: &str) -> &str {
|
||||
oid.get(..7).unwrap_or(oid)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
344
crates/luxe-tools/src/git/checks/tests.rs
Normal file
344
crates/luxe-tools/src/git/checks/tests.rs
Normal file
@@ -0,0 +1,344 @@
|
||||
use super::*;
|
||||
use luxe_core::github::FailedStep;
|
||||
|
||||
fn target(pending: Option<usize>) -> Target {
|
||||
Target {
|
||||
oid: "1ee6ffe1e7cc5e51a79ec5df24e7e8db03f237b5".into(),
|
||||
name: "#119 · Bump getrandom".into(),
|
||||
pending,
|
||||
}
|
||||
}
|
||||
|
||||
fn check(name: &str, log: CheckLog) -> FailingCheck {
|
||||
FailingCheck {
|
||||
name: name.into(),
|
||||
outcome: "failure".into(),
|
||||
url: format!("https://github.com/o/r/actions/runs/1/job/{name}"),
|
||||
summary: None,
|
||||
log,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_failing_says_so_and_what_is_still_running() {
|
||||
assert_eq!(render(&target(Some(0)), &[]), "No checks are failing on #119 · Bump getrandom.");
|
||||
assert_eq!(
|
||||
render(&target(Some(2)), &[]),
|
||||
"No checks are failing on #119 · Bump getrandom. 2 checks are still running."
|
||||
);
|
||||
assert!(render(&target(Some(1)), &[]).ends_with("1 check is still running."));
|
||||
assert!(render(&target(None), &[]).ends_with("getrandom."));
|
||||
}
|
||||
|
||||
/// Each kind of failure says where its log is, and a cut tail says how much it left out.
|
||||
#[test]
|
||||
fn every_failure_says_where_its_log_is() {
|
||||
let steps = CheckLog::Steps(vec![FailedStep {
|
||||
name: "Clippy (deny warnings)".into(),
|
||||
tail: vec!["error[E0425]: cannot find function".into(), "##[error]exit 101".into()],
|
||||
omitted: 59,
|
||||
after: 0,
|
||||
}]);
|
||||
let failing = [
|
||||
check("clippy", steps),
|
||||
FailingCheck {
|
||||
summary: Some("#20260924.53 failed".into()),
|
||||
..check("Azure Pipelines CI", CheckLog::NotActions)
|
||||
},
|
||||
check("windows", CheckLog::Unreadable("HTTP 410: logs expired".into())),
|
||||
check("macos", CheckLog::NotRead),
|
||||
check("empty", CheckLog::Steps(Vec::new())),
|
||||
check(
|
||||
"short",
|
||||
CheckLog::Steps(vec![FailedStep {
|
||||
name: "Build".into(),
|
||||
tail: vec!["oops".into()],
|
||||
omitted: 0,
|
||||
after: 0,
|
||||
}]),
|
||||
),
|
||||
check(
|
||||
"whole",
|
||||
CheckLog::Steps(vec![FailedStep {
|
||||
name: "UNKNOWN STEP".into(),
|
||||
tail: vec!["##[error]exit 1".into()],
|
||||
omitted: 5_000,
|
||||
after: 40,
|
||||
}]),
|
||||
),
|
||||
];
|
||||
let text = render(&target(Some(1)), &failing);
|
||||
assert!(text.starts_with(
|
||||
"7 checks failing on #119 · Bump getrandom (1ee6ffe). 1 check is still running."
|
||||
));
|
||||
for expected in [
|
||||
"clippy — failure\n https://github.com/o/r/actions/runs/1/job/clippy",
|
||||
" step \"Clippy (deny warnings)\", last 2 of 61 lines:\n error[E0425]",
|
||||
"Azure Pipelines CI — failure: #20260924.53 failed",
|
||||
"Not a GitHub Actions job",
|
||||
"Log unreadable: HTTP 410: logs expired",
|
||||
"Log not read: only the first few",
|
||||
"No failing step printed a log.",
|
||||
" step \"Build\":\n oops",
|
||||
" the job's log (gh could not split it by step), the line up to its last error, of \
|
||||
5041:",
|
||||
] {
|
||||
assert!(text.contains(expected), "{expected:?} in:\n{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flood_of_failures_is_capped_and_says_so() {
|
||||
let tail: Vec<String> = (0..LOG_TAIL).map(|n| format!("line {n}")).collect();
|
||||
let failing: Vec<FailingCheck> = (0..20)
|
||||
.map(|n| {
|
||||
let step =
|
||||
FailedStep { name: "Test".into(), tail: tail.clone(), omitted: 900, after: 0 };
|
||||
check(&format!("job {n}"), CheckLog::Steps(vec![step]))
|
||||
})
|
||||
.collect();
|
||||
let text = render(&target(None), &failing);
|
||||
assert!(text.lines().count() <= MAX_LINES + 2, "{}", text.lines().count());
|
||||
assert!(text.contains("lines of check output"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_oid_is_seven_characters_or_all_of_it() {
|
||||
assert_eq!(short("1ee6ffe1e7cc"), "1ee6ffe");
|
||||
assert_eq!(short("abc"), "abc");
|
||||
}
|
||||
|
||||
/// A GitHub double with one pull request, #7, whose head has one failing Actions job.
|
||||
struct Scripted {
|
||||
signed_in: bool,
|
||||
/// Whether the branch has a pull request
|
||||
pull_request: bool,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl luxe_core::github::Discovery for Scripted {
|
||||
async fn account(&self, _: Option<&str>) -> Result<luxe_core::github::Account, GitHubError> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
async fn repository(&self, _: &Path) -> Result<luxe_core::github::Repository, GitHubError> {
|
||||
if !self.signed_in {
|
||||
return Err(GitHubError::NotAuthenticated { host: None });
|
||||
}
|
||||
Ok(luxe_core::github::Repository {
|
||||
host: "github.com".into(),
|
||||
owner: "me".into(),
|
||||
name: "app".into(),
|
||||
default_branch: "main".into(),
|
||||
remote: Some("origin".into()),
|
||||
})
|
||||
}
|
||||
|
||||
async fn search(
|
||||
&self,
|
||||
_host: &str,
|
||||
_query: &str,
|
||||
_after: Option<&str>,
|
||||
) -> Result<luxe_core::github::SearchPage, GitHubError> {
|
||||
Ok(luxe_core::github::SearchPage::default())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl luxe_core::github::PullRequests for Scripted {
|
||||
async fn pull_request(
|
||||
&self,
|
||||
_: &luxe_core::github::Repository,
|
||||
number: u64,
|
||||
) -> Result<luxe_core::github::PullRequest, GitHubError> {
|
||||
if number != 7 {
|
||||
return Err(GitHubError::NotFound);
|
||||
}
|
||||
Ok(luxe_core::github::PullRequest {
|
||||
number: 7,
|
||||
title: "Topic".into(),
|
||||
body: String::new(),
|
||||
url: String::new(),
|
||||
author: luxe_core::github::Author { login: "me".into(), bot: false },
|
||||
draft: false,
|
||||
state: luxe_core::github::PullRequestState::Open,
|
||||
base_ref: "main".into(),
|
||||
base_oid: "b".into(),
|
||||
head_ref: "topic".into(),
|
||||
head_oid: "7777777aaaa".into(),
|
||||
cross_repository: false,
|
||||
review_decision: None,
|
||||
checks: luxe_core::github::CheckRollup { pending: 1, ..Default::default() },
|
||||
closing_issues: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn issue(
|
||||
&self,
|
||||
_: &luxe_core::github::Repository,
|
||||
_: u64,
|
||||
) -> Result<luxe_core::github::Issue, GitHubError> {
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
async fn conversation(
|
||||
&self,
|
||||
|
||||
_repository: &luxe_core::github::Repository,
|
||||
|
||||
_number: u64,
|
||||
|
||||
_pull_request: bool,
|
||||
) -> Result<Vec<luxe_core::github::overview::ConversationEntry>, GitHubError> {
|
||||
unreachable!("this double does not read conversations")
|
||||
}
|
||||
|
||||
async fn issue_overview(
|
||||
&self,
|
||||
_repository: &luxe_core::github::Repository,
|
||||
_number: u64,
|
||||
) -> Result<luxe_core::github::overview::IssueOverview, GitHubError> {
|
||||
unreachable!("this double does not read overviews")
|
||||
}
|
||||
|
||||
async fn pull_request_overview(
|
||||
&self,
|
||||
_repository: &luxe_core::github::Repository,
|
||||
_number: u64,
|
||||
) -> Result<luxe_core::github::overview::PullRequestOverview, GitHubError> {
|
||||
unreachable!("this double does not read overviews")
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl luxe_core::github::Branches for Scripted {
|
||||
async fn branch_status(
|
||||
&self,
|
||||
_: &luxe_core::github::Repository,
|
||||
head: &luxe_core::github::BranchHead,
|
||||
) -> Result<luxe_core::github::BranchStatus, GitHubError> {
|
||||
assert_eq!(head.name, "topic");
|
||||
if !self.pull_request {
|
||||
return Ok(luxe_core::github::BranchStatus { pull_request: None, rate_limit: None });
|
||||
}
|
||||
let pr = self.pull_request(&self.repository(Path::new("")).await?, 7).await?;
|
||||
Ok(luxe_core::github::BranchStatus {
|
||||
pull_request: Some(luxe_core::github::PullRequestStatus {
|
||||
number: pr.number,
|
||||
title: pr.title,
|
||||
url: pr.url,
|
||||
state: pr.state,
|
||||
draft: false,
|
||||
review_decision: None,
|
||||
checks: pr.checks,
|
||||
unresolved_threads: 0,
|
||||
head_oid: pr.head_oid,
|
||||
stack: None,
|
||||
}),
|
||||
rate_limit: None,
|
||||
})
|
||||
}
|
||||
|
||||
async fn pull_request_head(
|
||||
&self,
|
||||
_repository: &luxe_core::github::Repository,
|
||||
_number: u64,
|
||||
) -> Result<luxe_core::github::PullRequestHead, GitHubError> {
|
||||
unreachable!("this double reads no pull request heads")
|
||||
}
|
||||
|
||||
async fn merged_below(
|
||||
&self,
|
||||
_repository: &luxe_core::github::Repository,
|
||||
_number: u64,
|
||||
_base: &str,
|
||||
) -> Result<Option<luxe_core::restack::MergedBelow>, GitHubError> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl luxe_core::github::Checks for Scripted {
|
||||
async fn failing_checks(
|
||||
&self,
|
||||
_: &luxe_core::github::Repository,
|
||||
head_oid: &str,
|
||||
log_tail: usize,
|
||||
) -> Result<Vec<FailingCheck>, GitHubError> {
|
||||
assert_eq!(log_tail, LOG_TAIL);
|
||||
if head_oid != "7777777aaaa" {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
Ok(vec![check("test", CheckLog::NotRead)])
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_named_pull_request_reads_its_head() {
|
||||
let github = Scripted { signed_in: true, pull_request: true };
|
||||
let text = checks(&github, Path::new("."), &["#7".into()]).await.unwrap();
|
||||
assert!(
|
||||
text.starts_with("1 check failing on #7 · Topic (7777777). 1 check is still running."),
|
||||
"{text}"
|
||||
);
|
||||
|
||||
let error = checks(&github, Path::new("."), &["seven".into()]).await.unwrap_err();
|
||||
assert!(error.contains("`seven` is not a pull request number"), "{error}");
|
||||
let error = checks(&github, Path::new("."), &["8".into()]).await.unwrap_err();
|
||||
assert!(error.contains("never pushed has no checks"), "{error}");
|
||||
let error = checks(&Scripted { signed_in: false, pull_request: true }, Path::new("."), &[])
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.contains("gh auth login"), "{error}");
|
||||
}
|
||||
|
||||
/// With nothing named, the branch's own pull request is the one read.
|
||||
#[tokio::test]
|
||||
async fn the_branchs_pull_request_is_the_default() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let output = std::process::Command::new("git")
|
||||
.args(["init", "-q", "-b", "topic"])
|
||||
.current_dir(dir.path())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
let text =
|
||||
checks(&Scripted { signed_in: true, pull_request: true }, dir.path(), &[]).await.unwrap();
|
||||
assert!(text.starts_with("1 check failing on #7 · Topic"), "{text}");
|
||||
}
|
||||
|
||||
/// A branch with no pull request reads the checks on `HEAD`, and says it did.
|
||||
#[tokio::test]
|
||||
async fn without_a_pull_request_the_checks_on_head_are_read() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let git = |args: &[&str]| {
|
||||
let output =
|
||||
std::process::Command::new("git").args(args).current_dir(dir.path()).output().unwrap();
|
||||
assert!(output.status.success(), "{args:?}: {output:?}");
|
||||
String::from_utf8_lossy(&output.stdout).trim().to_string()
|
||||
};
|
||||
git(&["init", "-q", "-b", "topic"]);
|
||||
let github = Scripted { signed_in: true, pull_request: false };
|
||||
let error = checks(&github, dir.path(), &[]).await.unwrap_err();
|
||||
assert!(error.contains("no commit"), "{error}");
|
||||
|
||||
git(&["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "a"]);
|
||||
let head = git(&["rev-parse", "HEAD"]);
|
||||
let text = checks(&github, dir.path(), &[]).await.unwrap();
|
||||
assert_eq!(
|
||||
text,
|
||||
format!("No checks are failing on {} (this branch has no pull request).", &head[..7])
|
||||
);
|
||||
}
|
||||
|
||||
/// Against the real `gh` and luxe-dev's #119, whose getrandom bump failed three jobs: each
|
||||
/// comes back with the compiler's error at the end of its tail. `cargo test -- --ignored`.
|
||||
#[tokio::test]
|
||||
#[ignore = "needs a signed-in gh and the network"]
|
||||
async fn a_real_failed_run_ends_in_its_error() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let github = luxe_core::github::GhCli::new();
|
||||
let text = checks(&github, &root, &["119".into()]).await.unwrap();
|
||||
assert!(text.starts_with("1 check failing on #119"), "{text}");
|
||||
assert!(text.contains("##[error]Process completed with exit code"), "{text}");
|
||||
}
|
||||
103
crates/luxe-tools/src/git/failure.rs
Normal file
103
crates/luxe-tools/src/git/failure.rs
Normal file
@@ -0,0 +1,103 @@
|
||||
//! Failures — what git's and `gh`'s own complaints say once a model has to act on them.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// Turn git's plumbing failure into something a model can act on.
|
||||
///
|
||||
/// Outside a repository, `git status` answers with "fatal: not a git repository … Stopping at
|
||||
/// filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)" and `git diff` prints its entire
|
||||
/// usage screen — twenty lines of flags in place of a fact. Neither tells a reader the one thing
|
||||
/// that matters: this directory has no version control, so stop asking it about history.
|
||||
///
|
||||
/// **Both streams, always.** Git puts a *fatal* on stderr and a *refusal* on stdout: a commit with
|
||||
/// nothing staged exits 1 having said "no changes added to commit" on stdout and nothing at all on
|
||||
/// stderr. Reading stderr alone turned the most common commit failure there is into "Git command
|
||||
/// failed (no output).", which names no cause and suggests no fix — so the model abandoned the
|
||||
/// tool and ran the same commit through `bash`, where git's own words were waiting.
|
||||
pub(super) fn explain_failure(stderr: &str, stdout: &str, cwd: &Path) -> String {
|
||||
let lowered = format!("{stderr}\n{stdout}").to_ascii_lowercase();
|
||||
if lowered.contains("not a git repository") {
|
||||
return format!(
|
||||
"Not a git repository: `{}` is not version controlled, so there is no status, diff, \
|
||||
history, or branch to read. Use `read`/`grep` for the files themselves.",
|
||||
luxe_core::paths::display(cwd)
|
||||
);
|
||||
}
|
||||
// Reached because run_git closes the editor off deliberately. Git's own reply names `-m` and
|
||||
// `-F`, which are not the arguments this tool takes.
|
||||
if lowered.contains("problem with the editor") {
|
||||
return "Git wanted an editor to write this commit message and there is nobody to type \
|
||||
into one. Pass `message`, or add `--no-edit` to reuse the existing message."
|
||||
.to_string();
|
||||
}
|
||||
// Git's own advice here names `git add` and `git commit -a`, which are command lines rather
|
||||
// than this tool's arguments. The three refusals are distinct: what to do about each depends
|
||||
// on whether anything changed at all, and whether git can see it.
|
||||
if lowered.contains("no changes added to commit") {
|
||||
return "Nothing is staged, so there is nothing to commit — the changes are in the working \
|
||||
tree only. Stage them first with `{\"action\": \"add\", \"args\": [\".\"]}`, or \
|
||||
commit every tracked change at once by adding `-a` to `args`."
|
||||
.to_string();
|
||||
}
|
||||
if lowered.contains("nothing added to commit but untracked files present") {
|
||||
return "Every change here is in a file git has never tracked, so a commit would be empty. \
|
||||
Add the new paths first with `{\"action\": \"add\", \"args\": [\".\"]}` — `-a` does \
|
||||
not pick up untracked files."
|
||||
.to_string();
|
||||
}
|
||||
if lowered.contains("nothing to commit") {
|
||||
return "The working tree is clean, so this change is already committed. Check \
|
||||
`{\"action\": \"log\"}` before making another one."
|
||||
.to_string();
|
||||
}
|
||||
let reported = [stderr.trim(), stdout.trim()]
|
||||
.into_iter()
|
||||
.filter(|stream| !stream.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
if reported.is_empty() {
|
||||
return "Git command failed (no output).".to_string();
|
||||
}
|
||||
// Anything else keeps git's own words, bounded — a usage dump is not an explanation.
|
||||
crate::output_limit::cap_lines(
|
||||
&format!("Git command failed: {reported}"),
|
||||
GIT_ERROR_MAX_LINES,
|
||||
"lines",
|
||||
"Run the command through `bash` if you need git's full output.",
|
||||
)
|
||||
}
|
||||
|
||||
/// Max lines of git's own error text passed through.
|
||||
pub(super) const GIT_ERROR_MAX_LINES: usize = 12;
|
||||
|
||||
/// Max lines of `gh`'s error text passed through.
|
||||
pub(super) const GH_ERROR_MAX_LINES: usize = 12;
|
||||
|
||||
/// Rewrite a `gh` failure that has a known cause into the sentence that fixes it.
|
||||
///
|
||||
/// `gh` reports these accurately but in its own vocabulary, and the useful half is often below the
|
||||
/// part a bounded result keeps. Which failure it was is decided by
|
||||
/// [`luxe_core::github::classify_failure`], the one reading of `gh`'s wording in the tree; this only
|
||||
/// picks the words. The rest is passed through untouched — guessing at an error nobody anticipated
|
||||
/// is how a tool starts lying about what went wrong.
|
||||
pub(super) fn explain_gh_failure(reported: &str) -> Option<&'static str> {
|
||||
use luxe_core::github::GitHubError;
|
||||
match luxe_core::github::classify_failure(reported, "") {
|
||||
GitHubError::NotAuthenticated { .. } => return Some(
|
||||
"the GitHub CLI is installed but not signed in — run `gh auth login` in a terminal \
|
||||
(it needs a browser or a device code, so the agent cannot do it for you)",
|
||||
),
|
||||
GitHubError::NotGitHub => {
|
||||
return Some(
|
||||
"this repository has no remote on a GitHub host, so there are no pull requests \
|
||||
for `gh` to work with — `git remote -v` shows where it points",
|
||||
)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let lower = reported.to_lowercase();
|
||||
if lower.contains("no pull requests match") || lower.contains("no open pull requests") {
|
||||
return Some("no pull request matches — nothing to report, rather than a failure");
|
||||
}
|
||||
None
|
||||
}
|
||||
154
crates/luxe-tools/src/git/run.rs
Normal file
154
crates/luxe-tools/src/git/run.rs
Normal file
@@ -0,0 +1,154 @@
|
||||
//! Running git and `gh` — bounded, with the tree reaped on a timeout and a failure explained.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::Result;
|
||||
|
||||
use super::failure::{explain_failure, GH_ERROR_MAX_LINES};
|
||||
use super::GitTool;
|
||||
|
||||
/// How long a `gh` invocation may take before it is reaped.
|
||||
///
|
||||
/// Every `gh` subcommand is a network call, so this is not a guess about speed — it is the bound
|
||||
/// that stops a hung connection from stalling the turn with nothing to cancel.
|
||||
const GH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
|
||||
|
||||
/// How long a `git` invocation may take before its process tree is reaped.
|
||||
///
|
||||
/// Deliberately under the engine's own deadline so this fires first, because only this one can kill
|
||||
/// the *tree*: the engine bounds a call by dropping the future, which reaps `git` and leaves the
|
||||
/// `gpg` pinentry or pre-commit hook it started running — holding `.git/index.lock` against every
|
||||
/// call that follows. Generous enough for a hook that runs a linter; the engine remains the backstop
|
||||
/// under any configuration that shortens its own bound.
|
||||
const GIT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(90);
|
||||
|
||||
impl GitTool {
|
||||
/// Run a git command and return its stdout.
|
||||
pub(super) async fn run_git(&self, cwd: &Path, args: &[&str]) -> Result<String> {
|
||||
let mut cmd = luxe_core::program::captured_command("git", args, cwd);
|
||||
// Git opens `$EDITOR` for a commit it has no message for, and that editor would inherit a
|
||||
// terminal the TUI owns while waiting for a human who cannot see it. Failing costs nothing:
|
||||
// every commit reaching here already carries a message or names where git should find one,
|
||||
// and `explain_failure` turns git's reply into the two arguments that would have worked.
|
||||
cmd.env("GIT_EDITOR", "false");
|
||||
|
||||
let output =
|
||||
run_bounded(cmd, "git", GIT_TIMEOUT, "a commit hook or a signing passphrase").await?;
|
||||
|
||||
if output.status.success() {
|
||||
Ok(String::from_utf8_lossy(&output.stdout).to_string())
|
||||
} else {
|
||||
Err(anyhow::anyhow!(
|
||||
"{}",
|
||||
explain_failure(
|
||||
&String::from_utf8_lossy(&output.stderr),
|
||||
&String::from_utf8_lossy(&output.stdout),
|
||||
cwd
|
||||
)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Make the branch a pull request can actually be opened from, or say why it cannot be.
|
||||
///
|
||||
/// `gh pr create` has one precondition it does not fix for you: the branch has to exist on the
|
||||
/// remote. Otherwise the call fails with a message about a head branch, and the model spends
|
||||
/// two round trips on `git push -u` and a retry, for a step that has exactly one correct
|
||||
/// answer.
|
||||
///
|
||||
/// Returns a line to prepend to the result when something was done, so a push is never silent.
|
||||
/// The push is plain — `--set-upstream`, never `--force` — because publishing a branch that
|
||||
/// does not exist yet cannot destroy anything, and rewriting one that does is a different
|
||||
/// operation with a different permission story.
|
||||
pub(super) async fn ready_branch_for_pr(&self, cwd: &Path) -> Result<Option<String>> {
|
||||
let branch = self.run_git(cwd, &["rev-parse", "--abbrev-ref", "HEAD"]).await?;
|
||||
let branch = branch.trim().to_string();
|
||||
if branch.is_empty() || branch == "HEAD" {
|
||||
anyhow::bail!(
|
||||
"HEAD is detached, so there is no branch to open a pull request from — \
|
||||
`git checkout -b <name>` first"
|
||||
);
|
||||
}
|
||||
// A pull request from trunk to trunk is not a thing, and the error `gh` gives for it sends
|
||||
// people looking at their remote rather than at their branch.
|
||||
if matches!(branch.as_str(), "main" | "master") {
|
||||
anyhow::bail!(
|
||||
"you are on `{branch}`, which is what a pull request would target — put the work \
|
||||
on its own branch first (`git checkout -b <name>`)"
|
||||
);
|
||||
}
|
||||
// An upstream already set means the branch is published; `gh` takes it from here.
|
||||
if self.run_git(cwd, &["rev-parse", "--abbrev-ref", "@{u}"]).await.is_ok() {
|
||||
return Ok(None);
|
||||
}
|
||||
self.run_git(cwd, &["push", "--set-upstream", "origin", &branch])
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!("could not publish `{branch}`: {error}"))?;
|
||||
Ok(Some(format!("Pushed `{branch}` to origin (it had no upstream), then:")))
|
||||
}
|
||||
|
||||
/// Run a `gh` command and return its stdout.
|
||||
///
|
||||
/// Resolved rather than assumed: `gh` installed by scoop, winget or Homebrew is frequently
|
||||
/// absent from the `PATH` an app inherits.
|
||||
pub(super) async fn run_gh(&self, cwd: &Path, args: &[&str]) -> Result<String> {
|
||||
let program = luxe_core::program::resolve("gh").ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"the GitHub CLI (`gh`) is not installed \u{2014} see https://cli.github.com, then run \
|
||||
`gh auth login`"
|
||||
)
|
||||
})?;
|
||||
let cmd = luxe_core::program::captured_command(program, args, cwd);
|
||||
let output = run_bounded(cmd, "gh", GH_TIMEOUT, "network access").await?;
|
||||
|
||||
if output.status.success() {
|
||||
Ok(String::from_utf8_lossy(&output.stdout).to_string())
|
||||
} else {
|
||||
// Same trap as `git`: a failure whose only words went to stdout would otherwise come
|
||||
// back as a bare "gh command failed:" with the reason cut off.
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let reported = match stderr.trim() {
|
||||
"" => stdout.trim(),
|
||||
text => text,
|
||||
};
|
||||
Err(anyhow::anyhow!(
|
||||
"gh command failed{}",
|
||||
match reported {
|
||||
"" => " (no output).".to_string(),
|
||||
text => format!(
|
||||
": {}",
|
||||
crate::output_limit::cap_lines(
|
||||
text,
|
||||
GH_ERROR_MAX_LINES,
|
||||
"lines of gh output",
|
||||
"Run the command directly to see the rest.",
|
||||
)
|
||||
),
|
||||
}
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `cmd` to completion under `deadline`, killing its whole tree if it expires.
|
||||
///
|
||||
/// `waiting_for` names the usual culprit, so a timeout is a lead rather than a shrug.
|
||||
async fn run_bounded(
|
||||
cmd: tokio::process::Command,
|
||||
program: &str,
|
||||
deadline: std::time::Duration,
|
||||
waiting_for: &str,
|
||||
) -> Result<std::process::Output> {
|
||||
use luxe_core::program::BoundedRunError;
|
||||
luxe_core::program::run_bounded(cmd, deadline).await.map_err(|error| match error {
|
||||
BoundedRunError::Timeout { after } => anyhow::anyhow!(
|
||||
"{program} timed out after {}s \u{2014} {waiting_for} is the usual cause; run the \
|
||||
command yourself to see what it is waiting for",
|
||||
after.as_secs()
|
||||
),
|
||||
BoundedRunError::Spawn(source) | BoundedRunError::Wait(source) => {
|
||||
anyhow::Error::new(source).context(format!("Failed to execute {program} command"))
|
||||
}
|
||||
})
|
||||
}
|
||||
746
crates/luxe-tools/src/git/tests.rs
Normal file
746
crates/luxe-tools/src/git/tests.rs
Normal file
@@ -0,0 +1,746 @@
|
||||
use super::failure::{explain_failure, explain_gh_failure, GIT_ERROR_MAX_LINES};
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
fn test_context(tmp_dir: &std::path::Path) -> ToolContext {
|
||||
let (event_tx, _event_rx) = mpsc::channel(64);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
ToolContext {
|
||||
cwd: tmp_dir.to_path_buf(),
|
||||
session_id: "test-session".to_string(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_git_missing_action() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({}), &ctx).await;
|
||||
assert!(result.is_error);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_git_unknown_action() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({"action": "invalid"}), &ctx).await;
|
||||
assert!(result.is_error);
|
||||
}
|
||||
|
||||
/// The reply to an action nobody knows lists every action the schema offers.
|
||||
///
|
||||
/// The break this catches: the list was typed out by hand and stopped at `pr`, so a model that
|
||||
/// misspelled `checks` was told `show`, `issue` and `checks` did not exist.
|
||||
#[tokio::test]
|
||||
async fn an_unknown_action_names_every_action_the_schema_offers() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({"action": "invalid"}), &ctx).await;
|
||||
let luxe_core::ContentBlock::Text(said) = &result.content[0] else { panic!("text") };
|
||||
let schema = tool.schema();
|
||||
let offered = schema.parameters["properties"]["action"]["enum"].as_array().unwrap();
|
||||
for action in offered {
|
||||
let name = action.as_str().unwrap();
|
||||
assert!(said.contains(name), "{name} is missing from: {said}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The schema and the dispatcher cannot drift: every action the schema offers is one the tool
|
||||
/// parses, and every action it parses is offered.
|
||||
#[test]
|
||||
fn every_action_in_the_schema_parses_and_every_parsed_action_is_in_the_schema() {
|
||||
let schema = GitTool::new().schema();
|
||||
let offered: Vec<&str> = schema.parameters["properties"]["action"]["enum"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|action| action.as_str().unwrap())
|
||||
.collect();
|
||||
for name in &offered {
|
||||
let parsed = GitAction::parse(name).unwrap_or_else(|| panic!("`{name}` does not parse"));
|
||||
assert_eq!(parsed.name(), *name);
|
||||
}
|
||||
let parsed: Vec<&str> = GitAction::ALL.map(GitAction::name).to_vec();
|
||||
assert_eq!(parsed, offered, "the same actions, in the schema's order");
|
||||
}
|
||||
|
||||
/// What each action runs, bare and with arguments: the defaults a caller relies on, and that the
|
||||
/// arguments it gives are the ones git gets.
|
||||
#[test]
|
||||
fn each_action_plans_the_git_command_it_names() {
|
||||
let planned = |action: GitAction, request: &[&str]| {
|
||||
let request: Vec<String> = request.iter().map(|arg| arg.to_string()).collect();
|
||||
let plan = plan(action, &serde_json::json!({}), &request)
|
||||
.unwrap_or_else(|_| panic!("{action:?} plans"));
|
||||
plan.argv.join(" ")
|
||||
};
|
||||
assert_eq!(planned(GitAction::Status, &[]), "status --short");
|
||||
assert_eq!(planned(GitAction::Diff, &[]), "diff --unified=3");
|
||||
assert_eq!(planned(GitAction::Diff, &["--stat"]), "diff --stat");
|
||||
assert_eq!(planned(GitAction::Show, &["HEAD", "--stat"]), "show HEAD --stat");
|
||||
assert_eq!(planned(GitAction::Log, &[]), "log --oneline -11");
|
||||
assert_eq!(planned(GitAction::Log, &["-n", "3"]), "log -n 3");
|
||||
assert_eq!(planned(GitAction::Add, &["a.rs", "b.rs"]), "add a.rs b.rs");
|
||||
assert_eq!(planned(GitAction::Branch, &[]), "branch -a");
|
||||
assert_eq!(planned(GitAction::Branch, &["-d", "old"]), "branch -d old");
|
||||
assert_eq!(planned(GitAction::Checkout, &["topic"]), "checkout topic");
|
||||
assert_eq!(planned(GitAction::Stash, &[]), "stash push");
|
||||
|
||||
// Naming nothing where something is needed is refused before git is asked
|
||||
for action in [GitAction::Add, GitAction::Checkout] {
|
||||
let Err(refusal) = plan(action, &serde_json::json!({}), &[]) else { panic!("{action:?}") };
|
||||
assert!(refusal.is_error);
|
||||
}
|
||||
// and an action that goes to `gh` is not a git command
|
||||
assert!(plan(GitAction::Pr, &serde_json::json!({}), &[]).is_err());
|
||||
}
|
||||
|
||||
/// How each answer is told: a clean tree, an empty diff and history, and a staged add each say so
|
||||
/// rather than returning nothing.
|
||||
#[test]
|
||||
fn an_empty_answer_says_what_it_means() {
|
||||
assert_eq!(Shape::OrMessage("clean").tell(" \n"), "clean");
|
||||
assert_eq!(Shape::OrMessage("clean").tell(" M a.rs\n"), " M a.rs\n");
|
||||
let diff = Shape::Capped { max: 10, noun: "lines", hint: "", empty: Some("no changes") };
|
||||
assert_eq!(diff.tell(""), "no changes");
|
||||
assert_eq!(Shape::LogDefault.tell(""), "no commits matched");
|
||||
assert_eq!(Shape::Said("Files staged.").tell("anything"), "Files staged.");
|
||||
assert_eq!(Shape::Trimmed.tell(" x\n"), "x");
|
||||
assert_eq!(Shape::Raw.tell(" x\n"), " x\n");
|
||||
}
|
||||
|
||||
/// A repository with one commit on a branch, and a bare "remote" it can really push to.
|
||||
///
|
||||
/// A real remote rather than a mock: the whole point of the preflight is what `git` does about
|
||||
/// an upstream, and an upstream that no command could ever set is not the thing under test.
|
||||
///
|
||||
/// `cfg(unix)` for the same reason its callers are — it silences the global git config with
|
||||
/// `/dev/null`, so a contributor's own `init.defaultBranch` cannot change what is under test.
|
||||
#[cfg(unix)]
|
||||
fn repo_with_remote() -> (TempDir, std::path::PathBuf) {
|
||||
let dir = TempDir::new().expect("tempdir");
|
||||
let remote = dir.path().join("remote.git");
|
||||
let work = dir.path().join("work");
|
||||
let run = |args: &[&str], cwd: &std::path::Path| {
|
||||
let status = std::process::Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.env("GIT_CONFIG_GLOBAL", "/dev/null")
|
||||
.env("GIT_CONFIG_SYSTEM", "/dev/null")
|
||||
.output()
|
||||
.expect("git runs");
|
||||
assert!(status.status.success(), "git {args:?}: {:?}", status);
|
||||
};
|
||||
std::fs::create_dir_all(&work).expect("mkdir");
|
||||
run(&["init", "--bare", "-b", "main", remote.to_str().expect("utf8")], dir.path());
|
||||
run(&["init", "-b", "main"], &work);
|
||||
run(&["config", "user.email", "t@example.com"], &work);
|
||||
run(&["config", "user.name", "Test"], &work);
|
||||
std::fs::write(work.join("a.txt"), "x").expect("write");
|
||||
run(&["add", "."], &work);
|
||||
run(&["commit", "-m", "first"], &work);
|
||||
run(&["remote", "add", "origin", remote.to_str().expect("utf8")], &work);
|
||||
(dir, work)
|
||||
}
|
||||
|
||||
/// A bare `log` shows ten commits and says when there are older ones, rather than letting ten
|
||||
/// read as the whole history; exactly ten says nothing more.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_bare_log_says_when_history_goes_on() {
|
||||
let (_dir, work) = repo_with_remote();
|
||||
let commit = |message: &str| {
|
||||
let output = std::process::Command::new("git")
|
||||
.args(["commit", "--allow-empty", "-q", "-m", message])
|
||||
.current_dir(&work)
|
||||
.env("GIT_CONFIG_GLOBAL", "/dev/null")
|
||||
.output()
|
||||
.expect("git runs");
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
};
|
||||
for n in 2..=10 {
|
||||
commit(&format!("commit {n}"));
|
||||
}
|
||||
let tool = GitTool::new();
|
||||
let cx = test_context(&work);
|
||||
let log = || tool.run(serde_json::json!({"action": "log"}), &cx);
|
||||
let luxe_core::ContentBlock::Text(ten) = &log().await.content[0] else { panic!("text") };
|
||||
assert_eq!(ten.lines().count(), 10, "{ten}");
|
||||
assert!(!ten.contains("older commits"), "{ten}");
|
||||
commit("commit 11");
|
||||
let luxe_core::ContentBlock::Text(eleven) = &log().await.content[0] else { panic!("text") };
|
||||
assert!(eleven.lines().next().unwrap().ends_with("commit 11"), "{eleven}");
|
||||
assert!(!eleven.contains(" first"), "the oldest is the one left out: {eleven}");
|
||||
assert!(eleven.ends_with("or a path for more."), "{eleven}");
|
||||
}
|
||||
|
||||
/// The preflight's whole reason for existing: a branch nobody has pushed gets published, so
|
||||
/// `gh pr create` meets the precondition it will not fix for itself.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_pull_request_publishes_its_branch_first() {
|
||||
let (_dir, work) = repo_with_remote();
|
||||
let run = |args: &[&str]| {
|
||||
std::process::Command::new("git").args(args).current_dir(&work).output().expect("git runs");
|
||||
};
|
||||
run(&["checkout", "-b", "feature"]);
|
||||
|
||||
let tool = GitTool::new();
|
||||
let note = tool.ready_branch_for_pr(&work).await.expect("the branch can be published");
|
||||
assert!(
|
||||
note.as_deref().is_some_and(|line| line.contains("feature")),
|
||||
"a push is never silent: {note:?}"
|
||||
);
|
||||
|
||||
// Really published, and a second call is now a no-op rather than a second push.
|
||||
let upstream = tool
|
||||
.run_git(&work, &["rev-parse", "--abbrev-ref", "@{u}"])
|
||||
.await
|
||||
.expect("an upstream exists now");
|
||||
assert_eq!(upstream.trim(), "origin/feature");
|
||||
assert_eq!(tool.ready_branch_for_pr(&work).await.expect("still fine"), None);
|
||||
}
|
||||
|
||||
/// Opening a pull request from trunk cannot work, and `gh`'s own error for it sends people to
|
||||
/// look at their remote instead of at their branch.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_pull_request_from_trunk_is_refused_with_the_fix() {
|
||||
let (_dir, work) = repo_with_remote();
|
||||
let error =
|
||||
GitTool::new().ready_branch_for_pr(&work).await.expect_err("main cannot target main");
|
||||
let said = error.to_string();
|
||||
assert!(said.contains("main"), "{said}");
|
||||
assert!(said.contains("checkout -b"), "names the fix: {said}");
|
||||
}
|
||||
|
||||
/// A detached HEAD has no branch to publish, and saying "push failed" there would be a
|
||||
/// diagnosis of the wrong problem.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_detached_head_is_named_as_the_problem() {
|
||||
let (_dir, work) = repo_with_remote();
|
||||
std::process::Command::new("git")
|
||||
.args(["checkout", "--detach", "HEAD"])
|
||||
.current_dir(&work)
|
||||
.output()
|
||||
.expect("git runs");
|
||||
let error = GitTool::new().ready_branch_for_pr(&work).await.expect_err("nothing to push");
|
||||
assert!(error.to_string().contains("detached"), "{error}");
|
||||
}
|
||||
|
||||
/// Only `create` has a precondition; a read must not push anything.
|
||||
#[test]
|
||||
fn only_creating_a_pull_request_triggers_the_preflight() {
|
||||
assert!(is_pr_create(&["create".to_string(), "--title".to_string()]));
|
||||
for read_only in [vec![], vec!["list".to_string()], vec!["view".to_string()]] {
|
||||
assert!(!is_pr_create(&read_only), "{read_only:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The one `gh` failure a person can actually act on, in words that say what to do.
|
||||
#[test]
|
||||
fn a_signed_out_gh_is_explained_rather_than_echoed() {
|
||||
for raw in [
|
||||
"gh command failed: To get started with GitHub CLI, please run: gh auth login",
|
||||
"HTTP 401: Requires authentication",
|
||||
] {
|
||||
let explained = explain_gh_failure(raw).expect("a known cause");
|
||||
assert!(explained.contains("gh auth login"), "{explained}");
|
||||
}
|
||||
// Anything unrecognized is passed through rather than guessed at.
|
||||
assert_eq!(explain_gh_failure("something nobody anticipated"), None);
|
||||
}
|
||||
|
||||
/// `gh`'s "no GitHub remote" message ends by suggesting `gh auth login`. Read as a sign-in
|
||||
/// problem, it sent the reader to fix an account that was fine.
|
||||
#[test]
|
||||
fn a_repository_without_a_github_remote_is_not_a_sign_in_problem() {
|
||||
let explained = explain_gh_failure(
|
||||
"gh command failed: none of the git remotes configured for this repository point to a \
|
||||
known GitHub host. To tell gh about a new GitHub host, please use `gh auth login`",
|
||||
)
|
||||
.expect("a known cause");
|
||||
assert!(explained.contains("no remote on a GitHub host"), "{explained}");
|
||||
assert!(!explained.contains("not signed in"), "{explained}");
|
||||
}
|
||||
|
||||
/// The defect this guards was silent by construction: everything after the subaction was
|
||||
/// dropped, so a fully-specified `pr create` arrived at `gh` as a bare one and sat waiting for
|
||||
/// the title it had already been given.
|
||||
#[test]
|
||||
fn every_pr_argument_reaches_gh() {
|
||||
let requested: Vec<String> = ["create", "--title", "Fix the thing", "--body", "why", "--draft"]
|
||||
.iter()
|
||||
.map(|part| (*part).to_string())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
gh_args("pr", &requested),
|
||||
["pr", "create", "--title", "Fix the thing", "--body", "why", "--draft"]
|
||||
);
|
||||
|
||||
assert_eq!(gh_args("pr", &[]), ["pr", "list"], "no subaction is a listing, not an error");
|
||||
assert_eq!(gh_args("pr", &["view".to_string()]), ["pr", "view"]);
|
||||
let issue: Vec<String> = ["view", "12", "--comments"].map(String::from).to_vec();
|
||||
assert_eq!(gh_args("issue", &issue), ["issue", "view", "12", "--comments"]);
|
||||
assert_eq!(gh_args("issue", &[]), ["issue", "list"]);
|
||||
}
|
||||
|
||||
/// The same defect as [`every_pr_argument_reaches_gh`], one arm away and still live: only the
|
||||
/// subaction survived, so the `-m wip` that names a stash entry was dropped on the floor.
|
||||
#[test]
|
||||
fn every_stash_argument_reaches_git() {
|
||||
let requested: Vec<String> =
|
||||
["push", "-m", "wip", "--keep-index"].iter().map(|part| (*part).to_string()).collect();
|
||||
assert_eq!(stash_args(&requested), ["stash", "push", "-m", "wip", "--keep-index"]);
|
||||
|
||||
assert_eq!(stash_args(&[]), ["stash", "push"], "no subaction stashes, as it always did");
|
||||
assert_eq!(stash_args(&["pop".to_string()]), ["stash", "pop"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_git_status_not_repo() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({"action": "status"}), &ctx).await;
|
||||
// Should fail because tmp_dir is not a git repo
|
||||
assert!(result.is_error);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_git_commit_missing_message() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({"action": "commit"}), &ctx).await;
|
||||
assert!(result.is_error);
|
||||
let luxe_core::ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("\"message\""), "a refusal shows the call that works: {text}");
|
||||
}
|
||||
|
||||
/// No refusal may demand an argument the schema never offered.
|
||||
///
|
||||
/// The defect this guards was invisible from either side on its own. `commit` read a top-level
|
||||
/// `message`; `schema()` advertised `action` and `args` and nothing else. Both halves read fine
|
||||
/// in isolation, and together they meant the only call a model could build from the schema was
|
||||
/// the one call the tool rejected — which a real session hit three times before giving up and
|
||||
/// shelling out. So: hand every action everything the schema offers, and nothing may come back
|
||||
/// saying something is missing.
|
||||
#[tokio::test]
|
||||
async fn no_action_demands_an_argument_the_schema_never_offered() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
if !init_repo(tmp_dir.path()) {
|
||||
eprintln!("skipping: git unavailable");
|
||||
return;
|
||||
}
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
let schema = tool.schema();
|
||||
let properties = schema.parameters["properties"].as_object().expect("an object schema");
|
||||
let actions =
|
||||
properties["action"]["enum"].as_array().expect("the actions are enumerated").clone();
|
||||
|
||||
for action in actions {
|
||||
let mut call = serde_json::Map::new();
|
||||
call.insert("action".to_string(), action.clone());
|
||||
// Everything else the schema offers, filled with the most harmless value that fits, so
|
||||
// any complaint left is about something the schema never mentioned.
|
||||
for (name, spec) in properties.iter().filter(|(name, _)| *name != "action") {
|
||||
let value = match spec["type"].as_str() {
|
||||
Some("array") => serde_json::json!(["."]),
|
||||
_ => serde_json::json!("placeholder"),
|
||||
};
|
||||
call.insert(name.clone(), value);
|
||||
}
|
||||
|
||||
let result = tool.run(serde_json::Value::Object(call), &ctx).await;
|
||||
let luxe_core::ContentBlock::Text(text) = &result.content[0] else {
|
||||
panic!("expected text")
|
||||
};
|
||||
let lowered = text.to_ascii_lowercase();
|
||||
assert!(
|
||||
!lowered.contains("is required") && !lowered.contains("must include"),
|
||||
"`{action}` was handed every declared argument and still reports one missing: \
|
||||
{text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every spelling of a commit message reaches a real repository as a real commit.
|
||||
///
|
||||
/// [`crate::git::args`] proves the argument list; this proves the wiring, against git itself.
|
||||
#[tokio::test]
|
||||
async fn a_commit_message_lands_however_it_was_spelled() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
if !init_repo(tmp_dir.path()) {
|
||||
eprintln!("skipping: git unavailable");
|
||||
return;
|
||||
}
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let spellings = [
|
||||
serde_json::json!({"action": "commit", "message": "canonical"}),
|
||||
serde_json::json!({"action": "commit", "args": ["-m", "inside args"]}),
|
||||
serde_json::json!({"action": "commit", "args": ["a bare argument"]}),
|
||||
];
|
||||
for (nth, call) in spellings.iter().enumerate() {
|
||||
std::fs::write(tmp_dir.path().join(format!("{nth}.txt")), "x").unwrap();
|
||||
let staged = tool.run(serde_json::json!({"action": "add", "args": ["."]}), &ctx).await;
|
||||
assert!(!staged.is_error, "staging failed");
|
||||
|
||||
let result = tool.run(call.clone(), &ctx).await;
|
||||
let luxe_core::ContentBlock::Text(text) = &result.content[0] else {
|
||||
panic!("expected text")
|
||||
};
|
||||
assert!(!result.is_error, "{call} was refused: {text}");
|
||||
}
|
||||
|
||||
let log = tool.run(serde_json::json!({"action": "log", "args": ["--format=%s"]}), &ctx).await;
|
||||
let luxe_core::ContentBlock::Text(text) = &log.content[0] else { panic!("expected text") };
|
||||
let subjects: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(subjects, ["a bare argument", "inside args", "canonical"], "{text}");
|
||||
}
|
||||
|
||||
/// `show` reads a file as a revision has it, which is how a pull request that is not checked
|
||||
/// out is read without the shell.
|
||||
#[tokio::test]
|
||||
async fn show_reads_a_file_at_a_revision() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
if !init_repo(tmp_dir.path()) {
|
||||
eprintln!("skipping: git unavailable");
|
||||
return;
|
||||
}
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
let file = tmp_dir.path().join("a.txt");
|
||||
std::fs::write(&file, "as committed\n").unwrap();
|
||||
tool.run(serde_json::json!({"action": "add", "args": ["."]}), &ctx).await;
|
||||
tool.run(serde_json::json!({"action": "commit", "message": "base"}), &ctx).await;
|
||||
std::fs::write(&file, "since\n").unwrap();
|
||||
|
||||
let shown = tool.run(serde_json::json!({"action": "show", "args": ["HEAD:a.txt"]}), &ctx).await;
|
||||
let luxe_core::ContentBlock::Text(text) = &shown.content[0] else { panic!("text") };
|
||||
assert!(!shown.is_error, "{text}");
|
||||
assert_eq!(text.trim(), "as committed");
|
||||
}
|
||||
|
||||
/// The defect end to end, against git itself: an unstaged commit must come back saying why.
|
||||
///
|
||||
/// Pinned here as well as at [`explain_failure`] because the bug was neither in the wording
|
||||
/// nor in git — it was the one stream the runner threw away, and only a real invocation has
|
||||
/// two streams to throw away.
|
||||
#[tokio::test]
|
||||
async fn committing_with_nothing_staged_says_what_to_stage() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
if !init_repo(tmp_dir.path()) {
|
||||
eprintln!("skipping: git unavailable");
|
||||
return;
|
||||
}
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
let file = tmp_dir.path().join("a.txt");
|
||||
|
||||
std::fs::write(&file, "one").unwrap();
|
||||
tool.run(serde_json::json!({"action": "add", "args": ["."]}), &ctx).await;
|
||||
tool.run(serde_json::json!({"action": "commit", "message": "base"}), &ctx).await;
|
||||
std::fs::write(&file, "two").unwrap();
|
||||
|
||||
let refused =
|
||||
tool.run(serde_json::json!({"action": "commit", "message": "unstaged"}), &ctx).await;
|
||||
let luxe_core::ContentBlock::Text(text) = &refused.content[0] else { panic!("expected text") };
|
||||
assert!(refused.is_error, "an unstaged commit is a failure: {text}");
|
||||
assert!(!text.contains("no output"), "git said plenty, on stdout: {text}");
|
||||
assert!(text.contains("Nothing is staged"), "{text}");
|
||||
|
||||
// And the fix it names actually works, through this tool.
|
||||
tool.run(serde_json::json!({"action": "add", "args": ["."]}), &ctx).await;
|
||||
let committed =
|
||||
tool.run(serde_json::json!({"action": "commit", "message": "staged"}), &ctx).await;
|
||||
assert!(!committed.is_error, "{:?}", committed.content);
|
||||
}
|
||||
|
||||
/// A commit that reuses an existing message needs no `message`, and used to be unreachable.
|
||||
#[tokio::test]
|
||||
async fn amending_with_no_edit_keeps_the_message_it_already_had() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
if !init_repo(tmp_dir.path()) {
|
||||
eprintln!("skipping: git unavailable");
|
||||
return;
|
||||
}
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
std::fs::write(tmp_dir.path().join("a.txt"), "one").unwrap();
|
||||
tool.run(serde_json::json!({"action": "add", "args": ["."]}), &ctx).await;
|
||||
tool.run(serde_json::json!({"action": "commit", "message": "the subject"}), &ctx).await;
|
||||
|
||||
std::fs::write(tmp_dir.path().join("a.txt"), "two").unwrap();
|
||||
tool.run(serde_json::json!({"action": "add", "args": ["."]}), &ctx).await;
|
||||
let amended = tool
|
||||
.run(serde_json::json!({"action": "commit", "args": ["--amend", "--no-edit"]}), &ctx)
|
||||
.await;
|
||||
let luxe_core::ContentBlock::Text(text) = &amended.content[0] else { panic!("expected text") };
|
||||
assert!(!amended.is_error, "{text}");
|
||||
|
||||
let log = tool.run(serde_json::json!({"action": "log", "args": ["--format=%s"]}), &ctx).await;
|
||||
let luxe_core::ContentBlock::Text(text) = &log.content[0] else { panic!("expected text") };
|
||||
assert_eq!(text.lines().collect::<Vec<_>>(), ["the subject"], "one commit, same subject");
|
||||
}
|
||||
|
||||
/// The `stash` action forwards what it was given, proven against git rather than against
|
||||
/// [`stash_args`] alone — the argument list was already right in isolation, and the arm calling
|
||||
/// it is where the label used to go missing.
|
||||
#[tokio::test]
|
||||
async fn a_named_stash_keeps_its_name() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
if !init_repo(tmp_dir.path()) {
|
||||
eprintln!("skipping: git unavailable");
|
||||
return;
|
||||
}
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
let file = tmp_dir.path().join("a.txt");
|
||||
|
||||
std::fs::write(&file, "one").unwrap();
|
||||
tool.run(serde_json::json!({"action": "add", "args": ["."]}), &ctx).await;
|
||||
tool.run(serde_json::json!({"action": "commit", "message": "base"}), &ctx).await;
|
||||
std::fs::write(&file, "two").unwrap();
|
||||
|
||||
let stashed = tool
|
||||
.run(
|
||||
serde_json::json!({"action": "stash", "args": ["push", "-m", "the named entry"]}),
|
||||
&ctx,
|
||||
)
|
||||
.await;
|
||||
let luxe_core::ContentBlock::Text(text) = &stashed.content[0] else { panic!("expected text") };
|
||||
assert!(!stashed.is_error, "{text}");
|
||||
|
||||
let listed = std::process::Command::new("git")
|
||||
.args(["stash", "list"])
|
||||
.current_dir(tmp_dir.path())
|
||||
.output()
|
||||
.expect("git runs");
|
||||
let listed = String::from_utf8_lossy(&listed.stdout);
|
||||
assert!(listed.contains("the named entry"), "the label reached git: {listed:?}");
|
||||
}
|
||||
|
||||
/// Git asking for an editor is a hang everywhere else; here it is closed off, and the reply
|
||||
/// names the two arguments that would have worked instead of git's `-m`/`-F`.
|
||||
#[test]
|
||||
fn an_editor_prompt_is_answered_with_the_arguments_this_tool_takes() {
|
||||
let explained = explain_failure(
|
||||
"error: there was a problem with the editor 'false'\n\
|
||||
Please supply the message using either -m or -F option.",
|
||||
"",
|
||||
std::path::Path::new("/tmp/work"),
|
||||
);
|
||||
assert!(explained.contains("`message`"), "{explained}");
|
||||
assert!(explained.contains("--no-edit"), "{explained}");
|
||||
}
|
||||
|
||||
/// A repository that can commit: `init` plus the identity git refuses to invent.
|
||||
fn init_repo(path: &std::path::Path) -> bool {
|
||||
let run = |args: &[&str]| {
|
||||
std::process::Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(path)
|
||||
.output()
|
||||
.is_ok_and(|output| output.status.success())
|
||||
};
|
||||
run(&["init", "--quiet"])
|
||||
&& run(&["config", "user.email", "test@luxe.invalid"])
|
||||
&& run(&["config", "user.name", "Luxe Test"])
|
||||
// A signing key the machine may not have would fail every commit here.
|
||||
&& run(&["config", "commit.gpgsign", "false"])
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_clean_tree_says_so_instead_of_returning_nothing() {
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
// A real (empty) repo: `git status --short` prints nothing at all.
|
||||
let init = tokio::process::Command::new("git")
|
||||
.args(["init", "--quiet"])
|
||||
.current_dir(tmp_dir.path())
|
||||
.status()
|
||||
.await;
|
||||
if !matches!(init, Ok(status) if status.success()) {
|
||||
eprintln!("skipping: git unavailable");
|
||||
return;
|
||||
}
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({"action": "status"}), &ctx).await;
|
||||
assert!(!result.is_error);
|
||||
let luxe_core::ContentBlock::Text(text) = &result.content[0] else {
|
||||
panic!("expected text");
|
||||
};
|
||||
assert!(text.contains("clean"), "an empty status explains itself: {text:?}");
|
||||
|
||||
let diff = tool.run(serde_json::json!({"action": "diff"}), &ctx).await;
|
||||
let luxe_core::ContentBlock::Text(text) = &diff.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("no changes"), "an empty diff explains itself: {text:?}");
|
||||
}
|
||||
|
||||
/// A failing `gh` hands its own stderr back, rather than an empty complaint.
|
||||
///
|
||||
/// The break this catches, measured against the installed binary: `spawn` leaves stdout and
|
||||
/// stderr **inherited** — only `Command::output` pipes them — so this call reported
|
||||
/// "gh command failed:" with nothing after the colon while `gh`'s actual message ("no git
|
||||
/// remotes found") went to the terminal, on top of the TUI. Runs only where `gh` is installed,
|
||||
/// in a directory with no remote, which is a reliable way to make it fail without a network.
|
||||
#[tokio::test]
|
||||
async fn a_failing_gh_reports_what_gh_said() {
|
||||
if !luxe_core::program::is_available("gh") {
|
||||
return;
|
||||
}
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
// A repository with no remote: `gh pr list` refuses immediately and says why.
|
||||
std::process::Command::new("git")
|
||||
.args(["init", "-q"])
|
||||
.current_dir(tmp_dir.path())
|
||||
.output()
|
||||
.expect("git runs");
|
||||
|
||||
let tool = GitTool::new();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
let result = tool.run(serde_json::json!({"action": "pr"}), &ctx).await;
|
||||
|
||||
assert!(result.is_error, "a repository with no remote has no pull requests");
|
||||
let luxe_core::ContentBlock::Text(text) = &result.content[0] else {
|
||||
panic!("Expected Text content block")
|
||||
};
|
||||
|
||||
// The property, not the particular complaint. `gh` fails here for whatever reason the
|
||||
// machine supplies — "no git remotes found" on a developer's box, "set the GH_TOKEN
|
||||
// environment variable" on a CI runner — and asserting either one pins the test to one
|
||||
// environment, which is how the first version of it passed locally and failed in CI. What
|
||||
// has to hold everywhere is that a reason comes back: gh's own words, or the sentence a
|
||||
// recognized cause is rewritten into. The bug was an empty tail.
|
||||
let reason = text
|
||||
.strip_prefix("gh pr failed:")
|
||||
.map(|tail| tail.trim().trim_start_matches("gh command failed:").trim())
|
||||
.unwrap_or_default();
|
||||
assert!(!reason.is_empty(), "a reason must come back, got {text:?}");
|
||||
assert!(!reason.contains("(no output)"), "a reason must come back, got {text:?}");
|
||||
}
|
||||
|
||||
/// Without `gh` on PATH, `pr` says so and says what to do about it.
|
||||
///
|
||||
/// The break this catches: the old answer was "GitHub CLI integration is not enabled", gated on
|
||||
/// a `GitConfig` flag that nothing could set — `GitConfig::default()` is what registers the tool
|
||||
/// — so the action was unreachable and its error named an internal switch instead of the program
|
||||
/// the user has to install. Skipped where `gh` really is installed, since then there is nothing
|
||||
/// to report.
|
||||
#[tokio::test]
|
||||
async fn pr_without_the_github_cli_names_the_missing_program() {
|
||||
if luxe_core::program::is_available("gh") {
|
||||
return;
|
||||
}
|
||||
let tool = GitTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({"action": "pr"}), &ctx).await;
|
||||
assert!(result.is_error);
|
||||
let luxe_core::ContentBlock::Text(text) = &result.content[0] else {
|
||||
panic!("Expected Text content block")
|
||||
};
|
||||
assert!(text.contains("`gh`"), "name the program: {text}");
|
||||
assert!(text.contains("auth login"), "and what it needs after installing: {text}");
|
||||
}
|
||||
|
||||
/// Outside a repo, git answers `status` with a filesystem-boundary note and `diff` with its
|
||||
/// entire usage screen. Neither states the fact that matters.
|
||||
#[test]
|
||||
fn outside_a_repository_the_error_says_so_in_one_line() {
|
||||
let stderr = "fatal: not a git repository (or any parent up to mount point /)\n\
|
||||
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).";
|
||||
let explained = explain_failure(stderr, "", std::path::Path::new("/tmp/work"));
|
||||
|
||||
assert!(explained.starts_with("Not a git repository"), "{explained}");
|
||||
assert!(explained.contains("/tmp/work"), "names the directory: {explained}");
|
||||
assert!(explained.contains("read"), "and says what to do instead: {explained}");
|
||||
assert!(!explained.contains("GIT_DISCOVERY"), "plumbing noise is dropped: {explained}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_usage_dump_is_bounded_rather_than_pasted_whole() {
|
||||
let usage = vec![" -p, --patch generate patch"; 40].join("\n");
|
||||
let explained = explain_failure(&usage, "", std::path::Path::new("/tmp/work"));
|
||||
assert!(explained.lines().count() <= GIT_ERROR_MAX_LINES + 3, "{explained}");
|
||||
assert!(explained.contains("more lines not shown"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_real_git_error_keeps_gits_own_words() {
|
||||
let explained =
|
||||
explain_failure("error: pathspec 'nope' did not match", "", std::path::Path::new("."));
|
||||
assert!(explained.contains("pathspec 'nope' did not match"), "{explained}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_stderr_still_says_something() {
|
||||
assert!(explain_failure(" ", "", std::path::Path::new(".")).contains("no output"));
|
||||
}
|
||||
|
||||
/// Git says why a commit was refused on **stdout**, and exits 1 with an empty stderr. Reading
|
||||
/// one stream reported "no output" for the single most common commit failure there is.
|
||||
#[test]
|
||||
fn a_refusal_git_wrote_to_stdout_is_not_reported_as_no_output() {
|
||||
let refused = "On branch master\nChanges not staged for commit:\n\tmodified: f.txt\n\n\
|
||||
no changes added to commit (use \"git add\" and/or \"git commit -a\")";
|
||||
let explained = explain_failure("", refused, std::path::Path::new("."));
|
||||
|
||||
assert!(!explained.contains("no output"), "{explained}");
|
||||
assert!(explained.contains("Nothing is staged"), "names the cause: {explained}");
|
||||
assert!(explained.contains("\"action\": \"add\""), "and this tool's fix: {explained}");
|
||||
assert!(explained.contains("-a"), "and the one-call alternative: {explained}");
|
||||
}
|
||||
|
||||
/// The three refusals are corrected differently, so each gets its own answer: `-a` picks up a
|
||||
/// tracked modification and will never pick up an untracked file.
|
||||
#[test]
|
||||
fn each_reason_a_commit_is_refused_gets_its_own_answer() {
|
||||
let untracked = explain_failure(
|
||||
"",
|
||||
"nothing added to commit but untracked files present (use \"git add\" to track)",
|
||||
std::path::Path::new("."),
|
||||
);
|
||||
assert!(untracked.contains("never tracked"), "{untracked}");
|
||||
assert!(untracked.contains("`-a` does not"), "and why -a will not do: {untracked}");
|
||||
|
||||
let clean =
|
||||
explain_failure("", "nothing to commit, working tree clean", std::path::Path::new("."));
|
||||
assert!(clean.contains("already committed"), "{clean}");
|
||||
assert!(!clean.contains("Nothing to commit:"), "not two colons in one line: {clean}");
|
||||
assert!(!clean.contains("Stage them"), "there is nothing to stage: {clean}");
|
||||
}
|
||||
|
||||
/// When git splits its report across both streams, neither half is dropped.
|
||||
#[test]
|
||||
fn both_streams_reach_the_caller() {
|
||||
let explained = explain_failure(
|
||||
"Recorded preimage for 'f.txt'",
|
||||
"CONFLICT (content): Merge conflict in f.txt",
|
||||
std::path::Path::new("."),
|
||||
);
|
||||
assert!(explained.contains("CONFLICT (content)"), "{explained}");
|
||||
assert!(explained.contains("Recorded preimage"), "{explained}");
|
||||
}
|
||||
148
crates/luxe-tools/src/glob.rs
Normal file
148
crates/luxe-tools/src/glob.rs
Normal file
@@ -0,0 +1,148 @@
|
||||
//! `glob` tool — find files by name or path shape.
|
||||
//!
|
||||
//! Better than shelling out, not merely different: it respects the project's ignore files, skips
|
||||
//! VCS and build output, filters every path through read policy, caps the result
|
||||
//! deterministically, and speaks one glob dialect on every platform. It walks the tree itself
|
||||
//! ([`crate::walk`]), which is what lets it ask read policy about each path before returning it.
|
||||
|
||||
use async_trait::async_trait;
|
||||
use luxe_core::{ContentBlock, Tool, ToolContext, ToolResultData, ToolSchema};
|
||||
use serde_json::json;
|
||||
|
||||
mod guarded;
|
||||
|
||||
/// JSON-schema for the glob tool arguments.
|
||||
fn glob_schema() -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: "glob".to_string(),
|
||||
description: "Find files by name or path shape (`*.rs`, `src/**/*.ts`, `**/test_*.py`). \
|
||||
Skips ignored paths — `.gitignore`, `.git/`, build output — and returns at \
|
||||
most 200 paths, so it cannot bury the answer the way `find`/`ls -R` can. Set \
|
||||
`all: true` to include ignored files (build output, `.env`, vendored deps). \
|
||||
Searching file *contents* is `grep`; finding a symbol's definition is \
|
||||
`symbol_search`."
|
||||
.to_string(),
|
||||
parameters: json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"pattern": {
|
||||
"type": "string",
|
||||
"description": "Glob pattern to match (e.g., '*.rs', 'src/**/*.ts')"
|
||||
},
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Directory to search in (defaults to cwd)"
|
||||
},
|
||||
"all": {
|
||||
"type": "boolean",
|
||||
"description": "Include ignored files (build output, vendored deps). Default false."
|
||||
}
|
||||
},
|
||||
"required": ["pattern"]
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Max file paths returned to the model before the result is capped.
|
||||
const GLOB_MAX_FILES: usize = 200;
|
||||
|
||||
/// The `glob` tool implementation.
|
||||
pub struct GlobTool;
|
||||
|
||||
impl GlobTool {
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for GlobTool {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for GlobTool {
|
||||
fn name(&self) -> &str {
|
||||
"glob"
|
||||
}
|
||||
|
||||
fn schema(&self) -> ToolSchema {
|
||||
glob_schema()
|
||||
}
|
||||
|
||||
async fn run_with_read_hook(
|
||||
&self,
|
||||
args: serde_json::Value,
|
||||
cx: &ToolContext,
|
||||
read_hook: &dyn luxe_core::tool::FileReadHook,
|
||||
) -> ToolResultData {
|
||||
guarded::run(args, cx, read_hook).await
|
||||
}
|
||||
|
||||
async fn run(&self, args: serde_json::Value, cx: &ToolContext) -> ToolResultData {
|
||||
guarded::run(args, cx, &crate::NoReadPolicy).await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// What a walk from `path` matches, as the tool would list it.
|
||||
#[cfg(test)]
|
||||
fn matches(cwd: &std::path::Path, path: &str, pattern: &str) -> Vec<String> {
|
||||
let matcher = crate::walk::matcher(pattern).unwrap();
|
||||
crate::walk::files(cwd, std::path::Path::new(path), false)
|
||||
.into_iter()
|
||||
.filter(|found| matcher.is_match(found))
|
||||
.map(|found| luxe_core::paths::display(&found))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod clones {
|
||||
use super::*;
|
||||
|
||||
/// A project with a fetched repository in it: `.luxe/` ignores everything, the clone is a git
|
||||
/// repository of its own and ignores its own `node_modules/`.
|
||||
fn project_with_a_clone() -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let clone = root.join(".luxe/gh-cache/o/r");
|
||||
std::fs::create_dir_all(clone.join(".git")).unwrap();
|
||||
std::fs::create_dir_all(clone.join("docs")).unwrap();
|
||||
std::fs::create_dir_all(clone.join("node_modules/x")).unwrap();
|
||||
std::fs::write(root.join(".luxe/.gitignore"), "*\n").unwrap();
|
||||
std::fs::write(clone.join(".gitignore"), "node_modules/\n").unwrap();
|
||||
std::fs::write(clone.join("docs/a.md"), "needle\n").unwrap();
|
||||
std::fs::write(clone.join("node_modules/x/b.md"), "needle\n").unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// `web_fetch` says to explore a clone with `glob`, so `.luxe/.gitignore` must not hide every
|
||||
/// file in it. The clone's own ignore file still counts.
|
||||
#[test]
|
||||
fn a_fetched_repository_is_searchable_by_its_own_rules() {
|
||||
let dir = project_with_a_clone();
|
||||
let found = matches(dir.path(), ".luxe/gh-cache/o/r", "**/*.md");
|
||||
assert_eq!(found, [".luxe/gh-cache/o/r/docs/a.md"]);
|
||||
assert!(
|
||||
matches(dir.path(), ".luxe", "**/*.md").is_empty(),
|
||||
"the rest of .luxe/ stays ignored"
|
||||
);
|
||||
}
|
||||
|
||||
/// Only a clone searches by its own rules: a subdirectory of the project still answers to the
|
||||
/// project's `.gitignore`.
|
||||
#[test]
|
||||
fn a_subdirectory_of_the_project_still_honors_the_projects_ignore_file() {
|
||||
let dir = project_with_a_clone();
|
||||
let cwd = dir.path();
|
||||
std::fs::write(cwd.join(".gitignore"), "src/gen/\n").unwrap();
|
||||
std::fs::create_dir_all(cwd.join("src/gen")).unwrap();
|
||||
std::fs::write(cwd.join("src/a.rs"), "").unwrap();
|
||||
std::fs::write(cwd.join("src/gen/b.rs"), "").unwrap();
|
||||
assert_eq!(matches(cwd, "src", "**/*.rs"), ["src/a.rs"]);
|
||||
}
|
||||
}
|
||||
106
crates/luxe-tools/src/glob/guarded.rs
Normal file
106
crates/luxe-tools/src/glob/guarded.rs
Normal file
@@ -0,0 +1,106 @@
|
||||
//! Guarded glob — classify actual metadata paths before returning a bounded listing.
|
||||
|
||||
use super::*;
|
||||
use crate::walk::{StopOnDrop, Walked};
|
||||
use luxe_core::permission::PermissionAction;
|
||||
use luxe_core::tool::FileReadHook;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
async fn candidates(
|
||||
cx: &ToolContext,
|
||||
path: PathBuf,
|
||||
all: bool,
|
||||
stopped: Arc<AtomicBool>,
|
||||
) -> Result<Walked, String> {
|
||||
let cwd = cx.cwd.clone();
|
||||
let cancelled = cx.cancelled.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
crate::walk::files_until(&cwd, &path, all, None, move || {
|
||||
stopped.load(Ordering::Relaxed) || *cancelled.borrow()
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("glob candidate walk failed: {error}"))
|
||||
}
|
||||
|
||||
struct Listing {
|
||||
allowed: Vec<String>,
|
||||
denied: usize,
|
||||
asks: usize,
|
||||
}
|
||||
|
||||
fn classify(
|
||||
files: Vec<PathBuf>,
|
||||
pattern: &str,
|
||||
hook: &dyn FileReadHook,
|
||||
) -> Result<Listing, String> {
|
||||
let matcher = crate::walk::matcher(pattern)
|
||||
.map_err(|error| format!("'{pattern}' is not a valid glob: {error}"))?;
|
||||
let mut listing = Listing { allowed: Vec::new(), denied: 0, asks: 0 };
|
||||
for file in files {
|
||||
if !matcher.is_match(&file) {
|
||||
continue;
|
||||
}
|
||||
match hook.decision(&file) {
|
||||
PermissionAction::Allow => listing.allowed.push(luxe_core::paths::display(&file)),
|
||||
PermissionAction::Deny => listing.denied += 1,
|
||||
PermissionAction::Ask => listing.asks += 1,
|
||||
}
|
||||
}
|
||||
Ok(listing)
|
||||
}
|
||||
|
||||
fn render(listing: Listing, all: bool, capped: bool) -> ToolResultData {
|
||||
let body = if listing.allowed.is_empty() {
|
||||
if all {
|
||||
"No files found".into()
|
||||
} else {
|
||||
"No files found (ignored paths were skipped; pass all:true to include build output and vendored files)".into()
|
||||
}
|
||||
} else {
|
||||
crate::output_limit::cap_lines(
|
||||
&listing.allowed.join("\n"),
|
||||
GLOB_MAX_FILES,
|
||||
"files",
|
||||
"Narrow the pattern or search a subdirectory to see the rest.",
|
||||
)
|
||||
};
|
||||
let mut content = vec![ContentBlock::Text(body)];
|
||||
if listing.denied + listing.asks > 0 {
|
||||
content.push(ContentBlock::Text(format!("skipped {} metadata paths denied by read policy; {} require approval and were not returned", listing.denied, listing.asks)));
|
||||
}
|
||||
if capped {
|
||||
content.push(ContentBlock::Text(crate::walk::capped_notice()));
|
||||
}
|
||||
ToolResultData { content, is_error: false }
|
||||
}
|
||||
|
||||
pub(super) async fn run(
|
||||
args: serde_json::Value,
|
||||
cx: &ToolContext,
|
||||
hook: &dyn FileReadHook,
|
||||
) -> ToolResultData {
|
||||
let Some(pattern) = args.get("pattern").and_then(|value| value.as_str()) else {
|
||||
return ToolResultData::error("Error: 'pattern' argument is required");
|
||||
};
|
||||
let path = args
|
||||
.get("path")
|
||||
.and_then(|value| value.as_str())
|
||||
.map(str::trim)
|
||||
.filter(|path| !path.is_empty())
|
||||
.unwrap_or(".");
|
||||
let all = args.get("all").and_then(|value| value.as_bool()).unwrap_or(false);
|
||||
let stopped = Arc::new(AtomicBool::new(false));
|
||||
let _stop_on_drop = StopOnDrop(stopped.clone());
|
||||
let found = candidates(cx, PathBuf::from(path), all, stopped)
|
||||
.await
|
||||
.and_then(|walked| Ok((classify(walked.files, pattern, hook)?, walked.capped)));
|
||||
match found {
|
||||
Ok((listing, capped)) => render(listing, all, capped),
|
||||
Err(problem) => ToolResultData::error(format!("Glob failed: {problem}")),
|
||||
}
|
||||
}
|
||||
134
crates/luxe-tools/src/glob/tests.rs
Normal file
134
crates/luxe-tools/src/glob/tests.rs
Normal file
@@ -0,0 +1,134 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
mod read_policy;
|
||||
|
||||
fn test_context(tmp_dir: &Path) -> ToolContext {
|
||||
let (event_tx, _event_rx) = mpsc::channel(64);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
ToolContext {
|
||||
cwd: tmp_dir.to_path_buf(),
|
||||
session_id: "test-session".to_string(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A repo with one real source file and a build directory full of look-alikes.
|
||||
fn repo_with_build_output() -> TempDir {
|
||||
let dir = TempDir::new().unwrap();
|
||||
std::fs::write(dir.path().join(".gitignore"), "target/\n").unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("src")).unwrap();
|
||||
std::fs::write(dir.path().join("src").join("main.rs"), "fn main() {}").unwrap();
|
||||
let build = dir.path().join("target").join("debug").join("build");
|
||||
std::fs::create_dir_all(&build).unwrap();
|
||||
for index in 0..30 {
|
||||
std::fs::write(build.join(format!("generated_{index}.rs")), "// generated").unwrap();
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
/// The defect this tool shipped with: `--no-ignore` meant a `*.rs` search in a Rust repo
|
||||
/// returned build output, and the 200-file cap filled with it before any source appeared.
|
||||
#[tokio::test]
|
||||
async fn build_output_is_skipped_by_default() {
|
||||
let dir = repo_with_build_output();
|
||||
let tool = GlobTool::new();
|
||||
let result = tool.run(json!({"pattern": "*.rs"}), &test_context(dir.path())).await;
|
||||
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("main.rs"), "the real source file is found: {text}");
|
||||
assert!(!text.contains("generated_"), "build output is not: {text}");
|
||||
}
|
||||
|
||||
/// A strict-schema model sends every property, so "search everywhere" arrives as `path: ""`,
|
||||
/// which `fd` refused with a usage error a real eval session tripped over.
|
||||
#[tokio::test]
|
||||
async fn an_empty_path_searches_the_project() {
|
||||
let dir = repo_with_build_output();
|
||||
let result = GlobTool::new()
|
||||
.run(json!({"pattern": "*.rs", "path": ""}), &test_context(dir.path()))
|
||||
.await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(!result.is_error && text.contains("main.rs"), "{text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ignored_files_are_reachable_on_request() {
|
||||
let dir = repo_with_build_output();
|
||||
let tool = GlobTool::new();
|
||||
let result = tool.run(json!({"pattern": "*.rs", "all": true}), &test_context(dir.path())).await;
|
||||
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("generated_"), "all:true reaches build output: {text}");
|
||||
}
|
||||
|
||||
/// The walk agrees with what the old `find` version got wrong: ignore files are honored, `**/`
|
||||
/// matches zero directories (so `src/**/*.rs` finds `src/main.rs`, the common case, which
|
||||
/// `find -path` silently skipped), and paths come back project-relative.
|
||||
#[test]
|
||||
fn the_walk_honors_ignores_depth_and_relative_paths() {
|
||||
let dir = repo_with_build_output();
|
||||
let cwd = dir.path();
|
||||
assert_eq!(matches(cwd, ".", "*.rs"), ["src/main.rs"], "build output stays out, path relative");
|
||||
assert_eq!(matches(cwd, ".", "src/**/*.rs"), ["src/main.rs"], "`**/` matches zero directories");
|
||||
assert!(matches(cwd, ".", "*.nope").is_empty());
|
||||
}
|
||||
|
||||
/// An empty result reads as "no such files". A pattern that will not compile is a different
|
||||
/// thing entirely and has to say so, or the model retries the same broken glob.
|
||||
#[tokio::test]
|
||||
async fn a_broken_glob_is_reported_rather_than_finding_nothing() {
|
||||
let dir = repo_with_build_output();
|
||||
let result = GlobTool::new().run(json!({"pattern": "src/["}), &test_context(dir.path())).await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(result.is_error && text.contains("not a valid glob"), "{text}");
|
||||
}
|
||||
|
||||
/// Absolute paths on every row are a tax the model pays twice: once to read them, once to
|
||||
/// strip them before passing one to `read`.
|
||||
#[tokio::test]
|
||||
async fn results_are_project_relative() {
|
||||
let dir = repo_with_build_output();
|
||||
let tool = GlobTool::new();
|
||||
let result = tool.run(json!({"pattern": "*.rs"}), &test_context(dir.path())).await;
|
||||
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("src/main.rs"), "{text}");
|
||||
assert!(!text.contains(dir.path().to_string_lossy().as_ref()), "no absolute prefix: {text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_directory_spanning_pattern_matches() {
|
||||
let dir = repo_with_build_output();
|
||||
let tool = GlobTool::new();
|
||||
let result = tool.run(json!({"pattern": "src/**/*.rs"}), &test_context(dir.path())).await;
|
||||
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("main.rs"), "path-spanning globs work: {text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_match_says_that_ignored_paths_were_skipped() {
|
||||
let dir = repo_with_build_output();
|
||||
let tool = GlobTool::new();
|
||||
let result = tool.run(json!({"pattern": "*.nope"}), &test_context(dir.path())).await;
|
||||
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("all:true"), "the empty result names the escape hatch: {text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_glob_missing_pattern() {
|
||||
let tool = GlobTool::new();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let result = tool.run(json!({}), &test_context(tmp_dir.path())).await;
|
||||
assert!(result.is_error);
|
||||
}
|
||||
94
crates/luxe-tools/src/glob/tests/read_policy.rs
Normal file
94
crates/luxe-tools/src/glob/tests/read_policy.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
use super::*;
|
||||
use luxe_core::permission::{
|
||||
PermissionAction::{Allow, Ask, Deny},
|
||||
PermissionEngine, PermissionMode, Rule,
|
||||
};
|
||||
|
||||
fn tree() -> TempDir {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("nested")).unwrap();
|
||||
for name in [".env", "nested/.env", "nested/.env.example", "safe.rs", "review.rs"] {
|
||||
std::fs::write(dir.path().join(name), "content is not needed for metadata").unwrap();
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
fn read_rule(pattern: &str, action: luxe_core::permission::PermissionAction) -> Rule {
|
||||
Rule { permission: "read".into(), pattern: pattern.into(), action }
|
||||
}
|
||||
|
||||
async fn guarded(dir: &Path, args: serde_json::Value, policy: &PermissionEngine) -> String {
|
||||
let result = GlobTool::new().run_with_read_hook(args, &test_context(dir), policy).await;
|
||||
assert!(!result.is_error, "{:?}", result.content);
|
||||
result
|
||||
.content
|
||||
.into_iter()
|
||||
.filter_map(|block| match block {
|
||||
ContentBlock::Text(text) => Some(text),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
/// Metadata discovery must consult concrete path policy rather than expose denied names from a directory.
|
||||
#[tokio::test]
|
||||
async fn guarded_glob_withholds_secret_descendants_and_keeps_templates() {
|
||||
let dir = tree();
|
||||
let text = guarded(
|
||||
dir.path(),
|
||||
serde_json::json!({"pattern": "*", "all": true}),
|
||||
&PermissionEngine::permissive(),
|
||||
)
|
||||
.await;
|
||||
assert!(!text.lines().any(|line| line == ".env" || line == "nested/.env"), "{text}");
|
||||
assert!(text.lines().any(|line| line == "nested/.env.example"), "{text}");
|
||||
assert!(text.contains("safe.rs") && text.contains("skipped"), "{text}");
|
||||
}
|
||||
|
||||
/// A root-file exception must not approve another directory's env name, and Ask is still withheld.
|
||||
#[tokio::test]
|
||||
async fn guarded_glob_honors_actual_path_exceptions_and_ask() {
|
||||
let dir = tree();
|
||||
let policy = PermissionEngine::assemble(
|
||||
PermissionMode::Default,
|
||||
vec![read_rule(".env", Allow), read_rule("review.rs", Ask)],
|
||||
vec![],
|
||||
false,
|
||||
);
|
||||
let text = guarded(dir.path(), serde_json::json!({"pattern": "*", "all": true}), &policy).await;
|
||||
assert!(text.lines().any(|line| line == ".env"), "{text}");
|
||||
assert!(!text.lines().any(|line| line == "nested/.env" || line == "review.rs"), "{text}");
|
||||
assert!(text.contains("approval"), "{text}");
|
||||
}
|
||||
|
||||
/// Yolo opts out of default filters while preserving an explicit user path denial.
|
||||
#[tokio::test]
|
||||
async fn guarded_glob_keeps_user_denials_under_yolo() {
|
||||
let dir = tree();
|
||||
let policy = PermissionEngine::assemble(
|
||||
PermissionMode::Yolo,
|
||||
vec![read_rule("safe.rs", Deny)],
|
||||
vec![],
|
||||
false,
|
||||
);
|
||||
let text = guarded(dir.path(), serde_json::json!({"pattern": "*", "all": true}), &policy).await;
|
||||
assert!(text.lines().any(|line| line == "nested/.env"), "{text}");
|
||||
assert!(!text.lines().any(|line| line == "safe.rs"), "{text}");
|
||||
}
|
||||
|
||||
/// Ignores and glob matching must happen without changing the policy-free tool's ordinary behavior.
|
||||
#[tokio::test]
|
||||
async fn guarded_glob_preserves_ignored_file_and_pattern_behavior() {
|
||||
let dir = tree();
|
||||
std::fs::create_dir_all(dir.path().join("target")).unwrap();
|
||||
std::fs::write(dir.path().join(".gitignore"), "target/\n").unwrap();
|
||||
std::fs::write(dir.path().join("target/build.rs"), "").unwrap();
|
||||
let policy = PermissionEngine::permissive();
|
||||
let normal = guarded(dir.path(), serde_json::json!({"pattern": "*.rs"}), &policy).await;
|
||||
assert!(!normal.contains("target/build.rs"), "{normal}");
|
||||
let all =
|
||||
guarded(dir.path(), serde_json::json!({"pattern": "*.rs", "all": true}), &policy).await;
|
||||
assert!(all.contains("target/build.rs"), "{all}");
|
||||
assert!(!all.contains(".env"), "{all}");
|
||||
}
|
||||
386
crates/luxe-tools/src/grep.rs
Normal file
386
crates/luxe-tools/src/grep.rs
Normal file
@@ -0,0 +1,386 @@
|
||||
//! `grep` tool — search file contents by regex.
|
||||
//!
|
||||
//! Searches in-process: candidates come from [`crate::walk`], every one passes read policy before
|
||||
//! it is opened, and the approved files are scanned in parallel with `regex`. An external `rg`
|
||||
//! could not do the middle step, which is the one that keeps denied content out of the answer.
|
||||
//!
|
||||
//! The result is bounded `file:line:text`, with optional context lines and a glob filter — or,
|
||||
//! where the question is coarser than the lines, the files that match or a count per file.
|
||||
|
||||
use async_trait::async_trait;
|
||||
use luxe_core::{ContentBlock, Tool, ToolContext, ToolResultData, ToolSchema};
|
||||
use serde_json::json;
|
||||
use std::path::{Path, PathBuf};
|
||||
use tracing::warn;
|
||||
|
||||
mod guarded;
|
||||
#[cfg(test)]
|
||||
mod read_policy_tests;
|
||||
|
||||
/// JSON-schema for the grep tool arguments.
|
||||
fn grep_schema() -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: "grep".to_string(),
|
||||
description: "Search file *contents* by regex. Returns `file:line:text`, bounded \
|
||||
— a broad pattern says it was capped instead of flooding your context. Case \
|
||||
is sensitive unless the pattern says otherwise: prefix `(?i)`. Skips ignored \
|
||||
paths (`.gitignore`, `.git/`, build output); set `all: true` to include \
|
||||
them. Answer the coarse question coarsely: `outputMode: \"files\"` for \
|
||||
which files match and `\"count\"` for how many lines each, both a fraction \
|
||||
of the tokens of the lines themselves. Finding files by *name* is `glob`; \
|
||||
finding a symbol's definition is `symbol_search`; finding everything that \
|
||||
*uses* one \u{2014} callers, dependents, covering tests \u{2014} is `impact`, \
|
||||
which reads a code graph rather than guessing at a pattern."
|
||||
.to_string(),
|
||||
parameters: json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"pattern": {
|
||||
"type": "string",
|
||||
"description": "Regex pattern to search for. Prefix '(?i)' for a case-insensitive search."
|
||||
},
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "File or directory to search (defaults to cwd)"
|
||||
},
|
||||
"glob": {
|
||||
"type": "string",
|
||||
"description": "Glob pattern to filter files (e.g., '*.rs')"
|
||||
},
|
||||
"outputMode": {
|
||||
"type": "string",
|
||||
"enum": ["content", "files", "count"],
|
||||
"description": "What to return: 'content' (file:line:text, the default), \
|
||||
'files' (one path per matching file), or 'count' (file:count \
|
||||
of matching lines). Prefer 'files' when you only need to know \
|
||||
where to look."
|
||||
},
|
||||
"limit": {
|
||||
"type": "integer",
|
||||
"description": "Cap the rows returned (default and maximum 200). Lower it when \
|
||||
a sample will do — the equivalent of piping to 'head'."
|
||||
},
|
||||
"context": {
|
||||
"type": "integer",
|
||||
"description": "Context lines on both sides of each match (optional)"
|
||||
},
|
||||
"before": {
|
||||
"type": "integer",
|
||||
"description": "Context lines before each match; overrides 'context' on that side."
|
||||
},
|
||||
"after": {
|
||||
"type": "integer",
|
||||
"description": "Context lines after each match; overrides 'context' on that side."
|
||||
},
|
||||
"invert": {
|
||||
"type": "boolean",
|
||||
"description": "Return the lines that do NOT match the pattern. Default false."
|
||||
},
|
||||
"all": {
|
||||
"type": "boolean",
|
||||
"description": "Include ignored files (build output, vendored deps). Default false."
|
||||
}
|
||||
},
|
||||
"required": ["pattern"]
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Max rows returned to the model before the result is capped, and the ceiling on `limit`.
|
||||
const GREP_MAX_LINES: usize = 200;
|
||||
|
||||
/// Character budget for one search, the second half of the bound the schema promises.
|
||||
///
|
||||
/// Sized against Luxe's own tree, where a broad pattern's 200 rows measure ~21 KB and the worst
|
||||
/// measured — one reaching generated assets — came to 72 KB. So this leaves an ordinary search
|
||||
/// untouched and cuts the pathological one to a third.
|
||||
const GREP_MAX_CHARS: usize = 24_000;
|
||||
|
||||
/// Bytes of a file read before deciding it is binary and skipping it.
|
||||
///
|
||||
/// A NUL in the first few kilobytes is what every grep-alike uses, and it is right often enough:
|
||||
/// the alternative is dumping a shared object's bytes into the context window.
|
||||
const BINARY_SNIFF_BYTES: usize = 8192;
|
||||
|
||||
/// What a search answers with.
|
||||
///
|
||||
/// The lines are the expensive answer and often not the question: "which files mention this" and
|
||||
/// "how many are there" each cost a fraction of the tokens, and a model that has to read 200 rows
|
||||
/// to learn six filenames pays for the other 194.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
enum OutputMode {
|
||||
/// `file:line:text`
|
||||
#[default]
|
||||
Content,
|
||||
/// One path per file with at least one match
|
||||
Files,
|
||||
/// `file:count` of matching lines
|
||||
Count,
|
||||
}
|
||||
|
||||
impl OutputMode {
|
||||
/// Parse the schema's spelling, falling back to the default for anything unrecognized.
|
||||
fn parse(value: Option<&str>) -> Self {
|
||||
match value {
|
||||
Some("files") => Self::Files,
|
||||
Some("count") => Self::Count,
|
||||
_ => Self::Content,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the cap counts, for the note it appends.
|
||||
fn unit(self) -> &'static str {
|
||||
match self {
|
||||
Self::Content => "matching lines",
|
||||
Self::Files | Self::Count => "files",
|
||||
}
|
||||
}
|
||||
|
||||
/// How to see the rest, which for the expensive mode includes the cheaper ones.
|
||||
fn hint(self) -> &'static str {
|
||||
match self {
|
||||
Self::Content => {
|
||||
"Narrow the pattern, path, or glob, or use outputMode 'files' to see which files \
|
||||
match."
|
||||
}
|
||||
Self::Files | Self::Count => "Narrow the pattern, path, or glob to see the rest.",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One parsed search.
|
||||
///
|
||||
/// `limit` is deliberately *not* consulted while searching. Stopping early would make the total the
|
||||
/// result reports a count of what was collected rather than what exists — "5 more matching lines
|
||||
/// not shown (6 total)" for a pattern with three hundred hits.
|
||||
#[derive(Debug, Clone)]
|
||||
struct Search<'a> {
|
||||
pattern: &'a str,
|
||||
path: &'a Path,
|
||||
glob: Option<&'a str>,
|
||||
before: usize,
|
||||
after: usize,
|
||||
all: bool,
|
||||
invert: bool,
|
||||
mode: OutputMode,
|
||||
limit: usize,
|
||||
}
|
||||
|
||||
/// What `search` finds under `cwd`, unguarded, as the tests ask it.
|
||||
#[cfg(test)]
|
||||
fn native_search(cwd: &Path, search: &Search<'_>) -> Result<Vec<String>, String> {
|
||||
native_search_files(cwd, search, crate::walk::files(cwd, search.path, search.all), || false)
|
||||
}
|
||||
|
||||
/// Scans `paths` (relative to `cwd`) for `search`, in parallel, rows in path order.
|
||||
///
|
||||
/// Each worker takes a contiguous run of the sorted paths and the runs are joined in order, so the
|
||||
/// answer reads the same however many threads produced it. `stopped` is checked between files.
|
||||
fn native_search_files(
|
||||
cwd: &Path,
|
||||
search: &Search<'_>,
|
||||
paths: Vec<PathBuf>,
|
||||
stopped: impl Fn() -> bool + Sync,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let regex = regex::Regex::new(search.pattern)
|
||||
.map_err(|error| format!("'{}' is not a valid regex: {error}", search.pattern))?;
|
||||
let prefilter = prefilter(search);
|
||||
let filter = search
|
||||
.glob
|
||||
.map(|glob| {
|
||||
crate::walk::matcher(glob)
|
||||
.map_err(|error| format!("'{glob}' is not a valid glob: {error}"))
|
||||
})
|
||||
.transpose()?;
|
||||
let paths: Vec<PathBuf> = paths
|
||||
.into_iter()
|
||||
.filter(|path| filter.as_ref().is_none_or(|filter| filter.is_match(path)))
|
||||
.collect();
|
||||
let workers = std::thread::available_parallelism().map_or(1, usize::from).min(16);
|
||||
let run = paths.len().div_ceil(workers).max(1);
|
||||
// a worker is `Err` when it panicked, `Ok(None)` when it was stopped
|
||||
let scanned: Vec<std::thread::Result<Option<Vec<String>>>> = std::thread::scope(|scope| {
|
||||
let handles: Vec<_> = paths
|
||||
.chunks(run)
|
||||
.map(|chunk| {
|
||||
let (regex, prefilter, stopped) = (®ex, prefilter.as_ref(), &stopped);
|
||||
scope.spawn(move || {
|
||||
let mut rows = Vec::new();
|
||||
for relative in chunk {
|
||||
if stopped() {
|
||||
return None;
|
||||
}
|
||||
rows.extend(search_file(cwd, relative, (regex, prefilter), search));
|
||||
}
|
||||
Some(rows)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
handles.into_iter().map(|handle| handle.join()).collect()
|
||||
});
|
||||
combine(scanned, stopped())
|
||||
}
|
||||
|
||||
/// The workers' rows joined in order; a crashed worker is a failure, a stopped one a cancel.
|
||||
fn combine(
|
||||
scanned: Vec<std::thread::Result<Option<Vec<String>>>>,
|
||||
stopped: bool,
|
||||
) -> Result<Vec<String>, String> {
|
||||
if scanned.iter().any(Result::is_err) {
|
||||
return Err("a search worker failed; nothing it scanned is reported".into());
|
||||
}
|
||||
if stopped || scanned.iter().any(|worker| matches!(worker, Ok(None))) {
|
||||
return Err("grep cancelled".into());
|
||||
}
|
||||
Ok(scanned.into_iter().flatten().flatten().flatten().collect())
|
||||
}
|
||||
|
||||
/// A whole-text test that can only rule a file out, never in: the pattern with `^`/`$` at every
|
||||
/// line end, CRLF included, as matching line by line reads them.
|
||||
///
|
||||
/// `None` where it could rule out a file that matches: an inverted search; an anchor to the start
|
||||
/// or end of the text, which a line has and a whole file has only once; and an inline flag that
|
||||
/// turns a mode off, which can undo the line semantics. A file with a lone `\r` skips it too, in
|
||||
/// [`search_file`], since CRLF mode keeps `.` off a `\r` that a line still holds.
|
||||
fn prefilter(search: &Search<'_>) -> Option<regex::Regex> {
|
||||
let pattern = search.pattern;
|
||||
if search.invert
|
||||
|| pattern.contains("\\A")
|
||||
|| pattern.contains("\\z")
|
||||
|| turns_off_a_flag(pattern)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
regex::RegexBuilder::new(pattern).multi_line(true).crlf(true).build().ok()
|
||||
}
|
||||
|
||||
/// Whether `pattern` has an inline group like `(?-m)` or `(?i-s:…)`.
|
||||
fn turns_off_a_flag(pattern: &str) -> bool {
|
||||
pattern.match_indices("(?").any(|(at, _)| {
|
||||
let flags = &pattern[at + 2..];
|
||||
let end = flags.find([')', ':']).unwrap_or(flags.len());
|
||||
flags[..end].contains('-')
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `text` holds a `\r` that does not end a line, which a line keeps inside it.
|
||||
fn has_lone_carriage_return(text: &str) -> bool {
|
||||
let bytes = text.as_bytes();
|
||||
bytes.iter().enumerate().any(|(at, byte)| *byte == b'\r' && bytes.get(at + 1) != Some(&b'\n'))
|
||||
}
|
||||
|
||||
/// The rows one file contributes, in the shape ripgrep prints them: `file:line:text` for a match,
|
||||
/// `file-line-text` for context, or the file's name or count for the coarser modes.
|
||||
fn search_file(
|
||||
cwd: &Path,
|
||||
relative: &Path,
|
||||
(regex, prefilter): (®ex::Regex, Option<®ex::Regex>),
|
||||
search: &Search<'_>,
|
||||
) -> Vec<String> {
|
||||
let Ok(bytes) = std::fs::read(cwd.join(relative)) else { return Vec::new() };
|
||||
if bytes.iter().take(BINARY_SNIFF_BYTES).any(|byte| *byte == 0) {
|
||||
return Vec::new();
|
||||
}
|
||||
let Ok(text) = String::from_utf8(bytes) else { return Vec::new() };
|
||||
// most files hold no match, and one pass over the whole text is far cheaper than per line
|
||||
let filtered = prefilter.filter(|_| !has_lone_carriage_return(&text));
|
||||
if filtered.is_some_and(|prefilter| !prefilter.is_match(&text)) {
|
||||
return Vec::new();
|
||||
}
|
||||
let name = luxe_core::paths::display(relative);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
let matched: Vec<usize> = lines
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, line)| regex.is_match(line) != search.invert)
|
||||
.map(|(index, _)| index)
|
||||
.collect();
|
||||
if matched.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
match search.mode {
|
||||
OutputMode::Files => vec![name],
|
||||
OutputMode::Count => vec![format!("{name}:{}", matched.len())],
|
||||
OutputMode::Content => {
|
||||
// Decide *which* lines to print and *what each one is* separately, then print each
|
||||
// once. Doing it per match instead conflates the two: a match inside an earlier
|
||||
// match's trailing context gets emitted as context and never as the answer.
|
||||
let mut shown = vec![false; lines.len()];
|
||||
for index in &matched {
|
||||
let first = index.saturating_sub(search.before);
|
||||
let last = (index + search.after + 1).min(lines.len());
|
||||
shown[first..last].iter_mut().for_each(|slot| *slot = true);
|
||||
}
|
||||
let is_match = |index: usize| matched.binary_search(&index).is_ok();
|
||||
lines
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(index, _)| shown[*index])
|
||||
.map(|(index, line)| {
|
||||
// `-` marks a context line; the caller's parsers and the model both read the
|
||||
// `:` rows as the answer
|
||||
let separator = if is_match(index) { ':' } else { '-' };
|
||||
format!("{name}{separator}{}{separator}{line}", index + 1)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `grep` tool implementation.
|
||||
pub struct GrepTool {
|
||||
/// Shared read tracker; a file whose lines a search printed is recorded as read
|
||||
tracker: Option<std::sync::Arc<luxe_core::read_tracker::ReadTracker>>,
|
||||
}
|
||||
|
||||
impl GrepTool {
|
||||
/// Create a new grep tool instance.
|
||||
pub fn new() -> Self {
|
||||
Self { tracker: None }
|
||||
}
|
||||
|
||||
/// Attach the shared read tracker, so the lines a search showed satisfy the edit guards the
|
||||
/// way a `read` of them would.
|
||||
pub fn with_tracker(
|
||||
mut self,
|
||||
tracker: std::sync::Arc<luxe_core::read_tracker::ReadTracker>,
|
||||
) -> Self {
|
||||
self.tracker = Some(tracker);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for GrepTool {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for GrepTool {
|
||||
fn name(&self) -> &str {
|
||||
"grep"
|
||||
}
|
||||
|
||||
fn schema(&self) -> ToolSchema {
|
||||
grep_schema()
|
||||
}
|
||||
|
||||
async fn run_with_read_hook(
|
||||
&self,
|
||||
args: serde_json::Value,
|
||||
cx: &ToolContext,
|
||||
read_hook: &dyn luxe_core::tool::FileReadHook,
|
||||
) -> ToolResultData {
|
||||
guarded::run(self, args, cx, read_hook).await
|
||||
}
|
||||
|
||||
async fn run(&self, args: serde_json::Value, cx: &ToolContext) -> ToolResultData {
|
||||
guarded::run(self, args, cx, &crate::NoReadPolicy).await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod search_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
195
crates/luxe-tools/src/grep/guarded.rs
Normal file
195
crates/luxe-tools/src/grep/guarded.rs
Normal file
@@ -0,0 +1,195 @@
|
||||
//! Guarded grep — classify candidate paths before reading content in a bounded worker.
|
||||
|
||||
use super::*;
|
||||
use crate::walk::{StopOnDrop, Walked};
|
||||
use luxe_core::permission::PermissionAction;
|
||||
use luxe_core::tool::FileReadHook;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
pub(super) fn parse_search(args: &serde_json::Value) -> Result<Search<'_>, String> {
|
||||
let pattern = args
|
||||
.get("pattern")
|
||||
.and_then(|value| value.as_str())
|
||||
.ok_or("Error: 'pattern' argument is required")?;
|
||||
// a model under a strict schema sends every property, so "no path" arrives as `""`
|
||||
let path = args
|
||||
.get("path")
|
||||
.and_then(|value| value.as_str())
|
||||
.map(str::trim)
|
||||
.filter(|path| !path.is_empty())
|
||||
.unwrap_or(".");
|
||||
// a negative count is a mistake, not a smaller window
|
||||
let count = |key: &str| {
|
||||
args.get(key).and_then(|value| value.as_i64()).filter(|value| *value > 0).unwrap_or(0)
|
||||
as usize
|
||||
};
|
||||
// a zero on one side is the strict schema's default, not a choice
|
||||
let side = |key: &str| match count(key) {
|
||||
0 => count("context"),
|
||||
asked => asked,
|
||||
};
|
||||
// `limit` only tightens: a cap the caller can raise is not a bound
|
||||
let limit = args
|
||||
.get("limit")
|
||||
.and_then(|value| value.as_i64())
|
||||
.and_then(|value| usize::try_from(value).ok())
|
||||
.filter(|value| *value > 0)
|
||||
.unwrap_or(GREP_MAX_LINES)
|
||||
.min(GREP_MAX_LINES);
|
||||
Ok(Search {
|
||||
pattern,
|
||||
path: Path::new(path),
|
||||
glob: args.get("glob").and_then(|value| value.as_str()),
|
||||
before: side("before"),
|
||||
after: side("after"),
|
||||
all: args.get("all").and_then(|value| value.as_bool()).unwrap_or(false),
|
||||
invert: args.get("invert").and_then(|value| value.as_bool()).unwrap_or(false),
|
||||
// camelCase is advertised; snake_case is what models reach for, and a silently ignored
|
||||
// mode returns the expensive answer
|
||||
mode: OutputMode::parse(
|
||||
luxe_core::tool::arg(args, &["outputMode", "output_mode"])
|
||||
.and_then(|value| value.as_str()),
|
||||
),
|
||||
limit,
|
||||
})
|
||||
}
|
||||
|
||||
struct ReadPlan {
|
||||
allowed: Vec<PathBuf>,
|
||||
denied: usize,
|
||||
asks: usize,
|
||||
}
|
||||
|
||||
fn classify(
|
||||
paths: Vec<PathBuf>,
|
||||
glob: Option<&str>,
|
||||
hook: &dyn FileReadHook,
|
||||
) -> Result<ReadPlan, String> {
|
||||
let filter = glob.map(crate::walk::matcher).transpose().map_err(|error| error.to_string())?;
|
||||
let mut plan = ReadPlan { allowed: Vec::new(), denied: 0, asks: 0 };
|
||||
for path in paths {
|
||||
if filter.as_ref().is_some_and(|filter| !filter.is_match(&path)) {
|
||||
continue;
|
||||
}
|
||||
match hook.decision(&path) {
|
||||
PermissionAction::Allow => plan.allowed.push(path),
|
||||
PermissionAction::Deny => plan.denied += 1,
|
||||
PermissionAction::Ask => plan.asks += 1,
|
||||
}
|
||||
}
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
async fn candidates(
|
||||
cx: &ToolContext,
|
||||
path: &Path,
|
||||
all: bool,
|
||||
stopped: Arc<AtomicBool>,
|
||||
) -> Result<Walked, String> {
|
||||
let cwd = cx.cwd.clone();
|
||||
let path = path.to_path_buf();
|
||||
let cancelled = cx.cancelled.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
crate::walk::files_until(&cwd, &path, all, None, move || {
|
||||
stopped.load(Ordering::Relaxed) || *cancelled.borrow()
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("grep candidate walk failed: {error}"))
|
||||
}
|
||||
|
||||
async fn scan(
|
||||
args: serde_json::Value,
|
||||
cx: &ToolContext,
|
||||
paths: Vec<PathBuf>,
|
||||
stopped: Arc<AtomicBool>,
|
||||
) -> Result<String, String> {
|
||||
let cwd = cx.cwd.clone();
|
||||
let cancelled = cx.cancelled.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let search = parse_search(&args)?;
|
||||
super::native_search_files(&cwd, &search, paths, || {
|
||||
stopped.load(Ordering::Relaxed) || *cancelled.borrow()
|
||||
})
|
||||
.map(|rows| rows.join("\n"))
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("grep scan worker failed: {error}"))?
|
||||
}
|
||||
|
||||
pub(super) async fn run(
|
||||
tool: &GrepTool,
|
||||
args: serde_json::Value,
|
||||
cx: &ToolContext,
|
||||
hook: &dyn FileReadHook,
|
||||
) -> ToolResultData {
|
||||
let search = match parse_search(&args) {
|
||||
Ok(search) => search,
|
||||
Err(error) => return ToolResultData::error(error),
|
||||
};
|
||||
let stopped = Arc::new(AtomicBool::new(false));
|
||||
let _stop_on_drop = StopOnDrop(stopped.clone());
|
||||
let walked = match candidates(cx, search.path, search.all, stopped.clone()).await {
|
||||
Ok(walked) => walked,
|
||||
Err(error) => return ToolResultData::error(error),
|
||||
};
|
||||
let plan = match classify(walked.files, search.glob, hook) {
|
||||
Ok(plan) => plan,
|
||||
Err(error) => return ToolResultData::error(error),
|
||||
};
|
||||
let found = scan(args.clone(), cx, plan.allowed, stopped).await;
|
||||
let mut result = finish(tool, cx, &search, found);
|
||||
if plan.denied + plan.asks > 0 {
|
||||
result.content.push(ContentBlock::Text(format!(
|
||||
"skipped {} files denied by read policy; {} files require approval and were not read",
|
||||
plan.denied, plan.asks
|
||||
)));
|
||||
}
|
||||
if walked.capped {
|
||||
result.content.push(ContentBlock::Text(crate::walk::capped_notice()));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub(super) fn finish(
|
||||
tool: &GrepTool,
|
||||
cx: &ToolContext,
|
||||
search: &Search<'_>,
|
||||
found: Result<String, String>,
|
||||
) -> ToolResultData {
|
||||
match found {
|
||||
Ok(matches) if matches.trim().is_empty() => ToolResultData::text("No matches found"),
|
||||
Ok(matches) => {
|
||||
let bounded = crate::output_limit::cap_lines_within(
|
||||
&matches,
|
||||
search.limit,
|
||||
GREP_MAX_CHARS,
|
||||
search.mode.unit(),
|
||||
search.mode.hint(),
|
||||
);
|
||||
record_matches(tool, cx, search, &bounded);
|
||||
ToolResultData::text(bounded)
|
||||
}
|
||||
Err(problem) => {
|
||||
warn!(pattern = search.pattern, error = %problem, "grep failed");
|
||||
ToolResultData::error(format!("Grep failed: {problem}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn record_matches(tool: &GrepTool, cx: &ToolContext, search: &Search<'_>, bounded: &str) {
|
||||
let (Some(tracker), OutputMode::Content) = (&tool.tracker, search.mode) else { return };
|
||||
let searched = cx.cwd.join(search.path);
|
||||
let shown = if searched.is_file() {
|
||||
vec![searched]
|
||||
} else {
|
||||
crate::bash::seen::files_in_rows(bounded, &cx.cwd)
|
||||
};
|
||||
for path in shown {
|
||||
tracker.record(&cx.session_id, &path);
|
||||
}
|
||||
}
|
||||
147
crates/luxe-tools/src/grep/read_policy_tests.rs
Normal file
147
crates/luxe-tools/src/grep/read_policy_tests.rs
Normal file
@@ -0,0 +1,147 @@
|
||||
use super::*;
|
||||
use luxe_core::permission::{
|
||||
PermissionAction,
|
||||
PermissionAction::{Allow, Ask, Deny},
|
||||
PermissionEngine, PermissionMode, Rule,
|
||||
};
|
||||
|
||||
fn rule(permission: &str, pattern: &str, action: PermissionAction) -> Rule {
|
||||
Rule { permission: permission.into(), pattern: pattern.into(), action }
|
||||
}
|
||||
|
||||
fn context(cwd: &Path) -> ToolContext {
|
||||
let (_, cancelled) = tokio::sync::watch::channel(false);
|
||||
let (event_tx, _) = tokio::sync::mpsc::channel(8);
|
||||
ToolContext {
|
||||
cwd: cwd.into(),
|
||||
session_id: "grep-read-policy".into(),
|
||||
cancelled: std::sync::Arc::new(cancelled),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn tree() -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("nested")).unwrap();
|
||||
for (path, text) in [
|
||||
(".env", "needle ROOT_PRIVATE\n"),
|
||||
("nested/.env.local", "needle NESTED_PRIVATE\n"),
|
||||
("nested/.env", "needle CHILD_PRIVATE\n"),
|
||||
("nested/.env.example", "needle PUBLIC_TEMPLATE\n"),
|
||||
("safe.txt", "needle SAFE_TEXT\n"),
|
||||
("review.txt", "needle REVIEW_TEXT\n"),
|
||||
] {
|
||||
std::fs::write(dir.path().join(path), text).unwrap();
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
async fn guarded(dir: &Path, args: serde_json::Value, policy: &PermissionEngine) -> (String, bool) {
|
||||
let result = GrepTool::new().run_with_read_hook(args, &context(dir), policy).await;
|
||||
let text = result
|
||||
.content
|
||||
.iter()
|
||||
.filter_map(|block| match block {
|
||||
ContentBlock::Text(text) => Some(text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
(text, result.is_error)
|
||||
}
|
||||
|
||||
/// A broad ignored-file scan must consult actual paths before opening any env content.
|
||||
#[tokio::test]
|
||||
async fn guarded_grep_skips_secret_descendants_and_keeps_templates() {
|
||||
let dir = tree();
|
||||
let (text, error) = guarded(
|
||||
dir.path(),
|
||||
json!({"pattern": "needle", "all": true}),
|
||||
&PermissionEngine::permissive(),
|
||||
)
|
||||
.await;
|
||||
assert!(!error, "{text}");
|
||||
assert!(text.contains("SAFE_TEXT") && text.contains("PUBLIC_TEMPLATE"), "{text}");
|
||||
assert!(!text.contains("PRIVATE"), "{text}");
|
||||
assert!(text.contains("skipped"), "{text}");
|
||||
}
|
||||
|
||||
/// An exception for the root env file must not approve a secret env file in a child directory.
|
||||
#[tokio::test]
|
||||
async fn guarded_grep_evaluates_scope_specific_exceptions_per_file() {
|
||||
let dir = tree();
|
||||
let policy = PermissionEngine::assemble(
|
||||
PermissionMode::Default,
|
||||
vec![rule("read", ".env", Allow)],
|
||||
vec![],
|
||||
false,
|
||||
);
|
||||
let (text, error) =
|
||||
guarded(dir.path(), json!({"pattern": "needle", "glob": "**/.env*", "all": true}), &policy)
|
||||
.await;
|
||||
assert!(!error, "{text}");
|
||||
assert!(text.contains("ROOT_PRIVATE"), "{text}");
|
||||
assert!(!text.contains("NESTED_PRIVATE") && !text.contains("CHILD_PRIVATE"), "{text}");
|
||||
assert!(text.contains("PUBLIC_TEMPLATE"), "{text}");
|
||||
}
|
||||
|
||||
/// Ask is not a read allowance; skipped approval-required files must be reported, not searched.
|
||||
#[tokio::test]
|
||||
async fn guarded_grep_does_not_read_ask_paths() {
|
||||
let dir = tree();
|
||||
let policy = PermissionEngine::assemble(
|
||||
PermissionMode::Default,
|
||||
vec![rule("read", "review.txt", Ask)],
|
||||
vec![],
|
||||
false,
|
||||
);
|
||||
let (text, _) = guarded(dir.path(), json!({"pattern": "needle", "all": true}), &policy).await;
|
||||
assert!(!text.contains("REVIEW_TEXT"), "{text}");
|
||||
assert!(text.contains("approval"), "{text}");
|
||||
}
|
||||
|
||||
/// Files/count output must obey the same decisions even when it does not return content lines.
|
||||
#[tokio::test]
|
||||
async fn guarded_grep_applies_policy_in_coarse_output_modes() {
|
||||
let dir = tree();
|
||||
for mode in ["files", "count"] {
|
||||
let (text, _) = guarded(
|
||||
dir.path(),
|
||||
json!({"pattern": "needle", "all": true, "outputMode": mode}),
|
||||
&PermissionEngine::permissive(),
|
||||
)
|
||||
.await;
|
||||
assert!(!text.contains(".env.local") && !text.contains("nested/.env:"), "{mode}: {text}");
|
||||
assert!(text.contains(".env.example"), "{mode}: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Guarded grep honors a project's own `.ignore` file unless all is requested.
|
||||
#[tokio::test]
|
||||
async fn guarded_grep_honors_ignore_files_until_all_is_enabled() {
|
||||
let dir = tree();
|
||||
std::fs::write(dir.path().join(".ignore"), "ignored.txt\n").unwrap();
|
||||
std::fs::write(dir.path().join("ignored.txt"), "needle IGNORED_BY_FILE\n").unwrap();
|
||||
let policy = PermissionEngine::permissive();
|
||||
let (normal, _) = guarded(dir.path(), json!({"pattern": "needle"}), &policy).await;
|
||||
assert!(!normal.contains("IGNORED_BY_FILE"), "{normal}");
|
||||
let (all, _) = guarded(dir.path(), json!({"pattern": "needle", "all": true}), &policy).await;
|
||||
assert!(all.contains("IGNORED_BY_FILE"), "{all}");
|
||||
}
|
||||
|
||||
/// Yolo removes default exclusions without ignoring an explicit user read denial.
|
||||
#[tokio::test]
|
||||
async fn guarded_grep_honors_yolo_and_user_denials() {
|
||||
let dir = tree();
|
||||
let policy = PermissionEngine::assemble(
|
||||
PermissionMode::Yolo,
|
||||
vec![rule("read", "safe.txt", Deny)],
|
||||
vec![],
|
||||
false,
|
||||
);
|
||||
let (text, _) = guarded(dir.path(), json!({"pattern": "needle", "all": true}), &policy).await;
|
||||
assert!(text.contains("ROOT_PRIVATE") && text.contains("CHILD_PRIVATE"), "{text}");
|
||||
assert!(!text.contains("SAFE_TEXT"), "{text}");
|
||||
}
|
||||
156
crates/luxe-tools/src/grep/search_tests.rs
Normal file
156
crates/luxe-tools/src/grep/search_tests.rs
Normal file
@@ -0,0 +1,156 @@
|
||||
//! The in-process search, pinned to the rows ripgrep prints for the same request, which is what
|
||||
//! the model and every row parser here expect.
|
||||
|
||||
use super::*;
|
||||
|
||||
fn search(cwd: &Path, search: &Search<'_>) -> Vec<String> {
|
||||
native_search(cwd, search).expect("the search runs")
|
||||
}
|
||||
|
||||
/// A plain content search of `.`, generous enough that the cap never masks a row.
|
||||
fn base(pattern: &str) -> Search<'_> {
|
||||
Search {
|
||||
pattern,
|
||||
path: Path::new("."),
|
||||
glob: None,
|
||||
before: 0,
|
||||
after: 0,
|
||||
all: false,
|
||||
invert: false,
|
||||
mode: OutputMode::Content,
|
||||
limit: 500,
|
||||
}
|
||||
}
|
||||
|
||||
/// A tree with an ignored directory, nesting, two matches in one file, and Git's own files.
|
||||
fn tree() -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::create_dir_all(root.join("src/deep")).unwrap();
|
||||
std::fs::write(root.join("src/a.rs"), "fn a() {}\n// needle one\nfn b() {}\n// needle two\n")
|
||||
.unwrap();
|
||||
std::fs::write(root.join("src/deep/c.rs"), "// needle three\nlet x = 1;\n").unwrap();
|
||||
std::fs::write(root.join("notes.md"), "needle four\n").unwrap();
|
||||
std::fs::write(root.join(".gitignore"), "skipme/\n").unwrap();
|
||||
std::fs::create_dir_all(root.join("skipme")).unwrap();
|
||||
std::fs::write(root.join("skipme/d.rs"), "// needle five\n").unwrap();
|
||||
std::fs::create_dir_all(root.join(".git/refs")).unwrap();
|
||||
std::fs::write(root.join(".git/config"), "needle six\n").unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_come_in_ripgreps_shape_and_path_order() {
|
||||
let dir = tree();
|
||||
let cwd = dir.path();
|
||||
let needle = base("needle");
|
||||
assert_eq!(
|
||||
search(cwd, &needle),
|
||||
[
|
||||
"notes.md:1:needle four",
|
||||
"src/a.rs:2:// needle one",
|
||||
"src/a.rs:4:// needle two",
|
||||
"src/deep/c.rs:1:// needle three"
|
||||
]
|
||||
);
|
||||
// a match inside another's context is still a match, and each line prints once
|
||||
let context = Search { before: 1, after: 1, ..needle.clone() };
|
||||
assert_eq!(
|
||||
search(cwd, &context)[1..5],
|
||||
[
|
||||
"src/a.rs-1-fn a() {}",
|
||||
"src/a.rs:2:// needle one",
|
||||
"src/a.rs-3-fn b() {}",
|
||||
"src/a.rs:4:// needle two"
|
||||
]
|
||||
);
|
||||
let files = Search { mode: OutputMode::Files, glob: Some("*.rs"), ..needle.clone() };
|
||||
assert_eq!(search(cwd, &files), ["src/a.rs", "src/deep/c.rs"]);
|
||||
let count = Search { mode: OutputMode::Count, ..needle.clone() };
|
||||
assert_eq!(search(cwd, &count), ["notes.md:1", "src/a.rs:2", "src/deep/c.rs:1"]);
|
||||
let all = Search { all: true, mode: OutputMode::Files, ..needle };
|
||||
assert_eq!(search(cwd, &all), ["notes.md", "skipme/d.rs", "src/a.rs", "src/deep/c.rs"]);
|
||||
}
|
||||
|
||||
/// Spread over more files than there are workers, the rows still come back in path order.
|
||||
#[test]
|
||||
fn a_parallel_scan_keeps_path_order() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let expected: Vec<String> = (0..200)
|
||||
.map(|index| {
|
||||
let name = format!("f{index:03}.txt");
|
||||
std::fs::write(dir.path().join(&name), "needle\n").unwrap();
|
||||
format!("{name}:1:needle")
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(search(dir.path(), &base("needle")), expected);
|
||||
}
|
||||
|
||||
/// A project with a fetched repository in it: `.luxe/` ignores everything, the clone is a git
|
||||
/// repository of its own and ignores its own `node_modules/`.
|
||||
fn project_with_a_clone() -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let clone = root.join(".luxe/gh-cache/o/r");
|
||||
std::fs::create_dir_all(clone.join(".git")).unwrap();
|
||||
std::fs::create_dir_all(clone.join("docs")).unwrap();
|
||||
std::fs::create_dir_all(clone.join("node_modules/x")).unwrap();
|
||||
std::fs::write(root.join(".luxe/.gitignore"), "*\n").unwrap();
|
||||
std::fs::write(clone.join(".gitignore"), "node_modules/\n").unwrap();
|
||||
std::fs::write(clone.join("docs/a.md"), "needle\n").unwrap();
|
||||
std::fs::write(clone.join("node_modules/x/b.md"), "needle\n").unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// `web_fetch` says to explore a clone, which is searchable by its own ignore rules, not `.luxe/`'s.
|
||||
#[test]
|
||||
fn a_fetched_repository_is_searchable_by_its_own_rules() {
|
||||
let dir = project_with_a_clone();
|
||||
let clone =
|
||||
Search { path: Path::new(".luxe/gh-cache/o/r"), mode: OutputMode::Files, ..base("needle") };
|
||||
assert_eq!(search(dir.path(), &clone), [".luxe/gh-cache/o/r/docs/a.md"]);
|
||||
}
|
||||
|
||||
/// Only a clone searches by its own rules: a subdirectory of the project still answers to the
|
||||
/// project's `.gitignore`.
|
||||
#[test]
|
||||
fn a_subdirectory_of_the_project_still_honors_the_projects_ignore_file() {
|
||||
let dir = project_with_a_clone();
|
||||
let cwd = dir.path();
|
||||
std::fs::write(cwd.join(".gitignore"), "src/gen/\n").unwrap();
|
||||
std::fs::create_dir_all(cwd.join("src/gen")).unwrap();
|
||||
std::fs::write(cwd.join("src/a.rs"), "needle\n").unwrap();
|
||||
std::fs::write(cwd.join("src/gen/b.rs"), "needle\n").unwrap();
|
||||
let sub = Search { path: Path::new("src"), mode: OutputMode::Files, ..base("needle") };
|
||||
assert_eq!(search(cwd, &sub), ["src/a.rs"]);
|
||||
}
|
||||
|
||||
/// The whole-file test that skips files never rules out a line that matches: anchors read per
|
||||
/// line, CRLF included, and `\A` keeps its per-line meaning.
|
||||
#[test]
|
||||
fn the_prefilter_never_hides_a_matching_line() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("unix.py"), "x = 1\ndef run():\n pass\n").unwrap();
|
||||
std::fs::write(dir.path().join("dos.txt"), "first end\r\nsecond end\r\n").unwrap();
|
||||
let cwd = dir.path();
|
||||
assert_eq!(search(cwd, &base("^def")), ["unix.py:2:def run():"]);
|
||||
assert_eq!(search(cwd, &base("second end$")), ["dos.txt:2:second end"]);
|
||||
assert_eq!(search(cwd, &base(r"\Adef")), ["unix.py:2:def run():"]);
|
||||
assert_eq!(search(cwd, &base(r"pass\z")), ["unix.py:3: pass"]);
|
||||
// a lone `\r` stays inside a line, where `.` matches it and CRLF mode would not
|
||||
std::fs::write(cwd.join("progress.log"), "10%\r20%\rdone\n").unwrap();
|
||||
assert_eq!(search(cwd, &base("10%.*done")), ["progress.log:1:10%\r20%\rdone"]);
|
||||
// an inline flag turning multi-line off makes `^` the line's start again, per line
|
||||
assert_eq!(search(cwd, &base("(?-m)^def")), ["unix.py:2:def run():"]);
|
||||
}
|
||||
|
||||
/// A worker that crashed is a failure the caller hears about; one that was stopped is a cancel.
|
||||
#[test]
|
||||
fn a_crashed_worker_is_a_failure_not_a_cancel() {
|
||||
let rows = |row: &str| Ok(Some(vec![row.to_string()]));
|
||||
let crashed: std::thread::Result<Option<Vec<String>>> = Err(Box::new("boom"));
|
||||
let failed = combine(vec![rows("a"), crashed], false).unwrap_err();
|
||||
assert!(failed.contains("worker failed"), "{failed}");
|
||||
assert_eq!(combine(vec![rows("a"), Ok(None)], false).unwrap_err(), "grep cancelled");
|
||||
assert_eq!(combine(vec![rows("a"), rows("b")], false).unwrap(), ["a", "b"]);
|
||||
}
|
||||
464
crates/luxe-tools/src/grep/tests.rs
Normal file
464
crates/luxe-tools/src/grep/tests.rs
Normal file
@@ -0,0 +1,464 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
fn test_context(tmp_dir: &std::path::Path) -> ToolContext {
|
||||
let (event_tx, _event_rx) = mpsc::channel(64);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
ToolContext {
|
||||
cwd: tmp_dir.to_path_buf(),
|
||||
session_id: "test-session".to_string(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A plain content search of `.`, for a test to vary one field of.
|
||||
fn search<'a>(pattern: &'a str) -> Search<'a> {
|
||||
Search {
|
||||
pattern,
|
||||
path: Path::new("."),
|
||||
glob: None,
|
||||
before: 0,
|
||||
after: 0,
|
||||
all: false,
|
||||
invert: false,
|
||||
mode: OutputMode::Content,
|
||||
limit: GREP_MAX_LINES,
|
||||
}
|
||||
}
|
||||
|
||||
/// A repo with one real match and a build directory full of look-alikes.
|
||||
fn repo_with_build_output() -> tempfile::TempDir {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
std::fs::write(dir.path().join(".gitignore"), "target/\n").unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("src")).unwrap();
|
||||
std::fs::write(dir.path().join("src").join("main.rs"), "let needle = 1;").unwrap();
|
||||
let build = dir.path().join("target").join("debug");
|
||||
std::fs::create_dir_all(&build).unwrap();
|
||||
for index in 0..30 {
|
||||
std::fs::write(build.join(format!("gen_{index}.rs")), "needle in build output").unwrap();
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
/// The search honors ignore files and answers in ripgrep's row shape, which the old `grep`
|
||||
/// fallback, a different program with different rules, did not.
|
||||
#[test]
|
||||
fn the_native_search_honors_ignores_and_reports_ripgrep_shaped_rows() {
|
||||
let dir = repo_with_build_output();
|
||||
let cwd = dir.path();
|
||||
|
||||
let rows = native_search(cwd, &search("needle")).expect("a valid regex");
|
||||
assert_eq!(rows, vec!["src/main.rs:1:let needle = 1;"], "file:line:text, project-relative");
|
||||
|
||||
let unfiltered =
|
||||
native_search(cwd, &Search { all: true, ..search("needle") }).expect("a valid regex");
|
||||
assert!(unfiltered.len() > 30, "all:true reaches build output: {}", unfiltered.len());
|
||||
|
||||
let filtered =
|
||||
native_search(cwd, &Search { glob: Some("*.py"), all: true, ..search("needle") })
|
||||
.expect("valid");
|
||||
assert!(filtered.is_empty(), "the glob filter applies: {filtered:?}");
|
||||
|
||||
assert!(native_search(cwd, &search("no_such_text")).expect("valid").is_empty());
|
||||
}
|
||||
|
||||
/// Context lines use `-` where a match uses `:`, the way ripgrep prints them, so a reader (and
|
||||
/// the model) can tell the answer from its surroundings.
|
||||
#[test]
|
||||
fn the_native_search_marks_context_lines_apart_from_matches() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
std::fs::write(dir.path().join("a.rs"), "one\ntwo\nNEEDLE\nfour\nfive\n").unwrap();
|
||||
|
||||
let rows =
|
||||
native_search(dir.path(), &Search { before: 1, after: 1, ..search("NEEDLE") }).expect("ok");
|
||||
assert_eq!(rows, vec!["a.rs-2-two", "a.rs:3:NEEDLE", "a.rs-4-four"]);
|
||||
}
|
||||
|
||||
/// The two sides are independent, because "show me what follows this signature" is the common
|
||||
/// question and a symmetric window answers it with half the lines wasted.
|
||||
#[test]
|
||||
fn context_can_be_asked_for_on_one_side_only() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
std::fs::write(dir.path().join("a.rs"), "one\ntwo\nNEEDLE\nfour\nfive\n").unwrap();
|
||||
|
||||
let after = native_search(dir.path(), &Search { after: 2, ..search("NEEDLE") }).expect("ok");
|
||||
assert_eq!(after, vec!["a.rs:3:NEEDLE", "a.rs-4-four", "a.rs-5-five"]);
|
||||
|
||||
let before = native_search(dir.path(), &Search { before: 2, ..search("NEEDLE") }).expect("ok");
|
||||
assert_eq!(before, vec!["a.rs-1-one", "a.rs-2-two", "a.rs:3:NEEDLE"]);
|
||||
}
|
||||
|
||||
/// A match that falls inside an earlier match's trailing context is still a match.
|
||||
///
|
||||
/// The break this catches: the search walked the matches and printed a window around each,
|
||||
/// skipping lines an earlier window had already spent. The second `needle` was inside the first's
|
||||
/// `after`, so it came back as a `-` context row and the answer silently lost one of its two hits.
|
||||
#[test]
|
||||
fn a_match_inside_an_earlier_match_s_context_is_still_a_match() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
std::fs::write(dir.path().join("a.rs"), "one\nneedle A\nfiller\nneedle B\nlast\n").unwrap();
|
||||
|
||||
let rows = native_search(dir.path(), &Search { after: 2, ..search("needle") }).expect("ok");
|
||||
assert_eq!(
|
||||
rows,
|
||||
vec!["a.rs:2:needle A", "a.rs-3-filler", "a.rs:4:needle B", "a.rs-5-last"],
|
||||
"both hits are `:` rows, and no line is printed twice"
|
||||
);
|
||||
}
|
||||
|
||||
/// The coarse modes are the token lever: the same question, answered in rows a model can act on
|
||||
/// without reading the lines.
|
||||
#[test]
|
||||
fn the_native_search_answers_files_and_count_modes() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
std::fs::write(dir.path().join("a.rs"), "needle\nplain\nneedle\n").unwrap();
|
||||
std::fs::write(dir.path().join("b.rs"), "needle\n").unwrap();
|
||||
std::fs::write(dir.path().join("c.rs"), "nothing here\n").unwrap();
|
||||
|
||||
let mut files =
|
||||
native_search(dir.path(), &Search { mode: OutputMode::Files, ..search("needle") })
|
||||
.expect("ok");
|
||||
files.sort();
|
||||
assert_eq!(files, vec!["a.rs", "b.rs"], "one path per matching file, and no c.rs");
|
||||
|
||||
let mut counts =
|
||||
native_search(dir.path(), &Search { mode: OutputMode::Count, ..search("needle") })
|
||||
.expect("ok");
|
||||
counts.sort();
|
||||
assert_eq!(counts, vec!["a.rs:2", "b.rs:1"], "matching lines per file");
|
||||
}
|
||||
|
||||
/// An inverted search reports the lines that did *not* match, which is a different question and
|
||||
/// not one a pattern can always express.
|
||||
#[test]
|
||||
fn the_native_search_can_invert_the_match() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
std::fs::write(dir.path().join("a.rs"), "keep\ndrop\nkeep\n").unwrap();
|
||||
|
||||
let rows = native_search(dir.path(), &Search { invert: true, ..search("keep") }).expect("ok");
|
||||
assert_eq!(rows, vec!["a.rs:2:drop"]);
|
||||
|
||||
let counts = native_search(
|
||||
dir.path(),
|
||||
&Search { invert: true, mode: OutputMode::Count, ..search("keep") },
|
||||
)
|
||||
.expect("ok");
|
||||
assert_eq!(counts, vec!["a.rs:1"], "the count follows the inversion");
|
||||
}
|
||||
|
||||
/// A binary file has no lines worth reporting, and dumping one into the context window is the
|
||||
/// worst possible answer to a broad pattern.
|
||||
#[test]
|
||||
fn the_native_search_skips_binary_files() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
std::fs::write(dir.path().join("a.bin"), b"needle\x00\x01\x02needle").unwrap();
|
||||
std::fs::write(dir.path().join("a.txt"), "needle\n").unwrap();
|
||||
|
||||
let rows = native_search(dir.path(), &search("needle")).expect("ok");
|
||||
assert_eq!(rows, vec!["a.txt:1:needle"]);
|
||||
}
|
||||
|
||||
/// An empty result reads as "nothing matches"; a pattern that will not compile is a different
|
||||
/// thing and has to say so, or the model retries the same broken regex.
|
||||
#[test]
|
||||
fn the_native_search_reports_a_broken_regex_rather_than_finding_nothing() {
|
||||
let dir = repo_with_build_output();
|
||||
let problem = native_search(dir.path(), &search("(unclosed")).expect_err("not a regex");
|
||||
assert!(problem.contains("not a valid regex"), "{problem}");
|
||||
}
|
||||
|
||||
/// A search that reports build artifacts is worse than useless: the 200-line cap fills with
|
||||
/// them and the real match never appears.
|
||||
#[tokio::test]
|
||||
async fn build_output_is_skipped_by_default() {
|
||||
let dir = repo_with_build_output();
|
||||
let tool = GrepTool::new();
|
||||
let result = tool.run(json!({"pattern": "needle"}), &test_context(dir.path())).await;
|
||||
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("main.rs"), "the real match is found: {text}");
|
||||
assert!(!text.contains("gen_"), "build output is not: {text}");
|
||||
}
|
||||
|
||||
/// `path: ""` is what a strict-schema model sends for "the whole project".
|
||||
#[tokio::test]
|
||||
async fn an_empty_path_searches_the_project() {
|
||||
let dir = repo_with_build_output();
|
||||
let result = GrepTool::new()
|
||||
.run(json!({"pattern": "needle", "path": ""}), &test_context(dir.path()))
|
||||
.await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(!result.is_error && text.contains("main.rs"), "{text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ignored_files_are_searchable_on_request() {
|
||||
let dir = repo_with_build_output();
|
||||
let tool = GrepTool::new();
|
||||
let result =
|
||||
tool.run(json!({"pattern": "needle", "all": true}), &test_context(dir.path())).await;
|
||||
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("gen_"), "all:true reaches build output: {text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn grep_tool_basic() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let tmp_dir = tmp_dir_guard.path().to_path_buf();
|
||||
std::fs::write(tmp_dir.join("test.txt"), "line1\nline2\nline3 with pattern\nline4").unwrap();
|
||||
|
||||
let tool = GrepTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({
|
||||
"pattern": "pattern",
|
||||
"path": "."
|
||||
});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(!result.is_error);
|
||||
if let ContentBlock::Text(text) = &result.content[0] {
|
||||
assert!(text.contains("pattern"));
|
||||
} else {
|
||||
panic!("expected Text block");
|
||||
}
|
||||
}
|
||||
|
||||
/// A zero is the schema's default, not a request for nothing.
|
||||
///
|
||||
/// A model under a strict schema fills every property it was shown, so `limit: 0` arrives
|
||||
/// unasked — and read literally it caps the answer at no rows at all, which looks exactly like
|
||||
/// a search that found nothing.
|
||||
#[tokio::test]
|
||||
async fn a_zero_limit_is_an_absent_limit() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let body = (1..=20).map(|n| format!("needle {n}\n")).collect::<String>();
|
||||
std::fs::write(dir.path().join("many.txt"), body).unwrap();
|
||||
|
||||
let result = GrepTool::new()
|
||||
.run(json!({"pattern": "needle", "limit": 0}), &test_context(dir.path()))
|
||||
.await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert_eq!(text.lines().count(), 20, "every match, not none: {text}");
|
||||
assert!(!text.contains("not shown"), "and nothing was cut: {text}");
|
||||
}
|
||||
|
||||
/// The hint is the whole point of the cheap modes: a capped content search has to name the one
|
||||
/// that would have answered without the lines.
|
||||
#[tokio::test]
|
||||
async fn a_capped_content_search_points_at_the_cheaper_mode() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let body = (1..=300).map(|n| format!("needle {n}\n")).collect::<String>();
|
||||
std::fs::write(dir.path().join("many.txt"), body).unwrap();
|
||||
|
||||
let result = GrepTool::new().run(json!({"pattern": "needle"}), &test_context(dir.path())).await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("outputMode 'files'"), "names the cheaper answer: {text}");
|
||||
|
||||
let files = GrepTool::new()
|
||||
.run(
|
||||
json!({"pattern": "needle", "outputMode": "files", "limit": 1}),
|
||||
&test_context(dir.path()),
|
||||
)
|
||||
.await;
|
||||
let ContentBlock::Text(text) = &files.content[0] else { panic!("expected text") };
|
||||
assert!(!text.contains("outputMode"), "the cheapest mode is not told to use itself: {text}");
|
||||
}
|
||||
|
||||
/// `limit` may tighten the bound and never loosen it.
|
||||
#[tokio::test]
|
||||
async fn a_limit_can_only_tighten_the_cap() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let body = (1..=300).map(|n| format!("needle {n}\n")).collect::<String>();
|
||||
std::fs::write(dir.path().join("many.txt"), body).unwrap();
|
||||
let cx = test_context(dir.path());
|
||||
|
||||
let sampled = GrepTool::new().run(json!({"pattern": "needle", "limit": 5}), &cx).await;
|
||||
let ContentBlock::Text(text) = &sampled.content[0] else { panic!("expected text") };
|
||||
assert_eq!(text.lines().filter(|line| line.contains("many.txt")).count(), 5, "{text}");
|
||||
assert!(text.contains("295 more matching lines not shown (300 total)"), "{text}");
|
||||
|
||||
let greedy = GrepTool::new().run(json!({"pattern": "needle", "limit": 5000}), &cx).await;
|
||||
let ContentBlock::Text(text) = &greedy.content[0] else { panic!("expected text") };
|
||||
assert_eq!(
|
||||
text.lines().filter(|line| line.contains("many.txt")).count(),
|
||||
GREP_MAX_LINES,
|
||||
"a limit past the ceiling is the ceiling: {text}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The count a capped result reports is the count that exists, not the count that was kept.
|
||||
///
|
||||
/// The break this catches: the search used to stop walking once it had one row past the caller's
|
||||
/// limit, so a `limit: 5` over three hundred hits reported "(6 total)". A wrong total tells a
|
||||
/// model its search was narrow when it was not.
|
||||
#[test]
|
||||
fn the_search_reports_every_match_it_could_have_shown() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
for file in 0..5 {
|
||||
let body = (1..=60).map(|n| format!("needle {n}\n")).collect::<String>();
|
||||
std::fs::write(dir.path().join(format!("f{file}.txt")), body).unwrap();
|
||||
}
|
||||
|
||||
let rows = native_search(dir.path(), &Search { limit: 5, ..search("needle") }).expect("ok");
|
||||
assert_eq!(rows.len(), 300, "a tight limit bounds the answer, not the search");
|
||||
|
||||
let capped = crate::output_limit::cap_lines_within(
|
||||
&rows.join("\n"),
|
||||
5,
|
||||
GREP_MAX_CHARS,
|
||||
OutputMode::Content.unit(),
|
||||
OutputMode::Content.hint(),
|
||||
);
|
||||
assert!(capped.contains("295 more matching lines not shown (300 total)"), "{capped}");
|
||||
}
|
||||
|
||||
/// Grepping for the spot and then editing it is how models work, so the lines a search showed
|
||||
/// count as a read of their file. A search that showed no lines of it does not.
|
||||
#[tokio::test]
|
||||
async fn the_lines_a_search_shows_count_as_read() {
|
||||
use luxe_core::read_tracker::{ReadStatus, ReadTracker};
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
std::fs::create_dir(dir.path().join("src")).unwrap();
|
||||
for name in ["src/a.py", "src/b.py", "src/c.py"] {
|
||||
std::fs::write(dir.path().join(name), "def needle():\n pass\n").unwrap();
|
||||
}
|
||||
std::fs::write(dir.path().join("src/b.py"), "nothing here\n").unwrap();
|
||||
let cx = test_context(dir.path());
|
||||
let status =
|
||||
|tracker: &ReadTracker, name: &str| tracker.status(&cx.session_id, &dir.path().join(name));
|
||||
|
||||
let tracker = std::sync::Arc::new(ReadTracker::new());
|
||||
let tool = GrepTool::new().with_tracker(tracker.clone());
|
||||
tool.run(json!({"pattern": "needle", "path": "src"}), &cx).await;
|
||||
assert_eq!(status(&tracker, "src/a.py"), ReadStatus::Current);
|
||||
assert_eq!(status(&tracker, "src/b.py"), ReadStatus::Unseen, "no line of it was shown");
|
||||
|
||||
let tracker = std::sync::Arc::new(ReadTracker::new());
|
||||
let tool = GrepTool::new().with_tracker(tracker.clone());
|
||||
tool.run(json!({"pattern": "needle", "path": "src/c.py"}), &cx).await;
|
||||
assert_eq!(status(&tracker, "src/c.py"), ReadStatus::Current, "one file prints no name");
|
||||
|
||||
let tracker = std::sync::Arc::new(ReadTracker::new());
|
||||
let tool = GrepTool::new().with_tracker(tracker.clone());
|
||||
tool.run(json!({"pattern": "needle", "path": "src", "output_mode": "files"}), &cx).await;
|
||||
assert_eq!(status(&tracker, "src/a.py"), ReadStatus::Unseen, "a list of names is not lines");
|
||||
}
|
||||
|
||||
/// The coarse modes are what the schema points a model at, so they have to work end to end —
|
||||
/// through whichever half this machine runs.
|
||||
#[tokio::test]
|
||||
async fn the_tool_answers_files_and_count_modes() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
std::fs::write(dir.path().join("a.txt"), "needle\nplain\nneedle\n").unwrap();
|
||||
std::fs::write(dir.path().join("b.txt"), "nothing\n").unwrap();
|
||||
let cx = test_context(dir.path());
|
||||
|
||||
let files =
|
||||
GrepTool::new().run(json!({"pattern": "needle", "output_mode": "files"}), &cx).await;
|
||||
let ContentBlock::Text(text) = &files.content[0] else { panic!("expected text") };
|
||||
assert_eq!(text.trim(), "a.txt", "just the path, and only the file that matches");
|
||||
|
||||
let counts =
|
||||
GrepTool::new().run(json!({"pattern": "needle", "outputMode": "count"}), &cx).await;
|
||||
let ContentBlock::Text(text) = &counts.content[0] else { panic!("expected text") };
|
||||
assert_eq!(text.trim(), "a.txt:2", "matching lines, not matches");
|
||||
}
|
||||
|
||||
/// The advertised spelling is camelCase, but a model that has met this argument elsewhere sends
|
||||
/// the other one — and an ignored mode answers the expensive question instead of the cheap one,
|
||||
/// silently.
|
||||
#[tokio::test]
|
||||
async fn the_retired_spelling_of_the_mode_is_still_accepted() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
std::fs::write(dir.path().join("a.txt"), "needle\n").unwrap();
|
||||
let cx = test_context(dir.path());
|
||||
|
||||
for spelling in ["outputMode", "output_mode"] {
|
||||
let result =
|
||||
GrepTool::new().run(json!({"pattern": "needle", spelling: "files"}), &cx).await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert_eq!(text.trim(), "a.txt", "{spelling} selected the files mode");
|
||||
}
|
||||
}
|
||||
|
||||
/// The defect the character budget exists for: 200 rows is not 200 rows' worth of tokens when
|
||||
/// the rows are wide, and the schema's promise of a bounded result has to hold for both.
|
||||
#[tokio::test]
|
||||
async fn a_few_very_wide_matches_are_bounded_by_characters() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let wide = (1..=60).map(|n| format!("needle {n} {}\n", "x".repeat(2_000))).collect::<String>();
|
||||
std::fs::write(dir.path().join("generated.js"), wide).unwrap();
|
||||
|
||||
let result = GrepTool::new().run(json!({"pattern": "needle"}), &test_context(dir.path())).await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
|
||||
assert!(
|
||||
text.chars().count() < GREP_MAX_CHARS + 500,
|
||||
"60 rows are under the line cap but not under the budget: {} chars",
|
||||
text.chars().count()
|
||||
);
|
||||
assert!(text.contains("not shown (60 total)"), "and it says so: {}", &text[text.len() - 200..]);
|
||||
}
|
||||
|
||||
/// A search with no `path` argument searches the project.
|
||||
///
|
||||
/// The break this catches: every other test here passes `"path": "."`, so the default — which is
|
||||
/// what a model actually sends — went unexercised.
|
||||
#[tokio::test]
|
||||
async fn a_search_with_no_path_searches_the_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("wordfreq.py"), "def rank(counts):\n pass\n").unwrap();
|
||||
|
||||
let result =
|
||||
GrepTool::new().run(json!({ "pattern": "def rank" }), &test_context(dir.path())).await;
|
||||
|
||||
assert!(!result.is_error, "{:?}", result.content);
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("wordfreq.py"), "the file the match is in: {text}");
|
||||
assert!(text.contains("def rank"), "the matching line: {text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn grep_tool_no_matches() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let tmp_dir = tmp_dir_guard.path().to_path_buf();
|
||||
std::fs::write(tmp_dir.join("test.txt"), "line1\nline2").unwrap();
|
||||
|
||||
let tool = GrepTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({
|
||||
"pattern": "nonexistent",
|
||||
"path": "."
|
||||
});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(!result.is_error);
|
||||
if let ContentBlock::Text(text) = &result.content[0] {
|
||||
assert!(text.contains("No matches found"));
|
||||
} else {
|
||||
panic!("expected Text block");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn grep_tool_missing_pattern() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let tmp_dir = tmp_dir_guard.path().to_path_buf();
|
||||
|
||||
let tool = GrepTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(result.is_error);
|
||||
}
|
||||
98
crates/luxe-tools/src/lib.rs
Normal file
98
crates/luxe-tools/src/lib.rs
Normal file
@@ -0,0 +1,98 @@
|
||||
//! luxe-tools — tool implementations.
|
||||
//!
|
||||
//! Provides the standard tool set (read, write, edit, bash, grep, glob, etc.)
|
||||
//! as `Tool` trait impls. Depends on `luxe-core` for the `Tool` trait.
|
||||
|
||||
pub mod activate;
|
||||
pub mod astgrep;
|
||||
pub mod bash;
|
||||
pub mod brave;
|
||||
pub mod diff_preview;
|
||||
pub mod edit;
|
||||
pub mod exa;
|
||||
pub mod exa_mcp;
|
||||
pub mod firecrawl;
|
||||
mod git;
|
||||
pub mod glob;
|
||||
pub mod grep;
|
||||
mod line_endings;
|
||||
pub mod loop_control;
|
||||
mod output_limit;
|
||||
mod process;
|
||||
mod question;
|
||||
pub mod read;
|
||||
pub mod screenshot;
|
||||
mod skill;
|
||||
mod ssrf;
|
||||
pub mod tavily;
|
||||
mod test_baseline;
|
||||
mod test_runner;
|
||||
pub mod todo;
|
||||
pub(crate) use luxe_core::walk;
|
||||
|
||||
/// The read policy a tool runs under outside the engine, where none was given: every file allowed.
|
||||
///
|
||||
/// `glob` and `grep` have one implementation, the guarded one, so a direct call goes through it
|
||||
/// too rather than through a second path that could drift.
|
||||
pub(crate) struct NoReadPolicy;
|
||||
|
||||
impl luxe_core::tool::FileReadHook for NoReadPolicy {
|
||||
fn decision(&self, _: &std::path::Path) -> luxe_core::permission::PermissionAction {
|
||||
luxe_core::permission::PermissionAction::Allow
|
||||
}
|
||||
}
|
||||
pub mod web;
|
||||
pub mod write;
|
||||
|
||||
/// Register all built-in tools in the given registry.
|
||||
///
|
||||
/// The `todo` tool requires a store root (e.g. `.luxe/todos`). Pass `None` to skip registering it.
|
||||
/// `web` configures `web_search` and `web_fetch`; [`web::WebConfig::from_env`] is the usual start.
|
||||
///
|
||||
/// Returns the shared [`luxe_core::read_tracker::ReadTracker`] backing the read-before-edit /
|
||||
/// staleness / blind-write guards, so the caller can also wire it into the LSP funnel reads
|
||||
/// (`read_symbol`, `module_report`) that see file content but live in a crate that can't depend
|
||||
/// on `luxe-tools`.
|
||||
pub fn register_builtins(
|
||||
registry: &mut luxe_core::ToolRegistry,
|
||||
todo_store_root: Option<std::path::PathBuf>,
|
||||
web: web::WebConfig,
|
||||
) -> std::sync::Arc<luxe_core::read_tracker::ReadTracker> {
|
||||
use std::sync::Arc;
|
||||
// One shared read tracker backs the read-before-edit + staleness + blind-write guards across
|
||||
// the read/edit/write trio (and the LSP funnel reads, wired by the caller).
|
||||
let read_tracker = Arc::new(luxe_core::read_tracker::ReadTracker::new());
|
||||
// Both of these need a program that may simply not be here, and a tool that cannot work in
|
||||
// this environment should not cost a schema in every request — the same gate `debug` uses.
|
||||
// Where they do work, they cover ground nothing else does, so the gate is on capability, not
|
||||
// on how often they happen to get called.
|
||||
if astgrep::is_available() {
|
||||
registry.register(Arc::new(astgrep::AstGrepTool::new().with_tracker(read_tracker.clone())));
|
||||
}
|
||||
if screenshot::is_available() {
|
||||
registry.register(Arc::new(screenshot::ScreenshotTool::new()));
|
||||
}
|
||||
registry.register(Arc::new(read::ReadTool::new().with_tracker(read_tracker.clone())));
|
||||
registry.register(Arc::new(write::WriteTool::new().with_tracker(read_tracker.clone())));
|
||||
registry.register(Arc::new(edit::EditTool::new().with_tracker(read_tracker.clone())));
|
||||
registry.register(Arc::new(bash::BashTool::new().with_tracker(read_tracker.clone())));
|
||||
registry.register(Arc::new(grep::GrepTool::new().with_tracker(read_tracker.clone())));
|
||||
registry.register(Arc::new(glob::GlobTool::new()));
|
||||
registry.register(Arc::new(question::QuestionTool::new(question::QuestionConfig::default())));
|
||||
registry.register(Arc::new(skill::SkillTool::new(skill::SkillConfig)));
|
||||
registry.register(Arc::new(git::GitTool::new()));
|
||||
registry.register(Arc::new(test_runner::TestTool::new()));
|
||||
|
||||
// Web: both tools are always available and neither needs a key. Search falls back to Exa's
|
||||
// keyless endpoint, so research is a capability a fresh install has rather than one it has to
|
||||
// be configured into. A configured `BRAVE_API_KEY`/`TAVILY_API_KEY`/`EXA_API_KEY` still wins.
|
||||
let web = web::WebTools::new(web);
|
||||
registry.register(Arc::new(web.web_fetch()));
|
||||
registry.register(Arc::new(web.web_search()));
|
||||
|
||||
if let Some(root) = todo_store_root {
|
||||
registry.register(Arc::new(todo::TodoTool::new(root)));
|
||||
}
|
||||
|
||||
read_tracker
|
||||
}
|
||||
82
crates/luxe-tools/src/line_endings.rs
Normal file
82
crates/luxe-tools/src/line_endings.rs
Normal file
@@ -0,0 +1,82 @@
|
||||
//! line_endings — rewrite a file the way it was already written.
|
||||
//!
|
||||
//! A model writes `\n`. A Windows working tree, checked out with git's default `core.autocrlf=true`,
|
||||
//! is `\r\n`. Nothing warns about the mismatch: the `edit` tool's whole-line relaxation trims the
|
||||
//! stray `\r` and matches happily, then writes the replacement back with bare `\n` — so the four
|
||||
//! lines it touched are now the only LF lines in a CRLF file, and `git diff` reports a change to
|
||||
//! every line the user did not ask about.
|
||||
//!
|
||||
//! So the rule is: **the file decides.** We detect what it already uses and convert the payload to
|
||||
//! match. A new file gets `\n`, which is what the model wrote and what git normalizes to on commit.
|
||||
|
||||
/// The line ending a file uses.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum LineEnding {
|
||||
/// `\n` — unix, and the default for anything new
|
||||
Lf,
|
||||
/// `\r\n` — a Windows checkout
|
||||
Crlf,
|
||||
}
|
||||
|
||||
/// Which line ending `content` predominantly uses.
|
||||
///
|
||||
/// Majority rule rather than "any CRLF wins", so one stray `\r\n` in a generated header does not
|
||||
/// convert an entire unix file. A file with no newline at all is [`LineEnding::Lf`].
|
||||
pub(crate) fn detect(content: &str) -> LineEnding {
|
||||
let total = content.matches('\n').count();
|
||||
if total == 0 {
|
||||
return LineEnding::Lf;
|
||||
}
|
||||
let carriage = content.matches("\r\n").count();
|
||||
if carriage * 2 >= total {
|
||||
LineEnding::Crlf
|
||||
} else {
|
||||
LineEnding::Lf
|
||||
}
|
||||
}
|
||||
|
||||
/// Rewrite `text` so every line ends with `ending`, whatever it ends with now.
|
||||
pub(crate) fn normalize(text: &str, ending: LineEnding) -> String {
|
||||
let unix = text.replace("\r\n", "\n");
|
||||
match ending {
|
||||
LineEnding::Lf => unix,
|
||||
LineEnding::Crlf => unix.replace('\n', "\r\n"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_files_dominant_ending_is_what_counts() {
|
||||
assert_eq!(detect("a\nb\nc\n"), LineEnding::Lf);
|
||||
assert_eq!(detect("a\r\nb\r\nc\r\n"), LineEnding::Crlf);
|
||||
assert_eq!(detect("no newline at all"), LineEnding::Lf);
|
||||
assert_eq!(detect(""), LineEnding::Lf);
|
||||
}
|
||||
|
||||
/// One generated `\r\n` in an otherwise unix file must not convert the file.
|
||||
#[test]
|
||||
fn a_single_stray_carriage_return_does_not_win() {
|
||||
assert_eq!(detect("gen\r\na\nb\nc\nd\n"), LineEnding::Lf);
|
||||
assert_eq!(detect("a\r\nb\r\nc\n"), LineEnding::Crlf, "but a majority does");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalizing_is_idempotent_and_lossless_in_both_directions() {
|
||||
let unix = "one\ntwo\nthree";
|
||||
let windows = "one\r\ntwo\r\nthree";
|
||||
assert_eq!(normalize(unix, LineEnding::Crlf), windows);
|
||||
assert_eq!(normalize(windows, LineEnding::Lf), unix);
|
||||
assert_eq!(normalize(windows, LineEnding::Crlf), windows, "already right, left alone");
|
||||
assert_eq!(normalize(unix, LineEnding::Lf), unix);
|
||||
}
|
||||
|
||||
/// A lone `\r` is a classic-Mac ending nobody has produced this century, and treating it as a
|
||||
/// newline would corrupt any file that uses it as data.
|
||||
#[test]
|
||||
fn a_bare_carriage_return_is_data_not_a_line_ending() {
|
||||
assert_eq!(normalize("a\rb", LineEnding::Crlf), "a\rb");
|
||||
}
|
||||
}
|
||||
151
crates/luxe-tools/src/loop_control.rs
Normal file
151
crates/luxe-tools/src/loop_control.rs
Normal file
@@ -0,0 +1,151 @@
|
||||
// Loop control tool — direct the autonomous development loop (progress/complete/blocked).
|
||||
//
|
||||
// This tool is called by the agent to drive the unattended loop: signal phase completion,
|
||||
// trigger verification on all phases done, or pause for human input when blocked.
|
||||
|
||||
use async_trait::async_trait;
|
||||
use luxe_core::hook::{HookEvent, LoopControl};
|
||||
use luxe_core::provider::ToolSchema;
|
||||
use luxe_core::tool::{Tool, ToolContext, ToolResultData};
|
||||
use serde_json::json;
|
||||
|
||||
/// The `loop_control` tool — direct the autonomous loop.
|
||||
pub struct LoopControlTool;
|
||||
|
||||
impl Default for LoopControlTool {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl LoopControlTool {
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for LoopControlTool {
|
||||
fn name(&self) -> &str {
|
||||
"loop_control"
|
||||
}
|
||||
|
||||
/// No deadline of its own: this call *is* the phase gate, and the gate is already bounded.
|
||||
///
|
||||
/// A claim runs the acceptance commands (each capped by `gate.timeout_secs`, ten minutes by
|
||||
/// default) and then a reviewer turn (24 tool calls, ten minutes). The default 120-second tool
|
||||
/// deadline is shorter than either, so on a real project the claim timed out while its own gate
|
||||
/// was still running — the phase advanced, the reviewer's verdict was written to the log, and
|
||||
/// the agent was handed a timeout error instead of the answer. A refusal that never reaches the
|
||||
/// model is a refusal that teaches it nothing.
|
||||
fn timeout(&self) -> Option<std::time::Duration> {
|
||||
None
|
||||
}
|
||||
|
||||
fn schema(&self) -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: "loop_control".to_string(),
|
||||
description: "Direct the autonomous development loop: progress to next phase, complete all phases, or pause when blocked.".to_string(),
|
||||
parameters: json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["progress", "complete", "blocked"],
|
||||
"description": "Loop control action."
|
||||
},
|
||||
"phase": {
|
||||
"type": "integer",
|
||||
"description": "The phase you are claiming complete, for the record. The loop advances by exactly one when the gate agrees; it does not jump to a number you name (a human sets that with `luxe loop phase <n>`)."
|
||||
},
|
||||
"reason": {
|
||||
"type": "string",
|
||||
"description": "Reason for blocking (for blocked action)."
|
||||
}
|
||||
},
|
||||
"required": ["action"]
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(&self, args: serde_json::Value, cx: &ToolContext) -> ToolResultData {
|
||||
let action = match args.get("action").and_then(|v| v.as_str()) {
|
||||
Some(a) => a,
|
||||
None => {
|
||||
return ToolResultData::error(
|
||||
"Error: 'action' argument is required (progress/complete/blocked)".to_string(),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let loop_control = match action {
|
||||
"progress" => {
|
||||
let phase = args.get("phase").and_then(|v| v.as_u64()).map(|n| n as u32);
|
||||
LoopControl::Progress { phase }
|
||||
}
|
||||
"complete" => LoopControl::Complete,
|
||||
"blocked" => {
|
||||
let reason = args
|
||||
.get("reason")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("no reason given")
|
||||
.to_string();
|
||||
LoopControl::Blocked { reason }
|
||||
}
|
||||
other => {
|
||||
return ToolResultData::error(format!(
|
||||
"Unknown action: {other}. Use progress/complete/blocked."
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
// Emit the HookEvent to the hook registry (if available).
|
||||
let result_content = if let Some(hook_ctx) = &cx.hook_ctx {
|
||||
let event = HookEvent::LoopControl(loop_control);
|
||||
let outcome = hook_ctx
|
||||
.hook_registry
|
||||
.invoke(luxe_core::hook::HookPoint::LoopControl, &event, hook_ctx)
|
||||
.await;
|
||||
// Log outcome but don't fail — hooks may return Continue.
|
||||
tracing::debug!(?outcome, "loop_control hook outcome");
|
||||
// Propagate the hook's message/reason back to the agent.
|
||||
match outcome {
|
||||
luxe_core::hook::HookOutcome::ContinueLoop { message } => {
|
||||
vec![luxe_core::ContentBlock::Text(message)]
|
||||
}
|
||||
luxe_core::hook::HookOutcome::StopLoop { reason } => {
|
||||
vec![luxe_core::ContentBlock::Text(format!("Loop stopped: {reason}"))]
|
||||
}
|
||||
luxe_core::hook::HookOutcome::Continue => {
|
||||
vec![luxe_core::ContentBlock::Text(format!("Loop control: {action}"))]
|
||||
}
|
||||
_ => {
|
||||
vec![luxe_core::ContentBlock::Text(format!("Loop control: {action}"))]
|
||||
}
|
||||
}
|
||||
} else {
|
||||
vec![luxe_core::ContentBlock::Text(format!("Loop control: {action}"))]
|
||||
};
|
||||
|
||||
ToolResultData { content: result_content, is_error: false }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A claim outlives the gate it triggers, or the gate's answer never gets back.
|
||||
///
|
||||
/// The break this catches, measured on a live loop: `loop_control` inherited the 120-second
|
||||
/// default while its own gate ran a test suite and a reviewer turn, each bounded in minutes. The
|
||||
/// call was cancelled mid-gate — the phase still advanced, and the developer was told only that
|
||||
/// its tool had timed out.
|
||||
#[test]
|
||||
fn a_phase_claim_outlasts_the_gate_it_runs() {
|
||||
assert!(
|
||||
LoopControlTool::new().timeout().is_none(),
|
||||
"the gate's own bounds are the deadline here"
|
||||
);
|
||||
}
|
||||
}
|
||||
167
crates/luxe-tools/src/output_limit.rs
Normal file
167
crates/luxe-tools/src/output_limit.rs
Normal file
@@ -0,0 +1,167 @@
|
||||
//! Output bounding — cap line-oriented tool results before they reach the model.
|
||||
//!
|
||||
//! `bash` already runs a full compression pipeline (`luxe_core::compression`), but the search/
|
||||
//! listing tools (`grep`, `glob`, `git`, `read`) must not stream their entire output straight into
|
||||
//! the model's context: a broad `grep` or a large `git diff` would bury the conversation and burn
|
||||
//! tokens. This keeps the first `max_lines` of signal, states exactly how much was dropped,
|
||||
//! and hard-clamps total bytes so a single pathological line can't blow the budget either.
|
||||
|
||||
/// Last-resort byte clamp applied after the line cap (guards one huge single line).
|
||||
const MAX_OUTPUT_BYTES: usize = 200_000;
|
||||
|
||||
/// Caps line-oriented output to `max_lines`, and to the shared character budget, appending a
|
||||
/// one-line note about what was dropped.
|
||||
///
|
||||
/// `unit` names the thing being counted (`"matches"`, `"files"`, `"lines"`) and `hint` tells the
|
||||
/// model how to recover the rest (narrow the query, use offset/limit, scope to a path). Output at
|
||||
/// or under both caps is returned untouched. The character budget is the one `read` keeps: a line
|
||||
/// count alone would let a diff of one minified file through at the 200 KB backstop.
|
||||
pub(crate) fn cap_lines(text: &str, max_lines: usize, unit: &str, hint: &str) -> String {
|
||||
cap_lines_within(text, max_lines, luxe_core::output_limit::RESULT_MAX_CHARS, unit, hint)
|
||||
}
|
||||
|
||||
/// [`cap_lines`] under a character budget as well: whichever bound binds first ends the output.
|
||||
///
|
||||
/// A line cap is not a token cap, because a line has no length limit: a broad `grep` over generated
|
||||
/// output can fit tens of kilobytes inside its 200-line cap. So the count alone cannot be the whole
|
||||
/// promise, and a tool whose output is *wide* rather than long needs the second bound.
|
||||
///
|
||||
/// The two are folded into one cut so the note stays last and stays true: capping by line and then
|
||||
/// by character would slice off the very footer that says how much went missing. At least one line
|
||||
/// always survives, however long it is — [`clamp_bytes`] is what stands behind that one.
|
||||
pub(crate) fn cap_lines_within(
|
||||
text: &str,
|
||||
max_lines: usize,
|
||||
max_chars: usize,
|
||||
unit: &str,
|
||||
hint: &str,
|
||||
) -> String {
|
||||
let total = text.lines().count();
|
||||
let mut kept_lines = 0usize;
|
||||
let mut spent = 0usize;
|
||||
for line in text.lines().take(max_lines) {
|
||||
let cost = line.chars().count().saturating_add(1);
|
||||
if kept_lines > 0 && spent.saturating_add(cost) > max_chars {
|
||||
break;
|
||||
}
|
||||
spent = spent.saturating_add(cost);
|
||||
kept_lines += 1;
|
||||
}
|
||||
if kept_lines >= total {
|
||||
return clamp_bytes(text);
|
||||
}
|
||||
let kept = text.lines().take(kept_lines).collect::<Vec<_>>().join("\n");
|
||||
let remaining = total - kept_lines;
|
||||
clamp_bytes(&format!("{kept}\n\n… {remaining} more {unit} not shown ({total} total). {hint}"))
|
||||
}
|
||||
|
||||
/// Head+tail byte clamp for the rare single-huge-line case the line cap can't shrink.
|
||||
fn clamp_bytes(text: &str) -> String {
|
||||
if text.len() <= MAX_OUTPUT_BYTES {
|
||||
return text.to_string();
|
||||
}
|
||||
// Slice on char boundaries so we never split a multi-byte codepoint.
|
||||
let head_end = floor_boundary(text, MAX_OUTPUT_BYTES / 2);
|
||||
let tail_start = ceil_boundary(text, text.len() - MAX_OUTPUT_BYTES / 2);
|
||||
format!(
|
||||
"{}\n-- clamped {} bytes --\n{}",
|
||||
&text[..head_end],
|
||||
text.len() - MAX_OUTPUT_BYTES,
|
||||
&text[tail_start..]
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) use luxe_core::output_limit::{ceil_boundary, floor_boundary};
|
||||
|
||||
/// The head-keeping character cap, shared with every tool that answers, `mcp` included.
|
||||
pub(crate) use luxe_core::output_limit::cap_chars;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn short_output_is_untouched() {
|
||||
let text = "a\nb\nc";
|
||||
assert_eq!(cap_lines(text, 10, "lines", "hint"), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_output_keeps_head_and_notes_the_remainder() {
|
||||
let text = (1..=50).map(|n| n.to_string()).collect::<Vec<_>>().join("\n");
|
||||
let capped = cap_lines(&text, 10, "matches", "Narrow the pattern.");
|
||||
assert!(capped.starts_with("1\n2\n"));
|
||||
assert!(capped.contains("10"));
|
||||
assert!(!capped.contains("\n11\n"), "line 11 is dropped");
|
||||
assert!(capped.contains("40 more matches not shown (50 total)"));
|
||||
assert!(capped.contains("Narrow the pattern."));
|
||||
}
|
||||
|
||||
/// A line cap is not a token cap. Four short lines fit; four long ones do not, and the caller
|
||||
/// gets the same honest footer either way.
|
||||
#[test]
|
||||
fn a_character_budget_binds_before_the_line_cap_when_the_lines_are_wide() {
|
||||
let narrow = (1..=100).map(|n| format!("row {n}\n")).collect::<String>();
|
||||
assert_eq!(
|
||||
cap_lines_within(&narrow, 200, 10_000, "matching lines", "Narrow it."),
|
||||
narrow,
|
||||
"a hundred short rows are under both bounds"
|
||||
);
|
||||
|
||||
let wide = (1..=100).map(|n| format!("row {n} {}\n", "x".repeat(500))).collect::<String>();
|
||||
let capped = cap_lines_within(&wide, 200, 10_000, "matching lines", "Narrow it.");
|
||||
assert!(capped.chars().count() < 11_000, "the budget binds: {}", capped.chars().count());
|
||||
assert!(capped.contains("more matching lines not shown (100 total)"), "{capped}");
|
||||
assert!(capped.trim_end().ends_with("Narrow it."), "the note survives its own cut");
|
||||
}
|
||||
|
||||
/// The footer is the first thing a naive second pass would cut, and it is the one line the
|
||||
/// reader cannot do without.
|
||||
#[test]
|
||||
fn the_note_is_never_truncated_away_by_the_character_budget() {
|
||||
let text = (1..=50).map(|n| format!("{}\n", "y".repeat(100 + n))).collect::<String>();
|
||||
let capped = cap_lines_within(&text, 50, 400, "matches", "Use output_mode files.");
|
||||
assert!(capped.contains("not shown (50 total)"), "{capped}");
|
||||
assert!(capped.contains("Use output_mode files."), "{capped}");
|
||||
}
|
||||
|
||||
/// The budget is what fits, not what almost fits: output landing exactly on it is whole output
|
||||
/// and must not be reported as truncated.
|
||||
#[test]
|
||||
fn output_that_lands_exactly_on_the_budget_is_untouched() {
|
||||
// Four rows of four characters, each costing its own newline: twenty on the nose.
|
||||
let text = "aaaa\nbbbb\ncccc\ndddd\n";
|
||||
assert_eq!(cap_lines_within(text, 200, 20, "matches", "Narrow it."), text);
|
||||
|
||||
let tighter = cap_lines_within(text, 200, 19, "matches", "Narrow it.");
|
||||
assert!(tighter.contains("1 more matches not shown (4 total)"), "{tighter}");
|
||||
}
|
||||
|
||||
/// A budget smaller than the first line still returns that line rather than nothing.
|
||||
#[test]
|
||||
fn one_line_always_survives_however_wide_it_is() {
|
||||
let text = format!("{}\nsecond\n", "z".repeat(5_000));
|
||||
let capped = cap_lines_within(&text, 200, 100, "matches", "Narrow it.");
|
||||
assert!(capped.starts_with(&"z".repeat(100)), "the first line is kept whole");
|
||||
assert!(capped.contains("1 more matches not shown (2 total)"), "{capped}");
|
||||
}
|
||||
|
||||
/// `cap_lines` is the same cut with the character budget switched off, so every existing caller
|
||||
/// keeps the behavior it was written against.
|
||||
#[test]
|
||||
fn cap_lines_is_the_unbudgeted_case_of_cap_lines_within() {
|
||||
let text = (1..=80).map(|n| format!("line {n}\n")).collect::<String>();
|
||||
assert_eq!(
|
||||
cap_lines(&text, 25, "lines", "hint"),
|
||||
cap_lines_within(&text, 25, usize::MAX, "lines", "hint")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn byte_clamp_handles_a_single_giant_line_on_char_boundaries() {
|
||||
let giant = "é".repeat(MAX_OUTPUT_BYTES); // 2 bytes each → well over the clamp
|
||||
let capped = cap_lines(&giant, 10, "lines", "hint");
|
||||
assert!(capped.contains("-- clamped"));
|
||||
assert!(capped.len() < giant.len());
|
||||
}
|
||||
}
|
||||
363
crates/luxe-tools/src/process.rs
Normal file
363
crates/luxe-tools/src/process.rs
Normal file
@@ -0,0 +1,363 @@
|
||||
//! Process — the one way `bash` and `test` run a shell command: bounded, captured, and reaped.
|
||||
//!
|
||||
//! The command gets a session of its own, so a timeout or a cancel can kill everything it started
|
||||
//! (`kill_on_drop` reaches only the shell). Each output stream keeps its first [`HEAD_BYTES`] and
|
||||
//! its last [`TAIL_BYTES`] and counts what fell between, so a command that prints without end
|
||||
//! cannot grow memory without end either. The call ends when the shell does, not when the last
|
||||
//! process holding its pipe lets go — see [`wait_for_output`].
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use tokio::process::Command;
|
||||
|
||||
/// How much of the start of each stream a capture keeps.
|
||||
pub(crate) const HEAD_BYTES: usize = 4 * 1024 * 1024;
|
||||
|
||||
/// How much of the end of each stream a capture keeps.
|
||||
pub(crate) const TAIL_BYTES: usize = 4 * 1024 * 1024;
|
||||
|
||||
/// How long output is still collected after the shell itself has exited.
|
||||
///
|
||||
/// Anything still buffered lands within microseconds of the shell's exit, since every writer is
|
||||
/// gone; this window is slack, not a wait.
|
||||
const DRAIN_GRACE: Duration = Duration::from_millis(250);
|
||||
|
||||
/// How much of a timed-out command's output its result keeps: the tail, where it stopped.
|
||||
const TIMEOUT_TAIL_BYTES: usize = 4_000;
|
||||
|
||||
/// The call ended with the shell, and something it started still had the pipe. Worth a line,
|
||||
/// because the reader is about to compare this output against what a terminal would show, and the
|
||||
/// fix is a detail of shell syntax rather than anything about their command.
|
||||
pub(crate) const DETACHED_WRITER_NOTE: &str =
|
||||
"\n\nNote: a process this command left running still held its \
|
||||
output, so anything written after the shell exited is not here. An `&` on a `&&` list \
|
||||
backgrounds the whole list, which keeps that pipe open; start a long-lived process as \
|
||||
`( cmd >/tmp/out.log 2>&1 & )` to detach it properly.";
|
||||
|
||||
/// How a run ended.
|
||||
pub(crate) enum Outcome {
|
||||
/// The shell exited, with what it printed
|
||||
Finished(Captured),
|
||||
/// The deadline passed. The tree was killed as `run_captured` returned, after the survivors in
|
||||
/// it were listed.
|
||||
TimedOut(TimedOut),
|
||||
}
|
||||
|
||||
/// A command stopped at its deadline: what it had printed, and what was still running.
|
||||
pub(crate) struct TimedOut {
|
||||
/// The end of what it printed, already cut to [`TIMEOUT_TAIL_BYTES`]
|
||||
pub(crate) printed: String,
|
||||
/// The processes still in its group when it was stopped
|
||||
pub(crate) survivors: Vec<luxe_core::program::GroupMember>,
|
||||
}
|
||||
|
||||
/// What one command produced, and whether it outlived its own output.
|
||||
pub(crate) struct Captured {
|
||||
pub(crate) stdout: String,
|
||||
pub(crate) stderr: String,
|
||||
pub(crate) status: std::process::ExitStatus,
|
||||
/// The shell exited while a process it started still held the output pipe.
|
||||
pub(crate) detached_writer: bool,
|
||||
}
|
||||
|
||||
/// The shell command line `command` runs as, in `cwd`, with no terminal and a group of its own.
|
||||
fn shell_command(command: &str, cwd: &Path) -> Command {
|
||||
let (shell, flag) = luxe_core::program::shell();
|
||||
let mut child = Command::new(shell);
|
||||
child
|
||||
.arg(flag)
|
||||
.arg(command)
|
||||
.current_dir(cwd)
|
||||
.kill_on_drop(true)
|
||||
// Never inherit the terminal: a command that reads stdin would eat the user's keystrokes,
|
||||
// and one that writes to the inherited fds would paint over the TUI.
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped());
|
||||
luxe_core::program::detach_from_terminal(&mut child);
|
||||
child
|
||||
}
|
||||
|
||||
/// Whether commands here run through a POSIX shell, which decides how an argument is quoted.
|
||||
pub(crate) fn posix_shell() -> bool {
|
||||
luxe_core::program::shell().1 == "-c"
|
||||
}
|
||||
|
||||
/// `value` as one shell word: POSIX quoting, or `cmd.exe`'s double quotes with inner ones doubled.
|
||||
/// A plain name stays bare either way.
|
||||
///
|
||||
/// `cmd.exe` still expands `%VAR%` inside double quotes, so there a `%` can change the value; it
|
||||
/// cannot end the word or start a command, since `&` and `|` stay quoted.
|
||||
pub(crate) fn quote_argument(value: &str, posix: bool) -> String {
|
||||
let plain = |c: char| c.is_ascii_alphanumeric() || "_-.:/".contains(c);
|
||||
if value.chars().all(plain) {
|
||||
return value.to_string();
|
||||
}
|
||||
if posix {
|
||||
// NUL is the one byte no shell word can hold
|
||||
let value = value.replace('\0', "");
|
||||
return shlex::try_quote(&value).map_or_else(|_| format!("'{value}'"), |q| q.into_owned());
|
||||
}
|
||||
format!("\"{}\"", value.replace('"', "\"\""))
|
||||
}
|
||||
|
||||
/// Runs `command` in `cwd` until it exits or `timeout` passes.
|
||||
///
|
||||
/// Every ending but a clean exit takes the whole tree with it, including the ones nobody writes
|
||||
/// code for: a cancel drops this future, and [`KillTreeOnDrop`] is what answers that.
|
||||
pub(crate) async fn run_captured(
|
||||
command: &str,
|
||||
cwd: &Path,
|
||||
timeout: Duration,
|
||||
) -> std::io::Result<Outcome> {
|
||||
let mut child = shell_command(command, cwd).spawn()?;
|
||||
let pid = child.id().unwrap_or(0);
|
||||
// Armed from here to the first normal exit: every early return, and every drop this function
|
||||
// never sees, takes the whole tree with it.
|
||||
let mut reaper = KillTreeOnDrop::arm(pid);
|
||||
let pipes = Pipes::attach(&mut child);
|
||||
let (stdout, stderr) = pipes.sinks();
|
||||
// Not `tokio::time::timeout`: that drops the wait on expiry, and with it the shell
|
||||
// (`kill_on_drop`), before the survivors can be listed. A group that loses its shell while a
|
||||
// member is suspended is sent SIGHUP by the kernel, so the very processes a timeout most
|
||||
// needs to name would be gone. Pinned here, the wait outlives the listing.
|
||||
let wait = wait_for_output(child, pipes);
|
||||
tokio::pin!(wait);
|
||||
tokio::select! {
|
||||
captured = &mut wait => {
|
||||
let captured = captured?;
|
||||
reaper.disarm();
|
||||
Ok(Outcome::Finished(captured))
|
||||
}
|
||||
() = tokio::time::sleep(timeout) => {
|
||||
let printed = printed_so_far(&stdout, &stderr);
|
||||
// asked before the guard kills them: which processes were still there, and in what
|
||||
// state, is the difference between "slow" and "stuck"
|
||||
let survivors = luxe_core::program::group_members(pid).await;
|
||||
Ok(Outcome::TimedOut(TimedOut { printed, survivors }))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Kills the command's whole process group unless the command finished on its own.
|
||||
///
|
||||
/// `kill_on_drop` reaps the direct child — the shell — and orphans everything the shell started.
|
||||
/// A **cancel** ends the call by *dropping* its future, so there is no code path to hang an
|
||||
/// explicit kill on: pressing Cancel on a `cargo build` left the build running, holding its locks
|
||||
/// and its CPU, with nothing left watching it.
|
||||
///
|
||||
/// Disarmed once the child has been reaped, because a reaped pid can be reused and killing a
|
||||
/// *group* by a recycled id is the one mistake worse than leaking one.
|
||||
struct KillTreeOnDrop(Option<u32>);
|
||||
|
||||
impl KillTreeOnDrop {
|
||||
fn arm(pid: u32) -> Self {
|
||||
Self((pid != 0).then_some(pid))
|
||||
}
|
||||
|
||||
fn disarm(&mut self) {
|
||||
self.0 = None;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for KillTreeOnDrop {
|
||||
fn drop(&mut self) {
|
||||
if let Some(pid) = self.0 {
|
||||
luxe_core::program::kill_tree(pid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One stream's bounded capture: its first bytes, its last bytes, and a count of what fell between.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Capture {
|
||||
head: Vec<u8>,
|
||||
tail: VecDeque<u8>,
|
||||
dropped: u64,
|
||||
}
|
||||
|
||||
impl Capture {
|
||||
/// Takes `bytes` into the head until it is full, then into the tail, dropping the tail's oldest.
|
||||
pub(crate) fn push(&mut self, mut bytes: &[u8]) {
|
||||
let room = HEAD_BYTES.saturating_sub(self.head.len());
|
||||
let (into_head, rest) = bytes.split_at(room.min(bytes.len()));
|
||||
self.head.extend_from_slice(into_head);
|
||||
bytes = rest;
|
||||
self.tail.extend(bytes);
|
||||
if self.tail.len() > TAIL_BYTES {
|
||||
let excess = self.tail.len() - TAIL_BYTES;
|
||||
self.tail.drain(..excess);
|
||||
self.dropped += excess as u64;
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes held, which never passes [`HEAD_BYTES`] + [`TAIL_BYTES`].
|
||||
#[cfg(test)]
|
||||
pub(crate) fn kept(&self) -> usize {
|
||||
self.head.len() + self.tail.len()
|
||||
}
|
||||
|
||||
/// Bytes that fell between head and tail.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn dropped(&self) -> u64 {
|
||||
self.dropped
|
||||
}
|
||||
|
||||
/// The capture as text, with a line saying how much is missing where it went missing.
|
||||
///
|
||||
/// Head and tail are decoded together when nothing fell between them, so a character that
|
||||
/// straddles the head's end survives whole.
|
||||
pub(crate) fn text(&self) -> String {
|
||||
let (front, back) = self.tail.as_slices();
|
||||
if self.dropped == 0 {
|
||||
return String::from_utf8_lossy(&[self.head.as_slice(), front, back].concat())
|
||||
.into_owned();
|
||||
}
|
||||
let head = String::from_utf8_lossy(&self.head);
|
||||
let tail = String::from_utf8_lossy(&[front, back].concat()).into_owned();
|
||||
format!("{head}\n… {} bytes of output not kept …\n{tail}", self.dropped)
|
||||
}
|
||||
}
|
||||
|
||||
type Sink = Arc<Mutex<Capture>>;
|
||||
|
||||
/// One pipe's reader, which goes when the call does.
|
||||
///
|
||||
/// Aborting on drop is the obligation every spawn inside a tool carries: a timed-out or cancelled
|
||||
/// call must not leave a task behind holding a pipe nobody will read.
|
||||
struct Pump(tokio::task::JoinHandle<()>);
|
||||
|
||||
impl Drop for Pump {
|
||||
fn drop(&mut self) {
|
||||
self.0.abort();
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `pipe` into a capture the caller can still read after the reader stops.
|
||||
fn pump(pipe: Option<impl tokio::io::AsyncRead + Unpin + Send + 'static>) -> (Sink, Pump) {
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
let sink = Sink::default();
|
||||
let into = sink.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
let Some(mut pipe) = pipe else { return };
|
||||
let mut buffer = [0u8; 8192];
|
||||
while let Ok(read) = pipe.read(&mut buffer).await {
|
||||
if read == 0 {
|
||||
return;
|
||||
}
|
||||
if let Ok(mut capture) = into.lock() {
|
||||
capture.push(&buffer[..read]);
|
||||
}
|
||||
}
|
||||
});
|
||||
(sink, Pump(task))
|
||||
}
|
||||
|
||||
/// A command's two output pipes, each being read into a capture the caller keeps a handle to.
|
||||
struct Pipes {
|
||||
stdout: Sink,
|
||||
stdout_pump: Pump,
|
||||
stderr: Sink,
|
||||
stderr_pump: Pump,
|
||||
}
|
||||
|
||||
impl Pipes {
|
||||
fn attach(child: &mut tokio::process::Child) -> Self {
|
||||
let (stdout, stdout_pump) = pump(child.stdout.take());
|
||||
let (stderr, stderr_pump) = pump(child.stderr.take());
|
||||
Self { stdout, stdout_pump, stderr, stderr_pump }
|
||||
}
|
||||
|
||||
fn sinks(&self) -> (Sink, Sink) {
|
||||
(self.stdout.clone(), self.stderr.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn text_of(sink: &Sink) -> String {
|
||||
sink.lock().map(|capture| capture.text()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The end of what a command printed before it was stopped, for a result that has to say where
|
||||
/// it got to.
|
||||
fn printed_so_far(stdout: &Sink, stderr: &Sink) -> String {
|
||||
let both = [text_of(stdout), text_of(stderr)]
|
||||
.into_iter()
|
||||
.filter(|text| !text.trim().is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let both = both.trim_end();
|
||||
if both.len() <= TIMEOUT_TAIL_BYTES {
|
||||
return both.to_string();
|
||||
}
|
||||
let start = crate::output_limit::ceil_boundary(both, both.len() - TIMEOUT_TAIL_BYTES);
|
||||
format!("… {} earlier bytes not shown …\n{}", start, &both[start..])
|
||||
}
|
||||
|
||||
/// Waits for the shell to exit, then takes what it wrote.
|
||||
///
|
||||
/// Deliberately not `wait_with_output`, which waits for the pipe to reach **EOF** — held open by
|
||||
/// every process that inherited it, however long it lives. Launching a GUI app or a daemon from a
|
||||
/// `&&` list is enough to do it: the `&` backgrounds the whole list, so the subshell keeps this
|
||||
/// call's pipe while only the last command gets the redirections. A command that reported `sleep
|
||||
/// 8` then sat for a minute is what that looks like from the outside.
|
||||
///
|
||||
/// The captures are the caller's (see [`Pipes`]), so a deadline that drops this future still
|
||||
/// leaves it whatever the command had printed.
|
||||
async fn wait_for_output(
|
||||
mut child: tokio::process::Child,
|
||||
pipes: Pipes,
|
||||
) -> std::io::Result<Captured> {
|
||||
let Pipes { stdout, mut stdout_pump, stderr, mut stderr_pump } = pipes;
|
||||
let status = child.wait().await?;
|
||||
let mut detached_writer = false;
|
||||
for reader in [&mut stdout_pump, &mut stderr_pump] {
|
||||
// Still reading after the grace means something that outlived the shell has the write
|
||||
// end. The reader is dropped either way, so it learns its reader is gone.
|
||||
if tokio::time::timeout(DRAIN_GRACE, &mut reader.0).await.is_err() {
|
||||
detached_writer = true;
|
||||
}
|
||||
}
|
||||
Ok(Captured { stdout: text_of(&stdout), stderr: text_of(&stderr), status, detached_writer })
|
||||
}
|
||||
|
||||
/// Tees a command's output to `.luxe/artifacts/<prefix>-<millis>.log` so the model can recover
|
||||
/// what a summary dropped. Returns the path, or `None` when nothing could be written.
|
||||
///
|
||||
/// Created exclusively, with a counter after the time when that name is taken: the calls of one
|
||||
/// reply run together, and two finishing in one millisecond must not overwrite each other.
|
||||
pub(crate) fn tee_artifact(
|
||||
cwd: &Path,
|
||||
prefix: &str,
|
||||
command: &str,
|
||||
captured: (&str, &str, Option<i32>),
|
||||
) -> Option<PathBuf> {
|
||||
use std::io::Write;
|
||||
|
||||
let (stdout, stderr, exit) = captured;
|
||||
let dir = cwd.join(".luxe").join("artifacts");
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
let millis = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0);
|
||||
let body = format!(
|
||||
"$ {command}\n\n=== STDOUT ===\n{stdout}\n=== STDERR ===\n{stderr}\n=== EXIT ===\n{}\n",
|
||||
exit.unwrap_or(-1)
|
||||
);
|
||||
for attempt in 0..1_000u32 {
|
||||
let name = match attempt {
|
||||
0 => format!("{prefix}-{millis}.log"),
|
||||
n => format!("{prefix}-{millis}-{n}.log"),
|
||||
};
|
||||
let path = dir.join(name);
|
||||
match std::fs::OpenOptions::new().write(true).create_new(true).open(&path) {
|
||||
Ok(mut file) => return file.write_all(body.as_bytes()).ok().map(|()| path),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(_) => return None,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
71
crates/luxe-tools/src/process/tests.rs
Normal file
71
crates/luxe-tools/src/process/tests.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
use super::*;
|
||||
|
||||
/// However much a stream prints, a capture holds its head and its tail and counts the rest.
|
||||
#[test]
|
||||
fn a_capture_holds_its_bound_and_counts_what_fell_between() {
|
||||
let mut capture = Capture::default();
|
||||
let chunk = vec![b'x'; 1024 * 1024];
|
||||
for _ in 0..200 {
|
||||
capture.push(&chunk);
|
||||
}
|
||||
assert_eq!(capture.kept(), HEAD_BYTES + TAIL_BYTES);
|
||||
assert_eq!(capture.dropped(), (200 * chunk.len() - HEAD_BYTES - TAIL_BYTES) as u64);
|
||||
assert!(capture.text().contains("bytes of output not kept"));
|
||||
|
||||
let mut small = Capture::default();
|
||||
small.push(b"all of it\n");
|
||||
assert_eq!(small.text(), "all of it\n", "a short stream is untouched");
|
||||
}
|
||||
|
||||
/// A stream past the head but short of the bound keeps a character that straddles the head's end.
|
||||
///
|
||||
/// The break this catches: head and tail were decoded apart, so an `é` cut by the 4 MB mark came
|
||||
/// back as two replacement characters though nothing was dropped.
|
||||
#[test]
|
||||
fn a_character_across_the_heads_end_survives() {
|
||||
let mut capture = Capture::default();
|
||||
capture.push(&vec![b'a'; HEAD_BYTES - 1]);
|
||||
capture.push("é".as_bytes());
|
||||
let text = capture.text();
|
||||
assert!(text.ends_with('é') && !text.contains('\u{fffd}'));
|
||||
}
|
||||
|
||||
/// A command printing 200 MB is captured within the bound, and says where it lost the middle.
|
||||
///
|
||||
/// The break this catches: every chunk was appended to one buffer for the life of the command, so
|
||||
/// `yes` or a runaway log grew memory until the timeout.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn two_hundred_megabytes_of_output_stays_within_the_bound() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let outcome = run_captured(
|
||||
"head -c 200000000 /dev/zero | tr '\\0' a",
|
||||
dir.path(),
|
||||
Duration::from_secs(120),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let Outcome::Finished(captured) = outcome else { panic!("it finishes") };
|
||||
assert!(captured.stdout.len() <= HEAD_BYTES + TAIL_BYTES + 100, "{}", captured.stdout.len());
|
||||
assert!(captured.stdout.contains("bytes of output not kept"));
|
||||
assert!(captured.status.success());
|
||||
}
|
||||
|
||||
/// Artifacts written in the same instant get names of their own.
|
||||
///
|
||||
/// The break this catches: the name was the millisecond alone, so two calls of one reply that
|
||||
/// finished together overwrote each other's output.
|
||||
#[test]
|
||||
fn artifacts_never_share_a_name() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let paths: std::collections::HashSet<PathBuf> = (0..50)
|
||||
.map(|index| {
|
||||
let stdout = format!("run {index}");
|
||||
tee_artifact(dir.path(), "cmd", "true", (&stdout, "", Some(0))).expect("written")
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(paths.len(), 50);
|
||||
for path in &paths {
|
||||
assert!(std::fs::read_to_string(path).unwrap().contains("run "));
|
||||
}
|
||||
}
|
||||
203
crates/luxe-tools/src/question.rs
Normal file
203
crates/luxe-tools/src/question.rs
Normal file
@@ -0,0 +1,203 @@
|
||||
// Interactive question tool.
|
||||
//
|
||||
// question — ONE question, two or three options with a marked recommendation, and free-text
|
||||
// input. Resolves to the recommended option in unattended mode instead of blocking.
|
||||
|
||||
use async_trait::async_trait;
|
||||
use luxe_core::event::Event;
|
||||
use luxe_core::provider::ToolSchema;
|
||||
use luxe_core::question::{QuestionOption, QuestionOutcome, QuestionReply};
|
||||
use luxe_core::tool::{Tool, ToolContext, ToolResultData};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
/// Hard ceiling on options. Decision time climbs steeply past a handful of choices, and a model
|
||||
/// that lists seven has not made up its mind — the error says so and asks it to merge.
|
||||
const MAX_OPTIONS: usize = 4;
|
||||
|
||||
/// Returns when the shared cancel flag flips to `true` (turn aborted), so a pending question
|
||||
/// unblocks promptly instead of hanging the turn.
|
||||
async fn wait_until_cancelled(cancel: &mut tokio::sync::watch::Receiver<bool>) {
|
||||
if *cancel.borrow() {
|
||||
return;
|
||||
}
|
||||
while cancel.changed().await.is_ok() {
|
||||
if *cancel.borrow() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse the `options` argument, accepting object form or a bare label string per entry.
|
||||
///
|
||||
/// Unparseable entries are dropped rather than failing the call: a malformed option is a worse
|
||||
/// reason to burn a round-trip than a slightly shorter list.
|
||||
fn parse_options(args: &serde_json::Value) -> Vec<QuestionOption> {
|
||||
args.get("options")
|
||||
.and_then(|value| value.as_array())
|
||||
.map(|entries| {
|
||||
entries
|
||||
.iter()
|
||||
.filter_map(|entry| serde_json::from_value::<QuestionOption>(entry.clone()).ok())
|
||||
.filter(|option| !option.label.trim().is_empty())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub(crate) struct QuestionConfig {
|
||||
/// Default resolution mode: "interactive" or "unattended".
|
||||
pub(crate) default_mode: String,
|
||||
/// Default answer for unattended mode.
|
||||
pub(crate) unattended_default: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for QuestionConfig {
|
||||
fn default() -> Self {
|
||||
Self { default_mode: "interactive".to_string(), unattended_default: None }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct QuestionTool {
|
||||
config: Arc<RwLock<QuestionConfig>>,
|
||||
}
|
||||
|
||||
impl QuestionTool {
|
||||
pub(crate) fn new(config: QuestionConfig) -> Self {
|
||||
Self { config: Arc::new(RwLock::new(config)) }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for QuestionTool {
|
||||
fn name(&self) -> &str {
|
||||
"question"
|
||||
}
|
||||
|
||||
/// No deadline: this tool waits on a person. A prompt that dismissed itself while the user was
|
||||
/// reading it would be a worse failure than any hang, and the wait is already bounded by the two
|
||||
/// things that should bound it — the user answering, or the user cancelling the turn.
|
||||
fn argument_aliases(&self) -> &'static [&'static str] {
|
||||
&["question"]
|
||||
}
|
||||
|
||||
fn timeout(&self) -> Option<std::time::Duration> {
|
||||
None
|
||||
}
|
||||
|
||||
fn schema(&self) -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: "question".to_string(),
|
||||
description: "Ask the user ONE question, with two or three distinct options and an \
|
||||
always-available free-text answer. In the interactive TUI this opens a \
|
||||
modal and blocks until the user answers; headless/loop runs resolve to \
|
||||
`default` (or the recommended option) without blocking. Prefer this over \
|
||||
asking in prose when you need a concrete decision.\n\n\
|
||||
One decision per call — wait for the answer before asking the next \
|
||||
thing; never stack several questions into one prompt. Give each option a \
|
||||
short `label` plus a one-line `description` saying what it means or what \
|
||||
it costs, and mark the one you would pick with `\"recommended\": true` \
|
||||
(the modal opens on it). Two or three options is the target and four is \
|
||||
the limit. Don't add an \"Other\" or \"Something else\" option — free \
|
||||
text is always offered."
|
||||
.to_string(),
|
||||
parameters: serde_json::json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"prompt": {"type": "string", "description": "The single question to ask"},
|
||||
"options": {
|
||||
"type": "array",
|
||||
"maxItems": MAX_OPTIONS,
|
||||
"description": "Two or three distinct options (four maximum). A bare string is accepted but loses the rationale.",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"label": {"type": "string", "description": "Short label the user picks (a few words)"},
|
||||
"description": {"type": "string", "description": "One line on what this option means or costs"},
|
||||
"recommended": {"type": "boolean", "description": "True on the one option you would pick; say why in its description"}
|
||||
},
|
||||
"required": ["label"]
|
||||
}
|
||||
},
|
||||
"multi": {"type": "boolean", "description": "Allow multiple selections (only when several answers can be true at once)"},
|
||||
"default": {"type": "string", "description": "Answer to use when nobody is there to ask"}
|
||||
},
|
||||
"required": ["prompt"]
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(&self, args: serde_json::Value, cx: &ToolContext) -> ToolResultData {
|
||||
// `question` is what other harnesses call it, and a model trained on them reaches for it
|
||||
let prompt = match luxe_core::tool::arg(&args, &["prompt", "question"]) {
|
||||
Some(v) => v.as_str().unwrap_or(""),
|
||||
None => {
|
||||
return ToolResultData::error("Error: 'prompt' argument is required");
|
||||
}
|
||||
};
|
||||
|
||||
let options = parse_options(&args);
|
||||
if options.len() > MAX_OPTIONS {
|
||||
return ToolResultData::error(format!(
|
||||
"Error: {} options is too many to choose between. Merge them into the two or \
|
||||
three decisions that actually differ (at most {MAX_OPTIONS}), mark the one \
|
||||
you recommend, and ask again — the free-text row covers the rest.",
|
||||
options.len()
|
||||
));
|
||||
}
|
||||
|
||||
let multi = args.get("multi").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let default_ans = args.get("default").and_then(|v| v.as_str()).map(String::from);
|
||||
|
||||
// Interactive path: a front-end can answer. Register with the broker, emit the prompt, and
|
||||
// block until the user answers or the turn is cancelled.
|
||||
if let Some(broker) = &cx.question_broker {
|
||||
let (id, rx) = broker.register();
|
||||
let _ = cx
|
||||
.event_tx
|
||||
.send(Event::QuestionAsked {
|
||||
id: id.clone(),
|
||||
session_id: cx.session_id.clone(),
|
||||
prompt: prompt.to_string(),
|
||||
options: options.clone(),
|
||||
multi,
|
||||
})
|
||||
.await;
|
||||
|
||||
let mut cancel = cx.cancelled.as_ref().clone();
|
||||
let reply = tokio::select! {
|
||||
reply = rx => reply.unwrap_or(QuestionReply::Cancelled),
|
||||
_ = wait_until_cancelled(&mut cancel) => {
|
||||
broker.forget(&id);
|
||||
QuestionReply::Cancelled
|
||||
}
|
||||
};
|
||||
|
||||
let outcome = match reply {
|
||||
QuestionReply::Answered(answers) => QuestionOutcome::Answered(answers),
|
||||
QuestionReply::Cancelled => QuestionOutcome::Dismissed,
|
||||
};
|
||||
return ToolResultData::text(outcome.result_text());
|
||||
}
|
||||
|
||||
// Unattended (headless/loop): resolve to a default without blocking. Prefer the call's
|
||||
// `default`, then the configured fallback, then the option the agent recommended (which is
|
||||
// a better unattended answer than whichever it happened to list first).
|
||||
let config = self.config.read().await;
|
||||
let answer = default_ans
|
||||
.or_else(|| config.unattended_default.clone())
|
||||
.or_else(|| {
|
||||
options
|
||||
.get(luxe_core::question::default_selection(&options))
|
||||
.map(|option| option.label.clone())
|
||||
})
|
||||
.unwrap_or_else(|| "No answer provided".to_string());
|
||||
let outcome = QuestionOutcome::Unattended { prompt: prompt.to_string(), answer };
|
||||
ToolResultData::text(outcome.result_text())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
276
crates/luxe-tools/src/question/tests.rs
Normal file
276
crates/luxe-tools/src/question/tests.rs
Normal file
@@ -0,0 +1,276 @@
|
||||
use super::*;
|
||||
use luxe_core::ContentBlock;
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
fn test_context(tmp_dir: &std::path::Path) -> ToolContext {
|
||||
let (event_tx, _event_rx) = mpsc::channel(64);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
ToolContext {
|
||||
cwd: tmp_dir.to_path_buf(),
|
||||
session_id: "test-session".to_string(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_question_missing_prompt() {
|
||||
let tool = QuestionTool::new(QuestionConfig::default());
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({}), &ctx).await;
|
||||
assert!(result.is_error);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_question_unattended_mode() {
|
||||
let config = QuestionConfig {
|
||||
default_mode: "unattended".to_string(),
|
||||
unattended_default: Some("Yes".to_string()),
|
||||
};
|
||||
let tool = QuestionTool::new(config);
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool
|
||||
.run(
|
||||
serde_json::json!({
|
||||
"prompt": "Do you want to proceed?",
|
||||
"options": ["Yes", "No"]
|
||||
}),
|
||||
&ctx,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(!result.is_error);
|
||||
let content = match &result.content[0] {
|
||||
ContentBlock::Text(s) => s.clone(),
|
||||
_ => panic!("Expected Text content block"),
|
||||
};
|
||||
assert!(content.contains("Auto-answered"));
|
||||
assert!(content.contains("Yes"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn interactive_question_emits_event_and_awaits_the_brokered_answer() {
|
||||
use luxe_core::question::QuestionBroker;
|
||||
let broker = Arc::new(QuestionBroker::new());
|
||||
let (event_tx, mut event_rx) = mpsc::channel(8);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = ToolContext {
|
||||
cwd: tmp_dir.path().to_path_buf(),
|
||||
session_id: "s1".into(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: Some(broker.clone()),
|
||||
};
|
||||
|
||||
let tool = QuestionTool::new(QuestionConfig::default());
|
||||
let handle = tokio::spawn(async move {
|
||||
tool.run(serde_json::json!({"prompt": "Pick a stack", "options": ["Rust", "Go"]}), &ctx)
|
||||
.await
|
||||
});
|
||||
|
||||
// The tool emits QuestionAsked and blocks; answer it via the broker.
|
||||
let Some(Event::QuestionAsked { id, prompt, options, .. }) = event_rx.recv().await else {
|
||||
panic!("expected a QuestionAsked event");
|
||||
};
|
||||
assert_eq!(prompt, "Pick a stack");
|
||||
assert_eq!(options, vec![QuestionOption::new("Rust"), QuestionOption::new("Go")]);
|
||||
broker.resolve(&id, QuestionReply::Answered(vec!["Rust".into()]));
|
||||
|
||||
let result = handle.await.unwrap();
|
||||
assert!(!result.is_error);
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("The user answered: Rust"), "got: {text}");
|
||||
}
|
||||
|
||||
/// A multi-select answer reaches the model as a list, and comes back off the text as the same
|
||||
/// list — which is what lets the transcript card name each choice after the modal has closed.
|
||||
#[tokio::test]
|
||||
async fn several_answers_reach_the_model_as_a_list_a_card_can_read_back() {
|
||||
use luxe_core::question::{QuestionBroker, QuestionOutcome};
|
||||
let broker = Arc::new(QuestionBroker::new());
|
||||
let (event_tx, mut event_rx) = mpsc::channel(8);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = ToolContext {
|
||||
cwd: tmp_dir.path().to_path_buf(),
|
||||
session_id: "s1".into(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: Some(broker.clone()),
|
||||
};
|
||||
|
||||
let tool = QuestionTool::new(QuestionConfig::default());
|
||||
let handle = tokio::spawn(async move {
|
||||
tool.run(serde_json::json!({"prompt": "Which features?", "multi": true}), &ctx).await
|
||||
});
|
||||
let Some(Event::QuestionAsked { id, .. }) = event_rx.recv().await else {
|
||||
panic!("expected a QuestionAsked event");
|
||||
};
|
||||
let chosen = vec!["Dark mode".to_string(), "and, while you are there, vim keys".to_string()];
|
||||
broker.resolve(&id, QuestionReply::Answered(chosen.clone()));
|
||||
|
||||
let result = handle.await.unwrap();
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert_eq!(QuestionOutcome::parse(text), Some(QuestionOutcome::Answered(chosen)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_question_reports_dismissal() {
|
||||
use luxe_core::question::QuestionBroker;
|
||||
let broker = Arc::new(QuestionBroker::new());
|
||||
let (event_tx, mut event_rx) = mpsc::channel(8);
|
||||
let (cancel_tx, cancel_rx) = watch::channel(false);
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = ToolContext {
|
||||
cwd: tmp_dir.path().to_path_buf(),
|
||||
session_id: "s1".into(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: Some(broker),
|
||||
};
|
||||
|
||||
let tool = QuestionTool::new(QuestionConfig::default());
|
||||
let handle =
|
||||
tokio::spawn(async move { tool.run(serde_json::json!({"prompt": "?"}), &ctx).await });
|
||||
let _ = event_rx.recv().await.expect("QuestionAsked emitted");
|
||||
cancel_tx.send(true).unwrap(); // abort the turn
|
||||
|
||||
let result = handle.await.unwrap();
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("dismissed"), "cancel unblocks the tool: {text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn options_carry_a_rationale_and_a_recommendation_to_the_front_end() {
|
||||
use luxe_core::question::QuestionBroker;
|
||||
let broker = Arc::new(QuestionBroker::new());
|
||||
let (event_tx, mut event_rx) = mpsc::channel(8);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = ToolContext {
|
||||
cwd: tmp_dir.path().to_path_buf(),
|
||||
session_id: "s1".into(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: Some(broker.clone()),
|
||||
};
|
||||
|
||||
let tool = QuestionTool::new(QuestionConfig::default());
|
||||
let handle = tokio::spawn(async move {
|
||||
tool.run(
|
||||
serde_json::json!({
|
||||
"prompt": "Which runtime?",
|
||||
"options": [
|
||||
{"label": "tokio", "description": "already a dependency", "recommended": true},
|
||||
"async-std"
|
||||
]
|
||||
}),
|
||||
&ctx,
|
||||
)
|
||||
.await
|
||||
});
|
||||
|
||||
let Some(Event::QuestionAsked { id, options, .. }) = event_rx.recv().await else {
|
||||
panic!("expected a QuestionAsked event");
|
||||
};
|
||||
assert_eq!(options[0].description.as_deref(), Some("already a dependency"));
|
||||
assert!(options[0].recommended);
|
||||
// A bare string still works; it just arrives without a rationale.
|
||||
assert_eq!(options[1], QuestionOption::new("async-std"));
|
||||
broker.resolve(&id, QuestionReply::Answered(vec!["tokio".into()]));
|
||||
assert!(!handle.await.unwrap().is_error);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn too_many_options_is_rejected_with_an_actionable_message() {
|
||||
let tool = QuestionTool::new(QuestionConfig::default());
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool
|
||||
.run(
|
||||
serde_json::json!({
|
||||
"prompt": "Pick one",
|
||||
"options": ["a", "b", "c", "d", "e"]
|
||||
}),
|
||||
&ctx,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(result.is_error);
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("Merge them"), "tells the model what to do instead: {text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unattended_falls_back_to_the_recommended_option() {
|
||||
let tool = QuestionTool::new(QuestionConfig::default());
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool
|
||||
.run(
|
||||
serde_json::json!({
|
||||
"prompt": "Which runtime?",
|
||||
"options": [
|
||||
{"label": "async-std"},
|
||||
{"label": "tokio", "recommended": true}
|
||||
]
|
||||
}),
|
||||
&ctx,
|
||||
)
|
||||
.await;
|
||||
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("Answer: tokio"), "not merely the first option: {text}");
|
||||
}
|
||||
|
||||
/// Asked in another harness's spelling, `question` rather than `prompt`, it still asks.
|
||||
#[tokio::test]
|
||||
async fn the_question_may_be_spelled_question() {
|
||||
let tool = QuestionTool::new(QuestionConfig::default());
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let args = serde_json::json!({"question": "Which runtime?", "options": ["tokio", "smol"]});
|
||||
let result = tool.run(args, &test_context(tmp_dir.path())).await;
|
||||
assert!(!result.is_error);
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("Which runtime?"), "{text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_question_unattended_no_default() {
|
||||
let config =
|
||||
QuestionConfig { default_mode: "unattended".to_string(), unattended_default: None };
|
||||
let tool = QuestionTool::new(config);
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool
|
||||
.run(
|
||||
serde_json::json!({
|
||||
"prompt": "Confirm?",
|
||||
"default": "Maybe"
|
||||
}),
|
||||
&ctx,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(!result.is_error);
|
||||
let content = match &result.content[0] {
|
||||
ContentBlock::Text(s) => s.clone(),
|
||||
_ => panic!("Expected Text content block"),
|
||||
};
|
||||
assert!(content.contains("Maybe"));
|
||||
}
|
||||
315
crates/luxe-tools/src/read.rs
Normal file
315
crates/luxe-tools/src/read.rs
Normal file
@@ -0,0 +1,315 @@
|
||||
//! `read` tool — read a file's contents, or look at it when it is a picture.
|
||||
//!
|
||||
//! Text reads page with offset/limit and report their own truncation. An **image** file comes back
|
||||
//! as a real image block beside a line of text describing it, so a vision-capable model sees the
|
||||
//! picture and the TUI can draw it — the same path a `screenshot` takes. Before that, pointing
|
||||
//! `read` at a PNG got "this is a binary file, there is nothing to read as source", which is true
|
||||
//! and useless: the file is a design, a chart, a mockup, and looking at it together is the whole
|
||||
//! job.
|
||||
|
||||
mod image_file;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use luxe_core::read_tracker::ReadTracker;
|
||||
use luxe_core::{ContentBlock, Tool, ToolContext, ToolResultData, ToolSchema};
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use tracing::{debug, warn};
|
||||
|
||||
/// Character ceiling for one read, so a minified single-line file cannot flood the context — the
|
||||
/// same one every tool that answers promises.
|
||||
const READ_MAX_CHARS: usize = luxe_core::output_limit::RESULT_MAX_CHARS;
|
||||
|
||||
/// Default line cap for a read with no explicit `limit`, so a huge file can't flood context.
|
||||
const READ_DEFAULT_LIMIT: usize = 2000;
|
||||
|
||||
/// JSON-schema for the read tool arguments.
|
||||
fn read_schema() -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: "read".to_string(),
|
||||
description: "Read a file's contents, or several at once with `paths` — one call for what \
|
||||
`cat a b c` would show, each file under its own header. Line numbers are \
|
||||
1-based: `offset` is the first line \
|
||||
to read and `limit` caps how many lines, matching the line numbers reported by \
|
||||
diagnostics, navigation, and file:line references. That pair *is* the line \
|
||||
range — reaching for a shell one-liner to slice one costs a round-trip and \
|
||||
says nothing about where the slice sits in the file. Each line comes back \
|
||||
prefixed with its number, `12: `, which is not part of the file: leave it \
|
||||
out of an `edit`. A result that stops early says how many lines remain and \
|
||||
the exact `offset` to continue from.\n\
|
||||
An image file (PNG/JPEG/GIF/WebP) comes back as the image itself, downscaled \
|
||||
for the model, so a design, chart, or mockup can simply be looked at \u{2014} \
|
||||
offset/limit do not apply to one.\n\
|
||||
Reading one function or type is `read_symbol`, which finds it by name instead \
|
||||
of a line range you have to guess; a file's shape without its bodies is \
|
||||
`module_report`."
|
||||
.to_string(),
|
||||
parameters: json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Path to the file to read (relative to cwd)"
|
||||
},
|
||||
"paths": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Several files to read in one call (up to 10); instead of `path`. `offset` and `limit` apply to each"
|
||||
},
|
||||
"offset": {
|
||||
"type": "integer",
|
||||
"description": "First line to read, 1-based (optional; default 1)"
|
||||
},
|
||||
"limit": {
|
||||
"type": "integer",
|
||||
"description": "Maximum number of lines to read (optional)"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `read` tool implementation.
|
||||
#[derive(Default)]
|
||||
pub struct ReadTool {
|
||||
/// Shared read tracker; records each read so `edit`/`write` can enforce read-before-mutate.
|
||||
tracker: Option<Arc<ReadTracker>>,
|
||||
}
|
||||
|
||||
impl ReadTool {
|
||||
/// Create a new read tool instance.
|
||||
pub fn new() -> Self {
|
||||
Self { tracker: None }
|
||||
}
|
||||
|
||||
/// Attach the shared read tracker so reads are recorded for the mutation guards.
|
||||
pub fn with_tracker(mut self, tracker: Arc<ReadTracker>) -> Self {
|
||||
self.tracker = Some(tracker);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for ReadTool {
|
||||
fn name(&self) -> &str {
|
||||
"read"
|
||||
}
|
||||
|
||||
fn schema(&self) -> ToolSchema {
|
||||
read_schema()
|
||||
}
|
||||
|
||||
async fn run(&self, args: serde_json::Value, cx: &ToolContext) -> ToolResultData {
|
||||
// 1-based line numbers (match diagnostics/nav/file:line); 0 or missing is treated as line 1.
|
||||
let offset = args.get("offset").and_then(|v| v.as_i64()).unwrap_or(1).max(1) as usize;
|
||||
let limit = args.get("limit").and_then(|v| v.as_i64()).map(|l| l.max(1) as usize);
|
||||
let range = (offset, limit);
|
||||
let paths: Vec<&str> = args
|
||||
.get("paths")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|paths| paths.iter().filter_map(|path| path.as_str()).collect())
|
||||
.unwrap_or_default();
|
||||
let path_str = match args.get("path").and_then(|v| v.as_str()) {
|
||||
Some(s) => s,
|
||||
None if !paths.is_empty() => return self.read_many(&paths, range, cx).await,
|
||||
None => {
|
||||
return ToolResultData::error(
|
||||
"Error: 'path' (or 'paths') argument is required".to_string(),
|
||||
);
|
||||
}
|
||||
};
|
||||
if !paths.is_empty() {
|
||||
let mut every = vec![path_str];
|
||||
every.extend(paths.iter().filter(|path| **path != path_str));
|
||||
return self.read_many(&every, range, cx).await;
|
||||
}
|
||||
self.read_one(path_str, range.0, range.1, cx).await
|
||||
}
|
||||
}
|
||||
|
||||
/// The most files one `read` takes. Enough for a look around a change; past it, a model is
|
||||
/// reading a directory, which is `glob` and then a choice.
|
||||
const READ_MANY_MAX: usize = 10;
|
||||
|
||||
impl ReadTool {
|
||||
/// Each of `paths`, under a header naming it, in one result.
|
||||
///
|
||||
/// The point is the round trip: `cat a b c` answers in one call and three `read`s looked like
|
||||
/// three, which is a large part of why a model reached for the shell to look around. Each file
|
||||
/// is read exactly as alone — guards, images, truncation — and a file that cannot be read says
|
||||
/// why under its header without failing the rest. `range` is `(offset, limit)` for every file,
|
||||
/// since a caller who asked for twenty lines of each did not mean all of them.
|
||||
async fn read_many(
|
||||
&self,
|
||||
paths: &[&str],
|
||||
range: (usize, Option<usize>),
|
||||
cx: &ToolContext,
|
||||
) -> ToolResultData {
|
||||
let mut content = Vec::new();
|
||||
let mut text = String::new();
|
||||
let mut failed = 0;
|
||||
for path in paths.iter().take(READ_MANY_MAX) {
|
||||
let one = self.read_one(path, range.0, range.1, cx).await;
|
||||
failed += usize::from(one.is_error);
|
||||
if !text.is_empty() {
|
||||
text.push_str("\n\n");
|
||||
}
|
||||
text.push_str(&format!("── {path} ──\n"));
|
||||
for block in one.content {
|
||||
match block {
|
||||
ContentBlock::Text(body) => text.push_str(&body),
|
||||
image => content.push(image),
|
||||
}
|
||||
}
|
||||
}
|
||||
if paths.len() > READ_MANY_MAX {
|
||||
text.push_str(&format!(
|
||||
"\n\n-- {} more not read: one call takes {READ_MANY_MAX} files --",
|
||||
paths.len() - READ_MANY_MAX
|
||||
));
|
||||
}
|
||||
let text = crate::output_limit::cap_chars(
|
||||
&text,
|
||||
READ_MAX_CHARS,
|
||||
"Read fewer files at once, or a range of one with offset/limit.",
|
||||
);
|
||||
content.insert(0, ContentBlock::Text(text));
|
||||
ToolResultData { content, is_error: failed == paths.len().min(READ_MANY_MAX) }
|
||||
}
|
||||
|
||||
/// One file, from `offset` for at most `limit` lines.
|
||||
async fn read_one(
|
||||
&self,
|
||||
path_str: &str,
|
||||
offset: usize,
|
||||
limit: Option<usize>,
|
||||
cx: &ToolContext,
|
||||
) -> ToolResultData {
|
||||
// Resolve path relative to cwd.
|
||||
let full_path = cx.cwd.join(path_str);
|
||||
|
||||
debug!(path = %full_path.display(), offset, limit = limit.unwrap_or(usize::MAX), "reading file");
|
||||
|
||||
// A picture is not a failed text file. Sniffed by content rather than by extension: a
|
||||
// `.txt` holding a PNG is still a PNG, and a `.png` holding markup is still markup.
|
||||
match image_file::read(&full_path, path_str) {
|
||||
image_file::Outcome::NotAnImage => {}
|
||||
image_file::Outcome::Read(result) => {
|
||||
if let Some(tracker) = &self.tracker {
|
||||
tracker.record(&cx.session_id, &full_path);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
// Read the file.
|
||||
let content = match std::fs::read_to_string(&full_path) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
warn!(path = %full_path.display(), error = %e, "failed to read file");
|
||||
// "stream did not contain valid UTF-8" is true and useless. Say what it is and
|
||||
// what to do about it, so the model stops rather than retrying the same read.
|
||||
let message = if e.kind() == std::io::ErrorKind::InvalidData {
|
||||
let size = std::fs::metadata(&full_path).map(|m| m.len()).unwrap_or(0);
|
||||
format!(
|
||||
"'{}' is a binary file ({size} bytes), not text — there is nothing to read \
|
||||
as source. Use `bash` if you genuinely need its bytes.",
|
||||
path_str
|
||||
)
|
||||
} else {
|
||||
format!("Error reading file '{}': {}", luxe_core::paths::display(&full_path), e)
|
||||
};
|
||||
return ToolResultData::error(message);
|
||||
}
|
||||
};
|
||||
|
||||
// Apply offset/limit (offset is 1-based; convert to a 0-based slice index).
|
||||
let lines: Vec<&str> = content.lines().collect();
|
||||
let start = offset.saturating_sub(1).min(lines.len());
|
||||
// A read with no explicit limit is capped at a sane default so a huge file can't flood
|
||||
// context in one call; the truncation note steers the model to page with offset/limit.
|
||||
let end = match limit {
|
||||
Some(l) => (start + l).min(lines.len()),
|
||||
None => (start + READ_DEFAULT_LIMIT).min(lines.len()),
|
||||
};
|
||||
|
||||
// An empty file is a fact, not a failure — reporting "offset exceeds file length" for one
|
||||
// sends the model hunting for a bad argument it never passed.
|
||||
if lines.is_empty() {
|
||||
return ToolResultData::text(format!("'{path_str}' is empty (0 lines)."));
|
||||
}
|
||||
|
||||
if start >= lines.len() {
|
||||
return ToolResultData::error(format!(
|
||||
"Error: offset {offset} is past the end of '{path_str}' ({} lines).",
|
||||
lines.len()
|
||||
));
|
||||
}
|
||||
|
||||
// Record that this session has now seen the file (any successful read counts) so the
|
||||
// edit/write guards accept a subsequent mutation.
|
||||
if let Some(tracker) = &self.tracker {
|
||||
tracker.record(&cx.session_id, &full_path);
|
||||
}
|
||||
|
||||
ToolResultData::text(window(&lines, start, end, limit.is_some()))
|
||||
}
|
||||
}
|
||||
|
||||
/// `lines[start..end]` as a result, each line numbered, kept under [`READ_MAX_CHARS`] by cutting at
|
||||
/// a line boundary.
|
||||
///
|
||||
/// Numbered because Luxe's other tools take line numbers as input (`lsp_navigation` positions,
|
||||
/// `debug` breakpoints, `read`'s own `offset`), and a line the agent has to count to is one it gets
|
||||
/// wrong. A result that stops early closes with the exact `offset` to continue from. The line cap
|
||||
/// cannot bound a minified file, one enormous line, so the character budget is counted as lines
|
||||
/// are taken, and a single line too long to show says so rather than suggesting an offset that
|
||||
/// cannot help.
|
||||
fn window(lines: &[&str], start: usize, end: usize, explicit_limit: bool) -> String {
|
||||
let total = lines.len();
|
||||
let mut body = String::new();
|
||||
let mut budget = READ_MAX_CHARS;
|
||||
let mut shown_end = start;
|
||||
for (index, line) in lines[start..end].iter().enumerate() {
|
||||
let numbered = format!("{}: {line}\n", start + index + 1);
|
||||
let cost = numbered.chars().count();
|
||||
if cost > budget {
|
||||
break;
|
||||
}
|
||||
body.push_str(&numbered);
|
||||
budget -= cost;
|
||||
shown_end += 1;
|
||||
}
|
||||
// A first line too long to show: what fits of it, and the honest way to the rest
|
||||
if shown_end == start {
|
||||
let line = lines[start];
|
||||
let kept: String = line.chars().take(READ_MAX_CHARS).collect();
|
||||
return format!(
|
||||
"{}: {kept}\n-- line {} is {} characters, more than one read returns; `grep` the file \
|
||||
for what you need --",
|
||||
start + 1,
|
||||
start + 1,
|
||||
line.chars().count()
|
||||
);
|
||||
}
|
||||
let mut out = body.trim_end_matches('\n').to_string();
|
||||
if shown_end < total {
|
||||
let why = if shown_end < end {
|
||||
format!(" (stopped at the {READ_MAX_CHARS}-character cap)")
|
||||
} else if !explicit_limit {
|
||||
format!(" (a read without `limit` stops at {READ_DEFAULT_LIMIT} lines)")
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
out.push_str(&format!(
|
||||
"\n-- {} more of {total} lines{why}; continue with offset {} --",
|
||||
total - shown_end,
|
||||
shown_end + 1
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
288
crates/luxe-tools/src/read/image_file.rs
Normal file
288
crates/luxe-tools/src/read/image_file.rs
Normal file
@@ -0,0 +1,288 @@
|
||||
//! Reading a file that turns out to be a picture.
|
||||
//!
|
||||
//! Split out of [`super`] because it answers a different question from the rest of `read`: not
|
||||
//! "which lines" but "is this even text, and if not, can it be looked at". Nothing here touches the
|
||||
//! offset/limit machinery, and the caller only has to ask once, before it opens the file as text.
|
||||
|
||||
use luxe_core::ContentBlock;
|
||||
use luxe_core::ToolResultData;
|
||||
use std::path::Path;
|
||||
|
||||
/// Longest edge (px) of the copy handed to the model.
|
||||
///
|
||||
/// The same bound `screenshot` uses, and for the same reason: it is Anthropic's recommended maximum
|
||||
/// long edge, past which an image costs tokens without carrying more detail.
|
||||
const MAX_INLINE_DIM: u32 = 1568;
|
||||
|
||||
/// Bytes a file may hold before `read` declines to decode it.
|
||||
///
|
||||
/// A read is a foreground call in a turn the user is waiting on, and a 60 MB TIFF is not something
|
||||
/// anyone meant to look at inline.
|
||||
const MAX_FILE_BYTES: u64 = 24 * 1024 * 1024;
|
||||
|
||||
/// Pixels an image may decode to. Four bytes each, so this is the real memory bound.
|
||||
const MAX_PIXELS: u64 = 40_000_000;
|
||||
|
||||
/// What [`read`] concluded about the file.
|
||||
pub(super) enum Outcome {
|
||||
/// Not an image; the caller should read it as text.
|
||||
NotAnImage,
|
||||
/// An image, and this is the answer — including when it could not be decoded, because at that
|
||||
/// point "this is a broken PNG" is the useful thing to say rather than "this is not UTF-8".
|
||||
Read(ToolResultData),
|
||||
}
|
||||
|
||||
/// Reads `path` as an image, or reports that it is not one.
|
||||
///
|
||||
/// `display` is the path as the caller wrote it, so the result talks about the file they asked for
|
||||
/// rather than the absolute path it resolved to.
|
||||
pub(super) fn read(path: &Path, display: &str) -> Outcome {
|
||||
let Some(format) = sniff(path) else {
|
||||
return Outcome::NotAnImage;
|
||||
};
|
||||
let size = std::fs::metadata(path).map(|meta| meta.len()).unwrap_or(0);
|
||||
if size > MAX_FILE_BYTES {
|
||||
return Outcome::Read(ToolResultData::error(format!(
|
||||
"'{display}' is a {} image of {} MB, too large to read inline. Open it outside the \
|
||||
session, or resize a copy first.",
|
||||
format_name(format),
|
||||
size / (1024 * 1024)
|
||||
)));
|
||||
}
|
||||
|
||||
let bytes = match std::fs::read(path) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) => {
|
||||
return Outcome::Read(ToolResultData::error(format!(
|
||||
"Error reading image '{display}': {error}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
let decoded = match image::load_from_memory_with_format(&bytes, format) {
|
||||
Ok(decoded) => decoded,
|
||||
Err(error) => {
|
||||
return Outcome::Read(ToolResultData::error(format!(
|
||||
"'{display}' looks like a {} image but could not be decoded: {error}",
|
||||
format_name(format)
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
let (width, height) = (decoded.width(), decoded.height());
|
||||
if u64::from(width) * u64::from(height) > MAX_PIXELS {
|
||||
return Outcome::Read(ToolResultData::error(format!(
|
||||
"'{display}' is {width}x{height}, too many pixels to read inline."
|
||||
)));
|
||||
}
|
||||
|
||||
// The saved file stays untouched; only the copy that travels to the model is bounded.
|
||||
let inline = if width > MAX_INLINE_DIM || height > MAX_INLINE_DIM {
|
||||
decoded.resize(MAX_INLINE_DIM, MAX_INLINE_DIM, image::imageops::FilterType::Lanczos3)
|
||||
} else {
|
||||
decoded
|
||||
};
|
||||
let mut png = std::io::Cursor::new(Vec::new());
|
||||
if let Err(error) = inline.write_to(&mut png, image::ImageFormat::Png) {
|
||||
return Outcome::Read(ToolResultData::error(format!(
|
||||
"'{display}' could not be re-encoded: {error}"
|
||||
)));
|
||||
}
|
||||
|
||||
let scaled = (inline.width(), inline.height()) != (width, height);
|
||||
let mut summary =
|
||||
format!("{display}: {} image, {width}x{height}, {} KB.", format_name(format), size / 1024);
|
||||
if scaled {
|
||||
summary.push_str(&format!(
|
||||
" Shown at {}x{} \u{2014} the file is unchanged.",
|
||||
inline.width(),
|
||||
inline.height()
|
||||
));
|
||||
}
|
||||
// Said out loud because a text-only model receives the sentence and nothing else, and silence
|
||||
// would leave it guessing why a file it asked for came back almost empty.
|
||||
summary.push_str(" The image itself follows; a model without vision sees only this line.");
|
||||
|
||||
use base64::Engine as _;
|
||||
Outcome::Read(ToolResultData {
|
||||
content: vec![
|
||||
ContentBlock::Text(summary),
|
||||
ContentBlock::Image {
|
||||
data: base64::engine::general_purpose::STANDARD.encode(png.into_inner()),
|
||||
mime: "image/png".to_string(),
|
||||
name: Some(luxe_core::paths::display(path)),
|
||||
},
|
||||
],
|
||||
is_error: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The image format `path` really holds, by its magic bytes.
|
||||
///
|
||||
/// Content rather than extension: a `.txt` holding a PNG is a PNG, and a `.png` holding markup is
|
||||
/// markup. Reading a header is also the only bound that holds before a decode — an extension check
|
||||
/// would happily hand a decompression bomb to the decoder.
|
||||
fn sniff(path: &Path) -> Option<image::ImageFormat> {
|
||||
use std::io::Read as _;
|
||||
let mut header = [0u8; 16];
|
||||
let mut file = std::fs::File::open(path).ok()?;
|
||||
let read = file.read(&mut header).ok()?;
|
||||
let format = image::guess_format(&header[..read]).ok()?;
|
||||
// Only the formats this build actually links a decoder for; anything else is not an image as
|
||||
// far as `read` is concerned, and saying so beats a decode error the caller cannot act on.
|
||||
matches!(
|
||||
format,
|
||||
image::ImageFormat::Png
|
||||
| image::ImageFormat::Jpeg
|
||||
| image::ImageFormat::Gif
|
||||
| image::ImageFormat::WebP
|
||||
)
|
||||
.then_some(format)
|
||||
}
|
||||
|
||||
fn format_name(format: image::ImageFormat) -> &'static str {
|
||||
match format {
|
||||
image::ImageFormat::Png => "PNG",
|
||||
image::ImageFormat::Jpeg => "JPEG",
|
||||
image::ImageFormat::Gif => "GIF",
|
||||
image::ImageFormat::WebP => "WebP",
|
||||
_ => "image",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write_png(dir: &Path, name: &str, width: u32, height: u32) -> std::path::PathBuf {
|
||||
let path = dir.join(name);
|
||||
let pixels = image::RgbaImage::from_pixel(width, height, image::Rgba([9, 40, 120, 255]));
|
||||
image::DynamicImage::ImageRgba8(pixels).save(&path).expect("write png");
|
||||
path
|
||||
}
|
||||
|
||||
fn image_block(result: &ToolResultData) -> Option<(&String, &String)> {
|
||||
result.content.iter().find_map(|block| match block {
|
||||
ContentBlock::Image { data, mime, .. } => Some((data, mime)),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn text_of(result: &ToolResultData) -> String {
|
||||
result
|
||||
.content
|
||||
.iter()
|
||||
.filter_map(|block| match block {
|
||||
ContentBlock::Text(text) => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The point of the whole module: an image file comes back as an image, with a sentence a
|
||||
/// text-only model can still act on.
|
||||
#[test]
|
||||
fn an_image_file_comes_back_as_an_image() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
let path = write_png(dir.path(), "design.png", 40, 20);
|
||||
|
||||
let Outcome::Read(result) = read(&path, "design.png") else {
|
||||
panic!("a png is an image");
|
||||
};
|
||||
assert!(!result.is_error);
|
||||
let (data, mime) = image_block(&result).expect("an image block");
|
||||
assert_eq!(mime, "image/png");
|
||||
assert!(!data.is_empty());
|
||||
|
||||
let text = text_of(&result);
|
||||
assert!(text.contains("design.png") && text.contains("40x20"), "{text}");
|
||||
assert!(text.contains("without vision"), "a text-only model is told what it is missing");
|
||||
}
|
||||
|
||||
/// The image block carries where it came from, so a front-end can offer to open the real file
|
||||
/// and a model looking at three pictures can tell them apart.
|
||||
#[test]
|
||||
fn an_image_block_names_the_file_it_came_from() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
let path = write_png(dir.path(), "chart.png", 8, 8);
|
||||
let Outcome::Read(result) = read(&path, "chart.png") else { panic!("an image") };
|
||||
let named = result.content.iter().any(|block| {
|
||||
matches!(block, ContentBlock::Image { name: Some(name), .. } if name.ends_with("chart.png"))
|
||||
});
|
||||
assert!(named, "the image block names its file");
|
||||
}
|
||||
|
||||
/// Format is decided by content. An extension check would call this text and hand a decoder a
|
||||
/// file it never validated.
|
||||
#[test]
|
||||
fn the_contents_decide_the_format_not_the_extension() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
let lying = write_png(dir.path(), "notes.png", 4, 4);
|
||||
std::fs::rename(&lying, dir.path().join("notes.txt")).expect("rename");
|
||||
let renamed = dir.path().join("notes.txt");
|
||||
assert!(
|
||||
matches!(read(&renamed, "notes.txt"), Outcome::Read(_)),
|
||||
"a PNG named .txt is a PNG"
|
||||
);
|
||||
|
||||
let markup = dir.path().join("page.png");
|
||||
std::fs::write(&markup, "<html>not really a png</html>").expect("write");
|
||||
assert!(
|
||||
matches!(read(&markup, "page.png"), Outcome::NotAnImage),
|
||||
"markup named .png is markup, and the text path should have it"
|
||||
);
|
||||
}
|
||||
|
||||
/// Source files must be untouched by any of this, or every read pays a header probe's worth of
|
||||
/// wrong answers.
|
||||
#[test]
|
||||
fn ordinary_files_are_left_to_the_text_path() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
for (name, body) in
|
||||
[("lib.rs", "fn main() {}"), ("empty.txt", ""), ("data.json", "{\"a\":1}")]
|
||||
{
|
||||
let path = dir.path().join(name);
|
||||
std::fs::write(&path, body).expect("write");
|
||||
assert!(matches!(read(&path, name), Outcome::NotAnImage), "{name}");
|
||||
}
|
||||
assert!(matches!(read(&dir.path().join("gone.png"), "gone.png"), Outcome::NotAnImage));
|
||||
}
|
||||
|
||||
/// A big picture is scaled for the model and the file is left alone — and the summary says so,
|
||||
/// so nobody concludes the file on disk was rewritten.
|
||||
#[test]
|
||||
fn a_large_image_is_scaled_for_the_model_and_says_so() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
let path = write_png(dir.path(), "huge.png", MAX_INLINE_DIM + 400, 600);
|
||||
|
||||
let Outcome::Read(result) = read(&path, "huge.png") else { panic!("an image") };
|
||||
let text = text_of(&result);
|
||||
assert!(text.contains(&format!("{}x600", MAX_INLINE_DIM + 400)), "true size: {text}");
|
||||
assert!(text.contains("Shown at"), "and the size it was shown at: {text}");
|
||||
assert!(text.contains("file is unchanged"), "{text}");
|
||||
|
||||
use base64::Engine as _;
|
||||
let (data, _) = image_block(&result).expect("an image block");
|
||||
let decoded = base64::engine::general_purpose::STANDARD.decode(data).expect("base64");
|
||||
let inline = image::load_from_memory(&decoded).expect("a png");
|
||||
assert!(inline.width() <= MAX_INLINE_DIM && inline.height() <= MAX_INLINE_DIM);
|
||||
}
|
||||
|
||||
/// A file that claims to be a picture and is not decodable is an error about *that*, not a
|
||||
/// UTF-8 complaint from the text path.
|
||||
#[test]
|
||||
fn a_corrupt_image_says_what_is_wrong_with_it() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
let path = dir.path().join("truncated.png");
|
||||
// A valid PNG signature and header, then nothing.
|
||||
std::fs::write(&path, [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 13])
|
||||
.expect("write");
|
||||
|
||||
let Outcome::Read(result) = read(&path, "truncated.png") else {
|
||||
panic!("it announced itself as a png");
|
||||
};
|
||||
assert!(result.is_error);
|
||||
let text = text_of(&result);
|
||||
assert!(text.contains("PNG") && text.contains("could not be decoded"), "{text}");
|
||||
assert!(!text.contains("UTF-8"), "not the text path's words: {text}");
|
||||
}
|
||||
}
|
||||
265
crates/luxe-tools/src/read/tests.rs
Normal file
265
crates/luxe-tools/src/read/tests.rs
Normal file
@@ -0,0 +1,265 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
fn test_context(tmp_dir: &std::path::Path) -> ToolContext {
|
||||
let (event_tx, _event_rx) = mpsc::channel(64);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
ToolContext {
|
||||
cwd: tmp_dir.to_path_buf(),
|
||||
session_id: "test-session".to_string(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Several files in one call, each under its header and each recorded for the edit guards;
|
||||
/// one that cannot be read says so without failing the rest.
|
||||
#[tokio::test]
|
||||
async fn several_files_read_in_one_call() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("a.txt"), "alpha").unwrap();
|
||||
std::fs::write(dir.path().join("b.txt"), "beta").unwrap();
|
||||
let tracker = Arc::new(ReadTracker::new());
|
||||
let tool = ReadTool::new().with_tracker(tracker.clone());
|
||||
let cx = test_context(dir.path());
|
||||
|
||||
let result = tool.run(json!({"paths": ["a.txt", "b.txt", "missing.txt"]}), &cx).await;
|
||||
assert!(!result.is_error, "two of three read");
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("text") };
|
||||
assert!(text.contains("── a.txt ──\n1: alpha"), "{text}");
|
||||
assert!(text.contains("── b.txt ──\n1: beta"), "{text}");
|
||||
assert!(text.contains("── missing.txt ──\nError reading file"), "{text}");
|
||||
for name in ["a.txt", "b.txt"] {
|
||||
assert_eq!(
|
||||
tracker.status("test-session", &dir.path().join(name)),
|
||||
luxe_core::read_tracker::ReadStatus::Current,
|
||||
"{name} counts as read"
|
||||
);
|
||||
}
|
||||
|
||||
let none = tool.run(json!({"paths": ["missing.txt"]}), &cx).await;
|
||||
assert!(none.is_error, "nothing read is a failure");
|
||||
let both = tool.run(json!({"path": "a.txt", "paths": ["b.txt"]}), &cx).await;
|
||||
let ContentBlock::Text(text) = &both.content[0] else { panic!("text") };
|
||||
assert!(text.contains("── a.txt ──") && text.contains("── b.txt ──"), "{text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_tool_basic() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let tmp_dir = tmp_dir_guard.path().to_path_buf();
|
||||
std::fs::write(tmp_dir.join("test.txt"), "line1\nline2\nline3").unwrap();
|
||||
|
||||
let tool = ReadTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({"path": "test.txt"});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(!result.is_error);
|
||||
if let ContentBlock::Text(text) = &result.content[0] {
|
||||
assert_eq!(text, "1: line1\n2: line2\n3: line3");
|
||||
} else {
|
||||
panic!("expected Text block");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_tool_caps_a_huge_file_without_an_explicit_limit() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
let big = (1..=(READ_DEFAULT_LIMIT + 500)).map(|n| n.to_string()).collect::<Vec<_>>();
|
||||
std::fs::write(dir.path().join("big.txt"), big.join("\n")).unwrap();
|
||||
let result = ReadTool::new().run(json!({"path": "big.txt"}), &test_context(dir.path())).await;
|
||||
assert!(!result.is_error);
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected Text block") };
|
||||
assert!(text.starts_with("1: 1\n2: 2\n"), "{}", &text[..20]);
|
||||
assert!(
|
||||
text.ends_with(
|
||||
"-- 500 more of 2500 lines (a read without `limit` stops at 2000 lines); \
|
||||
continue with offset 2001 --"
|
||||
),
|
||||
"default cap fires and names the next offset: {}",
|
||||
&text[text.len().saturating_sub(120)..]
|
||||
);
|
||||
assert!(text.lines().any(|l| l == "2000: 2000"), "last kept line present");
|
||||
assert!(!text.lines().any(|l| l.starts_with("2001: ")), "line past the cap dropped");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_tool_with_offset_limit() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
std::fs::write(dir.path().join("test.txt"), "line1\nline2\nline3\nline4\nline5").unwrap();
|
||||
// 1-based: offset 2 starts at line2, limit 2 reads line2+line3
|
||||
let args = json!({"path": "test.txt", "offset": 2, "limit": 2});
|
||||
let result = ReadTool::new().run(args, &test_context(dir.path())).await;
|
||||
assert!(!result.is_error);
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected Text block") };
|
||||
assert_eq!(text, "2: line2\n3: line3\n-- 2 more of 5 lines; continue with offset 4 --");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_tool_missing_path() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let tmp_dir = tmp_dir_guard.path().to_path_buf();
|
||||
|
||||
let tool = ReadTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(result.is_error);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_tool_nonexistent_file() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let tmp_dir = tmp_dir_guard.path().to_path_buf();
|
||||
|
||||
let tool = ReadTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({"path": "nonexistent.txt"});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(result.is_error);
|
||||
}
|
||||
|
||||
/// A minified bundle or a large JSON blob is *one line*, so the line cap never fires and a
|
||||
/// single read returned half a megabyte straight into the context window.
|
||||
#[tokio::test]
|
||||
async fn a_minified_single_line_file_is_bounded() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
std::fs::write(dir.path().join("bundle.js"), "x".repeat(500_000)).expect("write");
|
||||
let tool = ReadTool::new();
|
||||
let result =
|
||||
tool.run(serde_json::json!({"path": "bundle.js"}), &test_context(dir.path())).await;
|
||||
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.chars().count() < READ_MAX_CHARS + 300, "bounded: {} chars", text.chars().count());
|
||||
assert!(text.contains("line 1 is 500000 characters"), "and says so");
|
||||
assert!(
|
||||
text.contains("grep"),
|
||||
"with a way to get what you need: {}",
|
||||
&text[text.len() - 160..]
|
||||
);
|
||||
}
|
||||
|
||||
/// A file of ordinary lines that outruns the character cap stops at a whole line, says so, and
|
||||
/// names the line to continue from, which is where the old note gave a wrong total and no offset.
|
||||
#[tokio::test]
|
||||
async fn the_character_cap_stops_at_a_line_and_says_where_to_continue() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
let line = "y".repeat(99);
|
||||
let lines = vec![line.as_str(); 1000];
|
||||
std::fs::write(dir.path().join("wide.txt"), lines.join("\n")).expect("write");
|
||||
let result = ReadTool::new()
|
||||
.run(serde_json::json!({"path": "wide.txt"}), &test_context(dir.path()))
|
||||
.await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
// each row is `N: `, 99 characters and a newline
|
||||
let (mut shown, mut spent) = (0, 0);
|
||||
while spent + format!("{}: ", shown + 1).len() + 100 <= READ_MAX_CHARS {
|
||||
spent += format!("{}: ", shown + 1).len() + 100;
|
||||
shown += 1;
|
||||
}
|
||||
assert!(text.starts_with("1: yyy"), "{}", &text[..40]);
|
||||
assert!(
|
||||
text.ends_with(&format!(
|
||||
"-- {} more of 1000 lines (stopped at the {READ_MAX_CHARS}-character cap); \
|
||||
continue with offset {} --",
|
||||
1000 - shown,
|
||||
shown + 1
|
||||
)),
|
||||
"{}",
|
||||
&text[text.len() - 120..]
|
||||
);
|
||||
assert!(
|
||||
text.lines().all(|row| row.starts_with("--") || row.ends_with(&"y".repeat(99))),
|
||||
"whole lines only"
|
||||
);
|
||||
}
|
||||
|
||||
/// `offset` and `limit` apply to each of `paths`, rather than being dropped in silence.
|
||||
#[tokio::test]
|
||||
async fn a_range_applies_to_each_of_several_files() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
std::fs::write(dir.path().join("a.txt"), "a1\na2\na3\na4").expect("write");
|
||||
std::fs::write(dir.path().join("b.txt"), "b1\nb2").expect("write");
|
||||
let args = serde_json::json!({"paths": ["a.txt", "b.txt"], "limit": 1});
|
||||
let result = ReadTool::new().run(args, &test_context(dir.path())).await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(
|
||||
text.contains("── a.txt ──\n1: a1\n-- 3 more of 4 lines; continue with offset 2 --"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(
|
||||
text.contains("── b.txt ──\n1: b1\n-- 1 more of 2 lines; continue with offset 2 --"),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A line that exactly fills the budget is shown whole, and the cap stops at the line after it.
|
||||
#[tokio::test]
|
||||
async fn a_line_exactly_the_size_of_the_cap_is_shown() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
// `1: `, the line and its newline come to exactly the cap
|
||||
let exact = "z".repeat(READ_MAX_CHARS - 4);
|
||||
std::fs::write(dir.path().join("exact.txt"), format!("{exact}\nnext")).expect("write");
|
||||
let result = ReadTool::new()
|
||||
.run(serde_json::json!({"path": "exact.txt"}), &test_context(dir.path()))
|
||||
.await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(
|
||||
text.starts_with(&format!("1: {exact}\n-- 1 more of 2 lines")),
|
||||
"{}",
|
||||
&text[text.len() - 100..]
|
||||
);
|
||||
}
|
||||
|
||||
/// An empty file is a fact, not a bad argument.
|
||||
#[tokio::test]
|
||||
async fn an_empty_file_is_not_an_error() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
std::fs::write(dir.path().join("empty.txt"), "").expect("write");
|
||||
let result = ReadTool::new()
|
||||
.run(serde_json::json!({"path": "empty.txt"}), &test_context(dir.path()))
|
||||
.await;
|
||||
|
||||
assert!(!result.is_error, "an empty file reads fine");
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("empty"), "{text}");
|
||||
assert!(!text.contains("offset"), "and never blames an offset the caller never sent: {text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_binary_file_says_it_is_binary() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
std::fs::write(dir.path().join("bin.dat"), [0u8, 159, 146, 150, 255]).expect("write");
|
||||
let result = ReadTool::new()
|
||||
.run(serde_json::json!({"path": "bin.dat"}), &test_context(dir.path()))
|
||||
.await;
|
||||
|
||||
assert!(result.is_error);
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("binary file"), "{text}");
|
||||
assert!(!text.contains("valid UTF-8"), "not the stream-decoder's words: {text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_offset_past_the_end_names_the_real_length() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
std::fs::write(dir.path().join("three.txt"), "a\nb\nc\n").expect("write");
|
||||
let result = ReadTool::new()
|
||||
.run(serde_json::json!({"path": "three.txt", "offset": 99}), &test_context(dir.path()))
|
||||
.await;
|
||||
|
||||
assert!(result.is_error);
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("99") && text.contains("3 lines"), "{text}");
|
||||
}
|
||||
390
crates/luxe-tools/src/screenshot.rs
Normal file
390
crates/luxe-tools/src/screenshot.rs
Normal file
@@ -0,0 +1,390 @@
|
||||
//! `screenshot` tool — cross-platform screen/window/URL capture for visual verification.
|
||||
//!
|
||||
//! Captures the screen, a region, a window, or a rendered URL to a PNG, then returns it inline
|
||||
//! (so vision-capable models can see it) alongside the saved path. Uses the platform's native
|
||||
//! capture tool (see `capture`) — no heavyweight capture crate — so the dependency surface and
|
||||
//! the supply-chain gate stay clean.
|
||||
|
||||
mod browser;
|
||||
mod capture;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use base64::Engine;
|
||||
use luxe_core::provider::ToolSchema;
|
||||
use luxe_core::{ContentBlock, Tool, ToolContext, ToolResultData};
|
||||
use std::path::PathBuf;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use capture::CaptureTarget;
|
||||
|
||||
/// The `screenshot` tool.
|
||||
#[derive(Default)]
|
||||
pub struct ScreenshotTool;
|
||||
|
||||
impl ScreenshotTool {
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for ScreenshotTool {
|
||||
fn name(&self) -> &str {
|
||||
"screenshot"
|
||||
}
|
||||
|
||||
/// `mode=url` hands a URL to a headless browser, and a browser told to load a host that never
|
||||
/// answers waits forever — `--virtual-time-budget` bounds the page's *clock*, not its network.
|
||||
/// The native capture backends are sub-second, so one network-shaped bound covers every mode.
|
||||
fn timeout(&self) -> Option<std::time::Duration> {
|
||||
Some(luxe_core::tool::NETWORK_TOOL_TIMEOUT)
|
||||
}
|
||||
|
||||
fn schema(&self) -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: "screenshot".to_string(),
|
||||
description: "Capture a screenshot and return it inline (for visual UI verification) \
|
||||
plus save it to .luxe/screenshots/. Cross-platform via the OS's native \
|
||||
tool (Wayland/grim, X11/maim|scrot, macOS/screencapture, Windows/\
|
||||
PowerShell); mode=url renders a page in headless Chrome/Chromium/Edge — \
|
||||
the best way to check a web UI or dev-server output. Params by mode: \
|
||||
fullscreen{output?}; region{region:\"X,Y WxH\"}; window{window?:title \
|
||||
substring}; url{url, width?, height?, waitMs?}. `note` is echoed back.\n\
|
||||
mode=url reaches public sites and this machine — localhost, 127.0.0.1 and \
|
||||
::1 all work with no setup, so capturing your dev server just works. It \
|
||||
refuses private-network hosts and cloud-metadata endpoints (reaching \
|
||||
those is not this tool's job), and refuses file:// (use `read` for file \
|
||||
contents). Only the requested host resolves: redirects, frames and \
|
||||
assets from any other host fail to load.\n\
|
||||
Prefer mode=url for anything web: it needs no desktop, no approval, and \
|
||||
shows only what the page drew. The other three photograph the reader's \
|
||||
actual screen, so they prompt for approval and are refused outright when \
|
||||
no one is at the keyboard (headless, the loop, a review agent)."
|
||||
.to_string(),
|
||||
parameters: serde_json::json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"enum": ["fullscreen", "region", "window", "url"],
|
||||
"description": "What to capture (default: url when a `url` is given, else fullscreen)"
|
||||
},
|
||||
"region": {
|
||||
"type": "string",
|
||||
"description": "region mode: capture rectangle as 'X,Y WxH', e.g. '0,0 1280x800'"
|
||||
},
|
||||
"window": {
|
||||
"type": "string",
|
||||
"description": "window mode: case-sensitive title substring; omit for the active window (Hyprland/X11 only)"
|
||||
},
|
||||
"url": {
|
||||
"type": "string",
|
||||
"description": "url mode: the http(s):// page to render and capture. Public or local (localhost/127.0.0.1/::1); private-network and cloud-metadata hosts are refused, and so is file://"
|
||||
},
|
||||
"output": {
|
||||
"type": "string",
|
||||
"description": "fullscreen mode: a specific monitor/output name (Wayland); omit for all"
|
||||
},
|
||||
"width": {
|
||||
"type": "integer",
|
||||
"description": "url mode: viewport width in px (default 1280)"
|
||||
},
|
||||
"height": {
|
||||
"type": "integer",
|
||||
"description": "url mode: viewport height in px (default 800)"
|
||||
},
|
||||
"waitMs": {
|
||||
"type": "integer",
|
||||
"description": "url mode: ms to let the page render before capture (default 1500)"
|
||||
},
|
||||
"note": {
|
||||
"type": "string",
|
||||
"description": "optional label echoed back with the result (what you're inspecting)"
|
||||
}
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(&self, args: serde_json::Value, cx: &ToolContext) -> ToolResultData {
|
||||
match self.capture(&args, cx).await {
|
||||
Ok(result) => result,
|
||||
Err(err) => ToolResultData::error(format!("Screenshot failed: {err:#}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ScreenshotTool {
|
||||
async fn capture(
|
||||
&self,
|
||||
args: &serde_json::Value,
|
||||
cx: &ToolContext,
|
||||
) -> anyhow::Result<ToolResultData> {
|
||||
let mode = luxe_core::permission::screenshot_mode(args);
|
||||
let note = args.get("note").and_then(|v| v.as_str());
|
||||
|
||||
// Photographing the desktop needs somebody at the keyboard. The permission engine makes it
|
||||
// an `ask`, and an `ask` auto-allows where nothing can prompt — which is precisely the run
|
||||
// that must not have it: a headless session or a loop iteration would capture a screen no
|
||||
// one is watching and send it to a provider. Same rule, and the same reasoning, as a
|
||||
// language server out of the project's own `node_modules`.
|
||||
if captures_the_desktop(mode) && cx.question_broker.is_none() {
|
||||
anyhow::bail!(
|
||||
"mode={mode} photographs the whole screen, so it runs only with someone at the \
|
||||
keyboard to approve it — this session has no way to ask. Use mode=url to capture \
|
||||
a page (a dev server, a local build), which needs no desktop and no approval."
|
||||
);
|
||||
}
|
||||
|
||||
let out_path = new_output_path(&cx.cwd)?;
|
||||
|
||||
let backend_label = if mode == "url" {
|
||||
"headless browser".to_string()
|
||||
} else {
|
||||
capture::backend_label(capture::detect_backend()).to_string()
|
||||
};
|
||||
|
||||
match mode {
|
||||
"url" => {
|
||||
let url = args
|
||||
.get("url")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("mode=url requires a `url`"))?;
|
||||
let width = args.get("width").and_then(|v| v.as_u64()).unwrap_or(1280) as u32;
|
||||
let height = args.get("height").and_then(|v| v.as_u64()).unwrap_or(800) as u32;
|
||||
let wait_ms = luxe_core::tool::arg(args, &["waitMs", "wait_ms"])
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(1500) as u32;
|
||||
browser::capture_url(url, (width, height), wait_ms, &out_path, &cx.cwd).await?;
|
||||
}
|
||||
"fullscreen" | "region" | "window" => {
|
||||
let target = build_target(mode, args)?;
|
||||
let backend = capture::detect_backend();
|
||||
capture::capture(backend, &target, &out_path).await?;
|
||||
}
|
||||
other => {
|
||||
anyhow::bail!("unknown mode '{other}' (use fullscreen | region | window | url)")
|
||||
}
|
||||
}
|
||||
|
||||
encode_result(&out_path, mode, &backend_label, note)
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the capture target for a screen-capture mode from the tool arguments.
|
||||
fn build_target(mode: &str, args: &serde_json::Value) -> anyhow::Result<CaptureTarget> {
|
||||
match mode {
|
||||
"fullscreen" => Ok(CaptureTarget::Fullscreen {
|
||||
output: args.get("output").and_then(|v| v.as_str()).map(str::to_string),
|
||||
}),
|
||||
"region" => {
|
||||
let geometry = args
|
||||
.get("region")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow::anyhow!("mode=region requires a `region` (\"X,Y WxH\")"))?;
|
||||
Ok(CaptureTarget::Region { geometry: geometry.to_string() })
|
||||
}
|
||||
"window" => Ok(CaptureTarget::Window {
|
||||
title: args.get("window").and_then(|v| v.as_str()).map(str::to_string),
|
||||
}),
|
||||
other => anyhow::bail!("unsupported capture mode '{other}'"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the captured PNG and packages it as an inline image plus a text summary.
|
||||
fn encode_result(
|
||||
out_path: &std::path::Path,
|
||||
mode: &str,
|
||||
backend_label: &str,
|
||||
note: Option<&str>,
|
||||
) -> anyhow::Result<ToolResultData> {
|
||||
let bytes = std::fs::read(out_path)
|
||||
.map_err(|err| anyhow::anyhow!("captured file could not be read: {err}"))?;
|
||||
if bytes.is_empty() {
|
||||
anyhow::bail!("capture produced an empty file");
|
||||
}
|
||||
// Keep the saved file full-resolution, but downscale the INLINE copy so a big multi-monitor
|
||||
// capture doesn't blow up token cost.
|
||||
let (inline_bytes, dimensions) = downscale_for_inline(&bytes);
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(&inline_bytes);
|
||||
let mut summary = format!(
|
||||
"Captured {mode} via {backend_label} ({dimensions}, {size} KB on disk). Saved: {path}",
|
||||
size = bytes.len() / 1024,
|
||||
path = luxe_core::paths::display(out_path)
|
||||
);
|
||||
if let Some(note) = note {
|
||||
summary.push_str(&format!("\nNote: {note}"));
|
||||
}
|
||||
Ok(ToolResultData {
|
||||
content: vec![
|
||||
ContentBlock::Text(summary),
|
||||
// The saved path travels with the pixels: a terminal that cannot draw the capture
|
||||
// offers to open it instead, and a model looking at three of them can tell them apart.
|
||||
ContentBlock::Image {
|
||||
data,
|
||||
mime: "image/png".to_string(),
|
||||
name: Some(luxe_core::paths::display(out_path)),
|
||||
},
|
||||
],
|
||||
is_error: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Longest edge (px) for the inline image sent to the model — keeps token cost sane while staying
|
||||
/// legible (Anthropic's recommended max long edge).
|
||||
const MAX_INLINE_DIM: u32 = 1568;
|
||||
|
||||
/// Returns the inline PNG bytes (downscaled if either side exceeds [`MAX_INLINE_DIM`]) plus a
|
||||
/// human-readable dimensions string. On any decode/encode failure, falls back to the original
|
||||
/// bytes so a capture is never lost to a resize hiccup.
|
||||
fn downscale_for_inline(bytes: &[u8]) -> (Vec<u8>, String) {
|
||||
let Ok(img) = image::load_from_memory(bytes) else {
|
||||
return (bytes.to_vec(), "unknown size".to_string());
|
||||
};
|
||||
let (w, h) = (img.width(), img.height());
|
||||
if w <= MAX_INLINE_DIM && h <= MAX_INLINE_DIM {
|
||||
return (bytes.to_vec(), format!("{w}x{h}"));
|
||||
}
|
||||
let resized = img.resize(MAX_INLINE_DIM, MAX_INLINE_DIM, image::imageops::FilterType::Triangle);
|
||||
let (nw, nh) = (resized.width(), resized.height());
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
match resized.write_to(&mut out, image::ImageFormat::Png) {
|
||||
Ok(()) => (out.into_inner(), format!("{w}x{h} → {nw}x{nh} inline")),
|
||||
Err(_) => (bytes.to_vec(), format!("{w}x{h}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Allocates a fresh `<cwd>/.luxe/screenshots/shot-<millis>.png`, creating the directory.
|
||||
fn new_output_path(cwd: &std::path::Path) -> anyhow::Result<PathBuf> {
|
||||
let dir = cwd.join(".luxe").join("screenshots");
|
||||
std::fs::create_dir_all(&dir)
|
||||
.map_err(|err| anyhow::anyhow!("could not create {}: {err}", dir.display()))?;
|
||||
let millis = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0);
|
||||
Ok(dir.join(format!("shot-{millis}.png")))
|
||||
}
|
||||
|
||||
/// Whether a screenshot could actually be taken here: a program that can photograph the desktop,
|
||||
/// or a headless browser for URL captures.
|
||||
///
|
||||
/// On a CI runner or an SSH session with neither, every call this tool could make ends in an
|
||||
/// install hint — so it is not worth a schema in every request. The desktop half asks for the
|
||||
/// *program*, not merely a display: see `capture::desktop_capture_available`.
|
||||
pub fn is_available() -> bool {
|
||||
capture::desktop_capture_available(capture::detect_backend()) || browser::is_available()
|
||||
}
|
||||
|
||||
/// Modes that photograph whatever is on the reader's screen, rather than a page Luxe rendered.
|
||||
///
|
||||
/// The distinction the permission engine and the unattended guard are both drawn on: `url` shows a
|
||||
/// model a document it asked Luxe to load, and these show it the desktop — a password manager, a
|
||||
/// private message, a colleague on a shared display.
|
||||
fn captures_the_desktop(mode: &str) -> bool {
|
||||
matches!(mode, "fullscreen" | "region" | "window")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tiny_png(w: u32, h: u32) -> Vec<u8> {
|
||||
let img = image::RgbaImage::from_pixel(w, h, image::Rgba([10, 20, 30, 255]));
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
image::DynamicImage::ImageRgba8(img).write_to(&mut out, image::ImageFormat::Png).unwrap();
|
||||
out.into_inner()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schema_exposes_four_modes() {
|
||||
let tool = ScreenshotTool::new();
|
||||
assert_eq!(tool.name(), "screenshot");
|
||||
let schema = tool.schema();
|
||||
let modes = schema.parameters["properties"]["mode"]["enum"].as_array().unwrap();
|
||||
assert_eq!(modes.len(), 4, "fullscreen/region/window/url");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn region_target_requires_geometry() {
|
||||
assert!(build_target("region", &serde_json::json!({})).is_err());
|
||||
assert!(build_target("region", &serde_json::json!({ "region": "0,0 8x6" })).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_images_pass_through_undownscaled() {
|
||||
let png = tiny_png(64, 48);
|
||||
let (bytes, dims) = downscale_for_inline(&png);
|
||||
assert_eq!(bytes, png);
|
||||
assert_eq!(dims, "64x48");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_images_are_downscaled_for_inline() {
|
||||
let png = tiny_png(3000, 1000);
|
||||
let (bytes, dims) = downscale_for_inline(&png);
|
||||
assert!(dims.contains('→'), "dims note should show the resize: {dims}");
|
||||
let img = image::load_from_memory(&bytes).unwrap();
|
||||
assert!(img.width() <= MAX_INLINE_DIM && img.height() <= MAX_INLINE_DIM);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_path_creates_the_screenshots_dir() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = new_output_path(tmp.path()).unwrap();
|
||||
assert!(path.parent().unwrap().is_dir());
|
||||
assert!(path.to_string_lossy().ends_with(".png"));
|
||||
}
|
||||
|
||||
/// Availability is a real capability question, and the answer is a *program*: a display is not
|
||||
/// a screenshot tool. Wayland and X11 ship neither, so a desktop without `grim` must not
|
||||
/// advertise this tool and then fail every capture with an install hint.
|
||||
#[test]
|
||||
fn availability_tracks_a_capture_program_or_a_browser() {
|
||||
let can_capture = capture::desktop_capture_available(capture::detect_backend());
|
||||
assert_eq!(is_available(), can_capture || browser::is_available());
|
||||
}
|
||||
|
||||
/// A display with nothing installed to photograph it is not availability.
|
||||
#[test]
|
||||
fn a_bare_display_server_provides_no_capture() {
|
||||
use capture::{desktop_capture_available, DisplayBackend};
|
||||
// The two that carry their capture tool in the OS, and the one that carries nothing.
|
||||
assert!(desktop_capture_available(DisplayBackend::MacOS));
|
||||
assert!(desktop_capture_available(DisplayBackend::Windows));
|
||||
assert!(!desktop_capture_available(DisplayBackend::Unknown));
|
||||
}
|
||||
|
||||
/// The desktop modes are the ones that need a human; `url` renders a page and needs nobody.
|
||||
#[test]
|
||||
fn only_the_desktop_modes_photograph_the_reader() {
|
||||
for mode in ["fullscreen", "region", "window"] {
|
||||
assert!(captures_the_desktop(mode), "{mode}");
|
||||
}
|
||||
assert!(!captures_the_desktop("url"));
|
||||
}
|
||||
|
||||
/// An unattended run refuses rather than capturing: an `ask` auto-allows where nothing can
|
||||
/// prompt, which is exactly the session that must not photograph a screen nobody is watching.
|
||||
/// The refusal names `mode=url`, because that is the one that still works there.
|
||||
#[tokio::test]
|
||||
async fn an_unattended_run_refuses_to_photograph_the_screen() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (event_tx, _rx) = tokio::sync::mpsc::channel(8);
|
||||
let (_cancel, cancel_rx) = tokio::sync::watch::channel(false);
|
||||
let cx = ToolContext {
|
||||
cwd: tmp.path().to_path_buf(),
|
||||
session_id: "s".into(),
|
||||
cancelled: std::sync::Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
// The signal itself: `None` is "no front-end can ask a human anything".
|
||||
question_broker: None,
|
||||
};
|
||||
|
||||
let result =
|
||||
ScreenshotTool::new().run(serde_json::json!({"mode": "fullscreen"}), &cx).await;
|
||||
|
||||
assert!(result.is_error, "an unattended desktop capture must not proceed");
|
||||
let ContentBlock::Text(message) = &result.content[0] else { panic!("a text refusal") };
|
||||
assert!(message.contains("someone at the keyboard"), "says why: {message}");
|
||||
assert!(message.contains("mode=url"), "and what does work instead: {message}");
|
||||
}
|
||||
}
|
||||
352
crates/luxe-tools/src/screenshot/browser.rs
Normal file
352
crates/luxe-tools/src/screenshot/browser.rs
Normal file
@@ -0,0 +1,352 @@
|
||||
//! Headless-browser capture for `mode=url` — renders a page (e.g. a local dev server) to PNG.
|
||||
//!
|
||||
//! Shells out to a headless Chrome/Chromium/Edge rather than embedding a CDP client, matching the
|
||||
//! native-tools philosophy of the rest of the screenshot backend.
|
||||
//!
|
||||
//! Model-supplied URLs are untrusted, so `mode=url` reuses the same [`crate::ssrf`] guard as
|
||||
//! `web_fetch`: private-network and cloud-metadata hosts are refused, `file://` is refused, and
|
||||
//! Chrome's own DNS is pinned to the address we validated so a rebind can't slip a different one past
|
||||
//! the check. **Loopback is allowed**, because capturing a dev server on this machine is the reason
|
||||
//! URL mode exists — see [`crate::ssrf`] for why that costs nothing next to an unrestricted `bash`.
|
||||
//! `LUXE_WEB_ALLOW_PRIVATE=1` remains the opt-out for a LAN host or a `file://` capture.
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use std::path::Path;
|
||||
use tokio::process::Command;
|
||||
|
||||
use super::capture::which;
|
||||
|
||||
/// Renders `url` at `width`x`height`, waiting `wait_ms` for it to settle, into the PNG at `out`.
|
||||
///
|
||||
/// Chrome runs on a throwaway profile under `<cwd>/.luxe/browser/`, removed afterwards, so a page
|
||||
/// never sees the user's cookies or a previous capture's.
|
||||
pub(super) async fn capture_url(
|
||||
url: &str,
|
||||
size: (u32, u32),
|
||||
wait_ms: u32,
|
||||
out: &Path,
|
||||
cwd: &Path,
|
||||
) -> Result<()> {
|
||||
let resolver_rule = validate_capture_url(url).await?;
|
||||
let browser = find_browser()
|
||||
.ok_or_else(|| anyhow!("no headless browser found (install Chrome, Chromium, or Edge)"))?;
|
||||
let out = out.to_str().ok_or_else(|| anyhow!("output path is not valid UTF-8"))?;
|
||||
let profile = Profile::create(cwd)?;
|
||||
let capture = ChromeCapture {
|
||||
url,
|
||||
width: size.0,
|
||||
height: size.1,
|
||||
wait_ms,
|
||||
out,
|
||||
resolver_rule,
|
||||
sandboxed: !sandbox_unavailable(
|
||||
luxe_core::isolation::running_as_root(),
|
||||
luxe_core::isolation::in_container(),
|
||||
),
|
||||
profile: &profile.0,
|
||||
};
|
||||
// `kill_on_drop` is what makes the engine's deadline and the user's interrupt actually reach
|
||||
// Chrome. Dropping this future is how a stopped tool call unwinds, and a browser aimed at a host
|
||||
// that accepts the connection and then answers nothing will otherwise sit there for the rest of
|
||||
// the session: `--virtual-time-budget` bounds the page's clock, not its network.
|
||||
let output = Command::new(&browser)
|
||||
.args(chrome_args(&capture))
|
||||
.kill_on_drop(true)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.output()
|
||||
.await
|
||||
.with_context(|| format!("failed to run headless browser `{browser}`"))?;
|
||||
// Chrome exits 0 on a successful screenshot; some builds print to stderr even on success, so
|
||||
// fall back to checking the file was actually written.
|
||||
if !output.status.success() && !out_written(out) {
|
||||
bail!("headless `{browser}` failed: {}", String::from_utf8_lossy(&output.stderr).trim());
|
||||
}
|
||||
if !out_written(out) {
|
||||
bail!("headless `{browser}` produced no screenshot for {url}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Everything Chrome is told for one capture, apart so the flags are testable without a browser.
|
||||
struct ChromeCapture<'a> {
|
||||
url: &'a str,
|
||||
width: u32,
|
||||
height: u32,
|
||||
wait_ms: u32,
|
||||
out: &'a str,
|
||||
resolver_rule: Option<String>,
|
||||
sandboxed: bool,
|
||||
profile: &'a Path,
|
||||
}
|
||||
|
||||
fn chrome_args(capture: &ChromeCapture<'_>) -> Vec<String> {
|
||||
let mut args = vec![
|
||||
"--headless=new".to_string(),
|
||||
"--disable-gpu".to_string(),
|
||||
"--hide-scrollbars".to_string(),
|
||||
"--force-device-scale-factor=1".to_string(),
|
||||
format!("--user-data-dir={}", capture.profile.display()),
|
||||
format!("--window-size={},{}", capture.width, capture.height),
|
||||
format!("--virtual-time-budget={}", capture.wait_ms),
|
||||
format!("--screenshot={}", capture.out),
|
||||
];
|
||||
// a container workaround, not a default: the sandbox is what stands between a hostile page and
|
||||
// the user's desktop
|
||||
if !capture.sandboxed {
|
||||
args.push("--no-sandbox".to_string());
|
||||
}
|
||||
if let Some(rule) = &capture.resolver_rule {
|
||||
args.push(format!("--host-resolver-rules={rule}"));
|
||||
}
|
||||
args.push(capture.url.to_string());
|
||||
args
|
||||
}
|
||||
|
||||
/// A fresh browser profile directory, removed when the capture is done.
|
||||
struct Profile(std::path::PathBuf);
|
||||
|
||||
impl Profile {
|
||||
fn create(cwd: &Path) -> Result<Self> {
|
||||
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let stamp = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|elapsed| elapsed.as_nanos())
|
||||
.unwrap_or_default();
|
||||
let next = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let name = format!("profile-{}-{stamp}-{next}", std::process::id());
|
||||
let dir = cwd.join(".luxe").join("browser").join(name);
|
||||
std::fs::create_dir_all(&dir)
|
||||
.with_context(|| format!("could not create {}", dir.display()))?;
|
||||
Ok(Self(dir))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Profile {
|
||||
fn drop(&mut self) {
|
||||
if let Err(error) = std::fs::remove_dir_all(&self.0) {
|
||||
tracing::warn!(%error, profile = %self.0.display(), "could not remove a browser profile");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether Chrome's sandbox cannot start here: as root, or inside a container.
|
||||
fn sandbox_unavailable(root: bool, in_container: bool) -> bool {
|
||||
root || in_container
|
||||
}
|
||||
|
||||
fn out_written(out: &str) -> bool {
|
||||
std::fs::metadata(out).map(|meta| meta.len() > 0).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Validates a `mode=url` target against the SSRF guard and returns the Chrome
|
||||
/// `--host-resolver-rules` value ([`resolver_rule`]) that keeps the capture on that host.
|
||||
///
|
||||
/// Public and loopback origins pass; private-network and metadata hosts are refused, as is `file://`.
|
||||
/// When the guard is disabled wholesale we return `None` (no pinning) so an intentional LAN or file
|
||||
/// capture still works.
|
||||
async fn validate_capture_url(url: &str) -> Result<Option<String>> {
|
||||
if url.starts_with("file://") {
|
||||
if crate::ssrf::guard_disabled() {
|
||||
return Ok(None);
|
||||
}
|
||||
// Not a network fetch at all: this would hand a model-supplied path to a browser with the
|
||||
// whole filesystem in reach, which `read` already does properly, scoped to the project.
|
||||
bail!(
|
||||
"file:// captures are blocked: a browser given a local path can read anything this user \
|
||||
can. Use `read` for file contents, or serve the file over http:// and capture that. \
|
||||
LUXE_WEB_ALLOW_PRIVATE=1 overrides this."
|
||||
);
|
||||
}
|
||||
if !(url.starts_with("http://") || url.starts_with("https://")) {
|
||||
bail!("url must start with http:// or https:// (got '{url}')");
|
||||
}
|
||||
if crate::ssrf::guard_disabled() {
|
||||
return Ok(None);
|
||||
}
|
||||
let parsed = url::Url::parse(url).map_err(|e| anyhow!("invalid URL: {e}"))?;
|
||||
// Loopback allowed: a local dev server is what this mode is for.
|
||||
let addrs = crate::ssrf::resolve_validated(&parsed, crate::ssrf::LocalAccess::Allowed)
|
||||
.await
|
||||
.map_err(|e| anyhow!("{e}"))?;
|
||||
Ok(resolver_rule(&parsed, &addrs))
|
||||
}
|
||||
|
||||
/// The Chrome resolver rule for a capture of `url`: only its host resolves, so a page cannot
|
||||
/// redirect to or embed another one. The rule covers IP-literal hosts too: checked by hand against
|
||||
/// Chromium, an image at `http://127.0.0.1:<port>/` on a `localhost` page did not load under
|
||||
/// `MAP * ~NOTFOUND , EXCLUDE localhost`, and did without it.
|
||||
///
|
||||
/// A public name is pinned to the address that was checked, closing the rebinding gap. A loopback
|
||||
/// name is not pinned: Chrome's MAP takes one address, and choosing between `::1` and `127.0.0.1`
|
||||
/// on the user's behalf is how a dev server listening on the other one becomes unreachable.
|
||||
fn resolver_rule(url: &url::Url, addrs: &[std::net::SocketAddr]) -> Option<String> {
|
||||
let host = match url.host()? {
|
||||
url::Host::Domain(name) if !addrs.iter().all(|addr| addr.ip().is_loopback()) => {
|
||||
let addr = addrs.first()?;
|
||||
// bracketed, so an IPv6 replacement can never be read as host:port
|
||||
let ip = match addr.ip() {
|
||||
std::net::IpAddr::V6(ip) => format!("[{ip}]"),
|
||||
ip => ip.to_string(),
|
||||
};
|
||||
return Some(format!("MAP {name} {ip} , MAP * ~NOTFOUND"));
|
||||
}
|
||||
url::Host::Domain(name) => name.to_string(),
|
||||
url::Host::Ipv4(ip) => ip.to_string(),
|
||||
// bare, not bracketed: Chrome's EXCLUDE does not match `[::1]`
|
||||
url::Host::Ipv6(ip) => ip.to_string(),
|
||||
};
|
||||
Some(format!("MAP * ~NOTFOUND , EXCLUDE {host}"))
|
||||
}
|
||||
|
||||
/// Whether a headless browser is installed, for URL captures without a display.
|
||||
pub(super) fn is_available() -> bool {
|
||||
find_browser().is_some()
|
||||
}
|
||||
|
||||
/// Finds a headless-capable browser: PATH candidates first, then well-known OS install locations.
|
||||
fn find_browser() -> Option<String> {
|
||||
const CANDIDATES: &[&str] = &[
|
||||
"chromium",
|
||||
"chromium-browser",
|
||||
"google-chrome",
|
||||
"google-chrome-stable",
|
||||
"microsoft-edge",
|
||||
"brave",
|
||||
"brave-browser",
|
||||
];
|
||||
for candidate in CANDIDATES {
|
||||
if which(candidate) {
|
||||
return Some((*candidate).to_string());
|
||||
}
|
||||
}
|
||||
for path in well_known_paths() {
|
||||
if Path::new(path).is_file() {
|
||||
return Some(path.to_string());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn well_known_paths() -> &'static [&'static str] {
|
||||
if cfg!(target_os = "macos") {
|
||||
&[
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
||||
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
||||
]
|
||||
} else if cfg!(target_os = "windows") {
|
||||
&[
|
||||
r"C:\Program Files\Google\Chrome\Application\chrome.exe",
|
||||
r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
|
||||
r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
|
||||
]
|
||||
} else {
|
||||
&["/usr/bin/chromium", "/usr/bin/google-chrome", "/snap/bin/chromium"]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// These assume LUXE_WEB_ALLOW_PRIVATE is unset (the default, and the CI environment).
|
||||
#[tokio::test]
|
||||
async fn blocks_file_scheme_by_default() {
|
||||
let err = validate_capture_url("file:///etc/passwd").await.unwrap_err().to_string();
|
||||
assert!(err.contains("file://"), "file:// must be refused: {err}");
|
||||
assert!(err.contains("`read`"), "and point at the tool that does this properly: {err}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_non_web_scheme() {
|
||||
assert!(validate_capture_url("ftp://example.com/x").await.is_err());
|
||||
assert!(validate_capture_url("data:text/html,hi").await.is_err());
|
||||
}
|
||||
|
||||
/// The capture this tool advertises: a dev server on this machine, with no env var set first and
|
||||
/// no session already running that could have inherited one. Every spelling a dev server prints,
|
||||
/// including the bracketed IPv6 literal Vite and Astro report.
|
||||
#[tokio::test]
|
||||
async fn captures_a_local_dev_server() {
|
||||
for url in ["http://127.0.0.1:4321/", "http://localhost:4321/", "http://[::1]:4321/"] {
|
||||
validate_capture_url(url)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("{url} must be capturable: {error:#}"));
|
||||
}
|
||||
// Nothing local is pinned: Chrome's MAP takes one address, and choosing between `::1` and
|
||||
// `127.0.0.1` on the user's behalf is how a dev server on the other one becomes unreachable.
|
||||
// Every other name is unresolvable, so the page cannot pull in another host.
|
||||
for (url, host) in [
|
||||
("http://localhost:4321/", "localhost"),
|
||||
("http://127.0.0.1:4321/", "127.0.0.1"),
|
||||
("http://[::1]:4321/", "::1"),
|
||||
] {
|
||||
let rule = validate_capture_url(url).await.unwrap();
|
||||
assert_eq!(
|
||||
rule.as_deref(),
|
||||
Some(&*format!("MAP * ~NOTFOUND , EXCLUDE {host}")),
|
||||
"{url}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn blocks_private_and_metadata_hosts() {
|
||||
assert!(validate_capture_url("http://192.168.0.5/admin").await.is_err());
|
||||
assert!(validate_capture_url("http://10.0.0.1/").await.is_err());
|
||||
assert!(validate_capture_url("http://169.254.169.254/latest/meta-data").await.is_err());
|
||||
}
|
||||
|
||||
/// A public *IP literal* needs no pin — there is no lookup between us and Chrome to rebind. A
|
||||
/// `MAP 1.1.1.1 1.1.1.1` rule would map a host Chrome never resolves.
|
||||
#[tokio::test]
|
||||
async fn a_public_ip_literal_needs_no_resolver_pin() {
|
||||
let rule = validate_capture_url("http://1.1.1.1/").await.unwrap();
|
||||
assert_eq!(rule.as_deref(), Some("MAP * ~NOTFOUND , EXCLUDE 1.1.1.1"));
|
||||
}
|
||||
|
||||
/// A pinned public name resolves to the address that was checked, and nothing else resolves:
|
||||
/// a page that redirects to or embeds the metadata endpoint or a LAN host gets no answer.
|
||||
#[test]
|
||||
fn a_pinned_name_is_the_only_one_that_resolves() {
|
||||
let addr = "93.184.216.34:443".parse().unwrap();
|
||||
let rule = resolver_rule(&url::Url::parse("https://example.com/").unwrap(), &[addr]);
|
||||
assert_eq!(rule.as_deref(), Some("MAP example.com 93.184.216.34 , MAP * ~NOTFOUND"));
|
||||
// an IPv6 replacement is bracketed, or Chrome cannot tell its colons from a port
|
||||
let addr = "[2606:2800:220:1::1]:443".parse().unwrap();
|
||||
let rule = resolver_rule(&url::Url::parse("https://example.com/").unwrap(), &[addr]);
|
||||
assert_eq!(rule.as_deref(), Some("MAP example.com [2606:2800:220:1::1] , MAP * ~NOTFOUND"));
|
||||
}
|
||||
|
||||
/// The flags Chrome gets: a throwaway profile, the resolver rule, and `--no-sandbox` only where
|
||||
/// the sandbox cannot run.
|
||||
#[test]
|
||||
fn chrome_args_carry_the_profile_the_rule_and_the_sandbox_choice() {
|
||||
let profile = std::path::Path::new("/project/.luxe/browser/profile-1");
|
||||
let capture = ChromeCapture {
|
||||
url: "http://localhost:4321/",
|
||||
width: 800,
|
||||
height: 600,
|
||||
wait_ms: 500,
|
||||
out: "/project/.luxe/screenshots/shot.png",
|
||||
resolver_rule: Some("MAP * ~NOTFOUND , EXCLUDE localhost".into()),
|
||||
sandboxed: true,
|
||||
profile,
|
||||
};
|
||||
let args = chrome_args(&capture);
|
||||
assert!(args.contains(&"--user-data-dir=/project/.luxe/browser/profile-1".to_string()));
|
||||
assert!(args.contains(&"--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE localhost".into()));
|
||||
assert!(!args.contains(&"--no-sandbox".to_string()), "{args:?}");
|
||||
assert_eq!(args.last().map(String::as_str), Some("http://localhost:4321/"));
|
||||
let unsandboxed = chrome_args(&ChromeCapture { sandboxed: false, ..capture });
|
||||
assert!(unsandboxed.contains(&"--no-sandbox".to_string()), "{unsandboxed:?}");
|
||||
}
|
||||
|
||||
/// Root and containers are where Chrome's sandbox cannot start; everywhere else it stays on.
|
||||
#[test]
|
||||
fn the_sandbox_is_dropped_only_where_it_cannot_run() {
|
||||
assert!(sandbox_unavailable(true, false));
|
||||
assert!(sandbox_unavailable(false, true));
|
||||
assert!(!sandbox_unavailable(false, false));
|
||||
}
|
||||
}
|
||||
460
crates/luxe-tools/src/screenshot/capture.rs
Normal file
460
crates/luxe-tools/src/screenshot/capture.rs
Normal file
@@ -0,0 +1,460 @@
|
||||
//! Native screen capture — OS/display-server detection and per-platform capture commands.
|
||||
//!
|
||||
//! Shells out to the platform's native tool rather than linking a capture crate, keeping the
|
||||
//! dependency surface tiny and the gate clean: grim (+ hyprctl) on Wayland, maim/scrot/ImageMagick
|
||||
//! on X11, `screencapture` on macOS, and PowerShell + System.Drawing on Windows. Each writes a PNG
|
||||
//! that the tool then reads and returns inline.
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use std::path::Path;
|
||||
use tokio::process::Command;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum DisplayBackend {
|
||||
/// Wayland compositor that is Hyprland (window geometry via `hyprctl`).
|
||||
WaylandHyprland,
|
||||
/// Any other wlroots-ish Wayland compositor (grim works; per-window needs help).
|
||||
Wayland,
|
||||
/// X11 (maim/scrot/import).
|
||||
X11,
|
||||
/// macOS (`screencapture`).
|
||||
MacOS,
|
||||
/// Windows (PowerShell + System.Drawing).
|
||||
Windows,
|
||||
/// Nothing usable detected.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
pub(super) enum CaptureTarget {
|
||||
/// The whole screen, optionally a single named output/monitor.
|
||||
Fullscreen { output: Option<String> },
|
||||
/// An explicit region, given as `"X,Y WxH"`.
|
||||
Region { geometry: String },
|
||||
/// A window matched by title substring, or the active window when `None`.
|
||||
Window { title: Option<String> },
|
||||
}
|
||||
|
||||
/// Detects the display backend from the environment and target OS.
|
||||
pub(super) fn detect_backend() -> DisplayBackend {
|
||||
if cfg!(target_os = "macos") {
|
||||
return DisplayBackend::MacOS;
|
||||
}
|
||||
if cfg!(target_os = "windows") {
|
||||
return DisplayBackend::Windows;
|
||||
}
|
||||
let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some();
|
||||
let hyprland = std::env::var_os("HYPRLAND_INSTANCE_SIGNATURE").is_some();
|
||||
if wayland {
|
||||
if hyprland {
|
||||
DisplayBackend::WaylandHyprland
|
||||
} else {
|
||||
DisplayBackend::Wayland
|
||||
}
|
||||
} else if std::env::var_os("DISPLAY").is_some() {
|
||||
DisplayBackend::X11
|
||||
} else {
|
||||
DisplayBackend::Unknown
|
||||
}
|
||||
}
|
||||
|
||||
/// Human-readable name for error messages.
|
||||
pub(super) fn backend_label(backend: DisplayBackend) -> &'static str {
|
||||
match backend {
|
||||
DisplayBackend::WaylandHyprland => "Wayland (Hyprland)",
|
||||
DisplayBackend::Wayland => "Wayland",
|
||||
DisplayBackend::X11 => "X11",
|
||||
DisplayBackend::MacOS => "macOS",
|
||||
DisplayBackend::Windows => "Windows",
|
||||
DisplayBackend::Unknown => "unknown display server",
|
||||
}
|
||||
}
|
||||
|
||||
/// A parsed pixel rectangle.
|
||||
struct Rect {
|
||||
x: i64,
|
||||
y: i64,
|
||||
w: i64,
|
||||
h: i64,
|
||||
}
|
||||
|
||||
/// Parses a `"X,Y WxH"` geometry string (the same shape grim accepts).
|
||||
fn parse_geometry(geometry: &str) -> Result<Rect> {
|
||||
let (pos, size) = geometry
|
||||
.split_once(' ')
|
||||
.ok_or_else(|| anyhow!("geometry must look like 'X,Y WxH', got '{geometry}'"))?;
|
||||
let (x, y) = pos.split_once(',').ok_or_else(|| anyhow!("bad position in '{geometry}'"))?;
|
||||
let (w, h) = size
|
||||
.split_once(['x', 'X'])
|
||||
.ok_or_else(|| anyhow!("bad size in '{geometry}' (want WxH)"))?;
|
||||
let parse = |v: &str, what: &str| {
|
||||
v.trim().parse::<i64>().with_context(|| format!("invalid {what} in geometry '{geometry}'"))
|
||||
};
|
||||
Ok(Rect { x: parse(x, "x")?, y: parse(y, "y")?, w: parse(w, "width")?, h: parse(h, "height")? })
|
||||
}
|
||||
|
||||
/// Whether this backend has a program that can actually take the picture.
|
||||
///
|
||||
/// A display is not a capture tool. `detect_backend` answers on the strength of `$WAYLAND_DISPLAY`
|
||||
/// or `$DISPLAY` alone, and neither Wayland nor X11 ships a screenshot binary — so a box with a
|
||||
/// desktop and no `grim` must not advertise `screenshot` to the model and then fail every desktop
|
||||
/// capture with "install `grim`". macOS and Windows carry theirs in the OS.
|
||||
pub(super) fn desktop_capture_available(backend: DisplayBackend) -> bool {
|
||||
match backend {
|
||||
DisplayBackend::WaylandHyprland | DisplayBackend::Wayland => which("grim"),
|
||||
DisplayBackend::X11 => which("maim") || which("scrot") || which("import"),
|
||||
// `screencapture` and PowerShell ship with the OS.
|
||||
DisplayBackend::MacOS | DisplayBackend::Windows => true,
|
||||
DisplayBackend::Unknown => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Captures `target` to the PNG file at `out`, routing to the backend's native tool.
|
||||
pub(super) async fn capture(
|
||||
backend: DisplayBackend,
|
||||
target: &CaptureTarget,
|
||||
out: &Path,
|
||||
) -> Result<()> {
|
||||
match backend {
|
||||
DisplayBackend::WaylandHyprland | DisplayBackend::Wayland => {
|
||||
capture_wayland(backend, target, out).await
|
||||
}
|
||||
DisplayBackend::X11 => capture_x11(target, out).await,
|
||||
DisplayBackend::MacOS => capture_macos(target, out).await,
|
||||
DisplayBackend::Windows => capture_windows(target, out).await,
|
||||
DisplayBackend::Unknown => bail!(
|
||||
"no supported display server detected (neither $WAYLAND_DISPLAY nor $DISPLAY is set)"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// === Wayland (grim + hyprctl) ===
|
||||
|
||||
async fn capture_wayland(
|
||||
backend: DisplayBackend,
|
||||
target: &CaptureTarget,
|
||||
out: &Path,
|
||||
) -> Result<()> {
|
||||
require("grim", "install `grim` (and `slurp` for interactive regions)")?;
|
||||
let out = path_str(out)?;
|
||||
match target {
|
||||
CaptureTarget::Fullscreen { output } => {
|
||||
let mut args: Vec<String> = Vec::new();
|
||||
if let Some(name) = output {
|
||||
args.push("-o".into());
|
||||
args.push(name.clone());
|
||||
}
|
||||
args.push(out);
|
||||
run("grim", &args).await
|
||||
}
|
||||
CaptureTarget::Region { geometry } => {
|
||||
// grim consumes the "X,Y WxH" shape directly; validate it first for a clear error.
|
||||
parse_geometry(geometry)?;
|
||||
run("grim", &["-g".into(), geometry.clone(), out]).await
|
||||
}
|
||||
CaptureTarget::Window { title } => {
|
||||
if backend != DisplayBackend::WaylandHyprland {
|
||||
bail!(
|
||||
"per-window capture on Wayland is only supported under Hyprland; \
|
||||
use mode=region with an explicit geometry instead"
|
||||
);
|
||||
}
|
||||
let geometry = hyprland_window_geometry(title.as_deref()).await?;
|
||||
run("grim", &["-g".into(), geometry, out]).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a window's `X,Y WxH` geometry from `hyprctl` (active window, or the first title match).
|
||||
async fn hyprland_window_geometry(title: Option<&str>) -> Result<String> {
|
||||
let query = if title.is_some() { "clients" } else { "activewindow" };
|
||||
let output = Command::new("hyprctl")
|
||||
.args(["-j", query])
|
||||
.kill_on_drop(true)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.output()
|
||||
.await
|
||||
.context("failed to run `hyprctl` for window geometry")?;
|
||||
if !output.status.success() {
|
||||
bail!("`hyprctl -j {query}` failed: {}", String::from_utf8_lossy(&output.stderr).trim());
|
||||
}
|
||||
let json: serde_json::Value =
|
||||
serde_json::from_slice(&output.stdout).context("could not parse hyprctl JSON")?;
|
||||
let window = match title {
|
||||
Some(needle) => json
|
||||
.as_array()
|
||||
.and_then(|clients| {
|
||||
clients
|
||||
.iter()
|
||||
.find(|client| client["title"].as_str().is_some_and(|t| t.contains(needle)))
|
||||
})
|
||||
.ok_or_else(|| anyhow!("no Hyprland window whose title contains '{needle}'"))?,
|
||||
None => &json,
|
||||
};
|
||||
let at = &window["at"];
|
||||
let size = &window["size"];
|
||||
let field = |value: &serde_json::Value, index: usize| -> Result<i64> {
|
||||
value[index].as_i64().ok_or_else(|| anyhow!("hyprctl returned no window geometry"))
|
||||
};
|
||||
Ok(format!("{},{} {}x{}", field(at, 0)?, field(at, 1)?, field(size, 0)?, field(size, 1)?))
|
||||
}
|
||||
|
||||
// === X11 (maim / scrot / ImageMagick import) ===
|
||||
|
||||
async fn capture_x11(target: &CaptureTarget, out: &Path) -> Result<()> {
|
||||
let out = path_str(out)?;
|
||||
match target {
|
||||
CaptureTarget::Fullscreen { .. } => {
|
||||
try_candidates(
|
||||
&[
|
||||
("maim", vec![out.clone()]),
|
||||
("scrot", vec!["-o".into(), out.clone()]),
|
||||
("import", vec!["-window".into(), "root".into(), out.clone()]),
|
||||
],
|
||||
"install one of: maim, scrot, or ImageMagick (`import`)",
|
||||
)
|
||||
.await
|
||||
}
|
||||
CaptureTarget::Region { geometry } => {
|
||||
let r = parse_geometry(geometry)?;
|
||||
let maim_geo = format!("{}x{}+{}+{}", r.w, r.h, r.x, r.y);
|
||||
let scrot_geo = format!("{},{},{},{}", r.x, r.y, r.w, r.h);
|
||||
let crop = format!("{}x{}+{}+{}", r.w, r.h, r.x, r.y);
|
||||
try_candidates(
|
||||
&[
|
||||
("maim", vec!["-g".into(), maim_geo, out.clone()]),
|
||||
("scrot", vec!["-a".into(), scrot_geo, "-o".into(), out.clone()]),
|
||||
(
|
||||
"import",
|
||||
vec!["-window".into(), "root".into(), "-crop".into(), crop, out.clone()],
|
||||
),
|
||||
],
|
||||
"install one of: maim, scrot, or ImageMagick (`import`)",
|
||||
)
|
||||
.await
|
||||
}
|
||||
CaptureTarget::Window { title } => {
|
||||
let id = x11_window_id(title.as_deref()).await?;
|
||||
try_candidates(
|
||||
&[
|
||||
("maim", vec!["-i".into(), id.clone(), out.clone()]),
|
||||
("import", vec!["-window".into(), id, out.clone()]),
|
||||
],
|
||||
"install `maim` (with `xdotool`) or ImageMagick (`import`)",
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves an X11 window id (hex) via `xdotool`, by title or the active window.
|
||||
async fn x11_window_id(title: Option<&str>) -> Result<String> {
|
||||
require("xdotool", "install `xdotool` for per-window X11 capture")?;
|
||||
let args: Vec<&str> = match title {
|
||||
Some(needle) => vec!["search", "--name", "--limit", "1", needle],
|
||||
None => vec!["getactivewindow"],
|
||||
};
|
||||
let output = Command::new("xdotool")
|
||||
.args(&args)
|
||||
.kill_on_drop(true)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.output()
|
||||
.await
|
||||
.context("failed to run xdotool")?;
|
||||
if !output.status.success() {
|
||||
bail!("xdotool could not resolve the window (title match failed?)");
|
||||
}
|
||||
let id =
|
||||
String::from_utf8_lossy(&output.stdout).trim().lines().next().unwrap_or("").to_string();
|
||||
if id.is_empty() {
|
||||
bail!("no matching X11 window found");
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
// === macOS (screencapture) ===
|
||||
|
||||
async fn capture_macos(target: &CaptureTarget, out: &Path) -> Result<()> {
|
||||
let out = path_str(out)?;
|
||||
match target {
|
||||
CaptureTarget::Fullscreen { .. } => run("screencapture", &["-x".into(), out]).await,
|
||||
CaptureTarget::Region { geometry } => {
|
||||
let r = parse_geometry(geometry)?;
|
||||
let rect = format!("{},{},{},{}", r.x, r.y, r.w, r.h);
|
||||
run("screencapture", &["-x".into(), "-R".into(), rect, out]).await
|
||||
}
|
||||
CaptureTarget::Window { .. } => bail!(
|
||||
"per-window capture on macOS needs a window id; use mode=fullscreen or mode=region"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// === Windows (PowerShell + System.Drawing) ===
|
||||
|
||||
async fn capture_windows(target: &CaptureTarget, out: &Path) -> Result<()> {
|
||||
let out = path_str(out)?;
|
||||
let script = match target {
|
||||
CaptureTarget::Fullscreen { .. } => windows_capture_script("virtual", &out),
|
||||
CaptureTarget::Region { geometry } => {
|
||||
let r = parse_geometry(geometry)?;
|
||||
windows_capture_script(&format!("{},{},{},{}", r.x, r.y, r.w, r.h), &out)
|
||||
}
|
||||
CaptureTarget::Window { .. } => bail!(
|
||||
"per-window capture on Windows is not supported yet; use mode=fullscreen or mode=region"
|
||||
),
|
||||
};
|
||||
run("powershell", &["-NoProfile".into(), "-NonInteractive".into(), "-Command".into(), script])
|
||||
.await
|
||||
}
|
||||
|
||||
/// Builds a PowerShell one-liner that captures the virtual screen (or `x,y,w,h`) to `out`.
|
||||
fn windows_capture_script(rect: &str, out: &str) -> String {
|
||||
let bounds = if rect == "virtual" {
|
||||
"$r=[System.Windows.Forms.SystemInformation]::VirtualScreen".to_string()
|
||||
} else {
|
||||
let parts: Vec<&str> = rect.split(',').collect();
|
||||
format!(
|
||||
"$r=New-Object System.Drawing.Rectangle({},{},{},{})",
|
||||
parts.first().unwrap_or(&"0"),
|
||||
parts.get(1).unwrap_or(&"0"),
|
||||
parts.get(2).unwrap_or(&"0"),
|
||||
parts.get(3).unwrap_or(&"0")
|
||||
)
|
||||
};
|
||||
format!(
|
||||
"Add-Type -AssemblyName System.Windows.Forms,System.Drawing; {bounds}; \
|
||||
$bmp=New-Object System.Drawing.Bitmap($r.Width,$r.Height); \
|
||||
$g=[System.Drawing.Graphics]::FromImage($bmp); \
|
||||
$g.CopyFromScreen($r.Left,$r.Top,0,0,$bmp.Size); \
|
||||
$bmp.Save('{out}',[System.Drawing.Imaging.ImageFormat]::Png); $g.Dispose(); $bmp.Dispose()"
|
||||
)
|
||||
}
|
||||
|
||||
// === Shared helpers ===
|
||||
|
||||
/// Runs `program` with `args`, surfacing stderr on failure and a clear hint when it's missing.
|
||||
///
|
||||
/// `kill_on_drop` throughout: a stopped tool call unwinds by dropping its future, and a capture
|
||||
/// helper waiting on a compositor that never answers has to go with it rather than linger. Stdin is
|
||||
/// closed for the same reason it is in `bash` — a helper that reads it would eat the user's
|
||||
/// keystrokes out from under the TUI.
|
||||
/// How long a native capture may take. Each is sub-second on a screen that is drawing; one that is
|
||||
/// locked or asleep draws no frames, and `grim` waits for one indefinitely, so a capture that has not
|
||||
/// finished by now never will.
|
||||
const CAPTURE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(15);
|
||||
|
||||
async fn run(program: &str, args: &[String]) -> Result<()> {
|
||||
run_within(program, args, CAPTURE_DEADLINE).await
|
||||
}
|
||||
|
||||
async fn run_within(program: &str, args: &[String], deadline: std::time::Duration) -> Result<()> {
|
||||
let child = Command::new(program)
|
||||
.args(args)
|
||||
.kill_on_drop(true)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.output();
|
||||
// Dropping the future on timeout kills the capture, `kill_on_drop` being what makes it so
|
||||
let Ok(output) = tokio::time::timeout(deadline, child).await else {
|
||||
bail!(
|
||||
"`{program}` produced no image within {}s. A screen that is locked or asleep draws no \
|
||||
frames to capture; wake it and try again.",
|
||||
deadline.as_secs()
|
||||
);
|
||||
};
|
||||
let output = output.map_err(|err| {
|
||||
if err.kind() == std::io::ErrorKind::NotFound {
|
||||
anyhow!("`{program}` is not installed or not on PATH")
|
||||
} else {
|
||||
anyhow!("failed to spawn `{program}`: {err}")
|
||||
}
|
||||
})?;
|
||||
if !output.status.success() {
|
||||
bail!("`{program}` failed: {}", String::from_utf8_lossy(&output.stderr).trim());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Tries each `(program, args)` candidate in order, returning on the first success. Reports the
|
||||
/// last error (and `hint`) when they all fail or none are installed.
|
||||
async fn try_candidates(candidates: &[(&str, Vec<String>)], hint: &str) -> Result<()> {
|
||||
let mut last_error = None;
|
||||
for (program, args) in candidates {
|
||||
if !which(program) {
|
||||
continue;
|
||||
}
|
||||
match run(program, args).await {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(err) => last_error = Some(err),
|
||||
}
|
||||
}
|
||||
match last_error {
|
||||
Some(err) => Err(err),
|
||||
None => bail!("no capture tool available — {hint}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Errors with an install hint when `program` isn't on PATH.
|
||||
fn require(program: &str, hint: &str) -> Result<()> {
|
||||
if which(program) {
|
||||
Ok(())
|
||||
} else {
|
||||
bail!("`{program}` is not installed or not on PATH — {hint}")
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `program` can be run.
|
||||
///
|
||||
/// Defers to [`luxe_core::program`], which is the one place that knows what "runnable" means on each
|
||||
/// platform — the executable bit on unix, a `PATHEXT` suffix on Windows — and which also looks in the
|
||||
/// install directories a package manager uses but a `PATH` often misses.
|
||||
pub(super) fn which(program: &str) -> bool {
|
||||
luxe_core::program::is_available(program)
|
||||
}
|
||||
|
||||
fn path_str(path: &Path) -> Result<String> {
|
||||
path.to_str().map(str::to_string).ok_or_else(|| anyhow!("output path is not valid UTF-8"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_geometry() {
|
||||
let r = parse_geometry("10,20 300x400").unwrap();
|
||||
assert_eq!((r.x, r.y, r.w, r.h), (10, 20, 300, 400));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_geometry() {
|
||||
assert!(parse_geometry("nonsense").is_err());
|
||||
assert!(parse_geometry("10,20").is_err()); // missing size
|
||||
assert!(parse_geometry("a,b cxd").is_err()); // non-numeric
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn which_resolves_installed_binaries() {
|
||||
if cfg!(unix) {
|
||||
assert!(which("sh"), "sh should resolve on unix");
|
||||
}
|
||||
assert!(!which("definitely-not-a-real-binary-xyzzy"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backend_label_is_stable() {
|
||||
assert_eq!(backend_label(DisplayBackend::X11), "X11");
|
||||
assert_eq!(backend_label(DisplayBackend::WaylandHyprland), "Wayland (Hyprland)");
|
||||
}
|
||||
|
||||
/// A capture that never finishes — a screen asleep, for `grim` — is cut off and says why,
|
||||
/// rather than holding the tool until its network-shaped deadline.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_capture_that_never_finishes_is_cut_off_with_a_reason() {
|
||||
let started = std::time::Instant::now();
|
||||
let error = run_within("sleep", &["30".into()], std::time::Duration::from_millis(200))
|
||||
.await
|
||||
.expect_err("cut off");
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5));
|
||||
assert!(error.to_string().contains("locked or asleep"), "{error}");
|
||||
}
|
||||
}
|
||||
198
crates/luxe-tools/src/skill.rs
Normal file
198
crates/luxe-tools/src/skill.rs
Normal file
@@ -0,0 +1,198 @@
|
||||
// Skill discovery + load tool.
|
||||
//
|
||||
// skill — discover SKILL.md playbooks from global (~/.config/luxe/skills/) and project
|
||||
// (./.luxe/skills/) directories, and load one's full instructions on demand. Discovery + parsing
|
||||
// live in `luxe_core::skills` (shared with the system-prompt builder); this tool is the surface.
|
||||
|
||||
use async_trait::async_trait;
|
||||
use luxe_core::provider::ToolSchema;
|
||||
use luxe_core::tool::{Tool, ToolContext, ToolResultData};
|
||||
|
||||
/// Skill discovery + load tool.
|
||||
pub(crate) struct SkillTool;
|
||||
|
||||
/// Configuration placeholder kept for API compatibility (discovery dirs are resolved by
|
||||
/// [`luxe_core::skills`]).
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub(crate) struct SkillConfig;
|
||||
|
||||
impl SkillTool {
|
||||
pub(crate) fn new(_config: SkillConfig) -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
/// Ceiling on one loaded skill body.
|
||||
const SKILL_MAX_CHARS: usize = 40_000;
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for SkillTool {
|
||||
fn name(&self) -> &str {
|
||||
"skill"
|
||||
}
|
||||
|
||||
fn schema(&self) -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: "skill".to_string(),
|
||||
description: "Discover and load skills — SKILL.md playbooks from ~/.config/luxe/skills \
|
||||
and ./.luxe/skills. `action:\"discover\"` lists available skills (name + \
|
||||
description); `action:\"load\"` with `name` returns that skill's full instructions. \
|
||||
Load a skill before doing work it covers."
|
||||
.to_string(),
|
||||
parameters: serde_json::json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {"type": "string", "enum": ["discover", "load"], "description": "discover = list skills; load = fetch one skill's instructions"},
|
||||
"name": {"type": "string", "description": "Skill name (required for load)"}
|
||||
},
|
||||
"required": ["action"]
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(&self, args: serde_json::Value, cx: &ToolContext) -> ToolResultData {
|
||||
let Some(action) = args.get("action").and_then(|v| v.as_str()) else {
|
||||
return ToolResultData::error("Error: 'action' argument is required");
|
||||
};
|
||||
match action {
|
||||
"discover" => {
|
||||
let skills: Vec<serde_json::Value> = luxe_core::skills::discover(&cx.cwd)
|
||||
.into_iter()
|
||||
.map(|s| {
|
||||
serde_json::json!({
|
||||
"name": s.name,
|
||||
"description": s.description,
|
||||
"path": luxe_core::paths::display(&s.path),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if skills.is_empty() {
|
||||
return ToolResultData::text(format!(
|
||||
"No skills found. Add one at .luxe/skills/<name>/SKILL.md (with \
|
||||
`name` + `description` frontmatter) or {}/.",
|
||||
luxe_core::user_dirs::config_path_display("skills")
|
||||
));
|
||||
}
|
||||
ToolResultData::text(serde_json::to_string_pretty(&skills).unwrap_or_default())
|
||||
}
|
||||
"load" => {
|
||||
let Some(name) =
|
||||
args.get("name").and_then(|v| v.as_str()).filter(|s| !s.is_empty())
|
||||
else {
|
||||
return ToolResultData::error("Error: 'name' is required for load");
|
||||
};
|
||||
match luxe_core::skills::load_with_path(&cx.cwd, name) {
|
||||
// A skill is authored to be loaded, so the ceiling is generous — it exists so
|
||||
// one oversized file cannot swallow the context window it was meant to inform.
|
||||
// The path goes in the hint because "read the file" is useless without it.
|
||||
Some((body, path)) => {
|
||||
let body = crate::output_limit::cap_chars(
|
||||
&body,
|
||||
SKILL_MAX_CHARS,
|
||||
&format!(
|
||||
"Read the rest with: read {}",
|
||||
luxe_core::paths::display(&path)
|
||||
),
|
||||
);
|
||||
// a skill's reference files are named relative to its own folder
|
||||
let folder = path.parent().map(luxe_core::paths::display);
|
||||
ToolResultData::text(match folder {
|
||||
Some(folder) => {
|
||||
format!("{body}\n\nFiles this skill names are in {folder}")
|
||||
}
|
||||
None => body,
|
||||
})
|
||||
}
|
||||
None => ToolResultData::error(format!(
|
||||
"No skill named '{name}'. Use action:\"discover\" to list skills."
|
||||
)),
|
||||
}
|
||||
}
|
||||
other => ToolResultData::error(format!(
|
||||
"Unknown action '{other}'. Use 'discover' or 'load'."
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
fn test_context(tmp_dir: &std::path::Path) -> ToolContext {
|
||||
let (event_tx, _event_rx) = mpsc::channel(64);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
ToolContext {
|
||||
cwd: tmp_dir.to_path_buf(),
|
||||
session_id: "test-session".to_string(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn text_of(result: &ToolResultData) -> String {
|
||||
match &result.content[0] {
|
||||
luxe_core::ContentBlock::Text(s) => s.clone(),
|
||||
_ => panic!("expected text"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discover_reports_none_when_empty() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::env::set_var("HOME", tmp.path()); // isolate global skills (nextest = process-per-test)
|
||||
std::env::remove_var("XDG_CONFIG_HOME");
|
||||
let tool = SkillTool::new(SkillConfig);
|
||||
let result =
|
||||
tool.run(serde_json::json!({"action": "discover"}), &test_context(tmp.path())).await;
|
||||
assert!(!result.is_error);
|
||||
assert!(text_of(&result).contains("No skills found"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discover_then_load_a_project_skill() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::env::set_var("HOME", tmp.path());
|
||||
std::env::remove_var("XDG_CONFIG_HOME");
|
||||
let sd = tmp.path().join(".luxe/skills/test-skill");
|
||||
std::fs::create_dir_all(&sd).unwrap();
|
||||
std::fs::write(
|
||||
sd.join("SKILL.md"),
|
||||
"---\nname: Test Skill\ndescription: A test skill\n---\n\n# Test Skill\n\nBody here.",
|
||||
)
|
||||
.unwrap();
|
||||
let tool = SkillTool::new(SkillConfig);
|
||||
let ctx = test_context(tmp.path());
|
||||
|
||||
let discovered = tool.run(serde_json::json!({"action": "discover"}), &ctx).await;
|
||||
assert!(text_of(&discovered).contains("Test Skill"));
|
||||
|
||||
let loaded =
|
||||
tool.run(serde_json::json!({"action": "load", "name": "Test Skill"}), &ctx).await;
|
||||
assert!(!loaded.is_error);
|
||||
let body = text_of(&loaded);
|
||||
assert!(body.contains("Body here."));
|
||||
assert!(!body.contains("description:"), "frontmatter stripped");
|
||||
// A skill that names `references/x.md` is no use unless the agent knows where it lives
|
||||
let folder = luxe_core::paths::display(&sd);
|
||||
assert!(body.contains(&format!("Files this skill names are in {folder}")), "{body}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn load_unknown_and_missing_args_error() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
std::env::set_var("HOME", tmp.path());
|
||||
let tool = SkillTool::new(SkillConfig);
|
||||
let ctx = test_context(tmp.path());
|
||||
assert!(tool.run(serde_json::json!({}), &ctx).await.is_error);
|
||||
assert!(tool.run(serde_json::json!({"action": "load"}), &ctx).await.is_error);
|
||||
assert!(
|
||||
tool.run(serde_json::json!({"action": "load", "name": "nope"}), &ctx).await.is_error
|
||||
);
|
||||
}
|
||||
}
|
||||
437
crates/luxe-tools/src/ssrf.rs
Normal file
437
crates/luxe-tools/src/ssrf.rs
Normal file
@@ -0,0 +1,437 @@
|
||||
//! SSRF guard for outbound web fetches.
|
||||
//!
|
||||
//! An agent can be steered — by a prompt, or by a page it just fetched — into requesting a URL the
|
||||
//! user never meant it to reach. Before every fetch we require http/https, resolve the host, and
|
||||
//! classify the address; redirects are followed manually so **each hop** is re-validated, and the
|
||||
//! connection is pinned to the validated IP to close the DNS-rebinding window.
|
||||
//!
|
||||
//! # What the guard is actually for
|
||||
//!
|
||||
//! The addresses split into two groups, and the guard treats them differently:
|
||||
//!
|
||||
//! - **Somewhere else** — cloud metadata (`169.254.169.254` and its IPv6 form), private LAN ranges,
|
||||
//! CGNAT, ULA. Reaching these is lateral movement: credentials the user never handed over, or a
|
||||
//! machine that merely shares their network. Denied, and a much stronger claim than the tool's
|
||||
//! convenience.
|
||||
//! - **This machine** — loopback. Luxe is a coding agent with an unrestricted `bash`, so
|
||||
//! `curl http://127.0.0.1:4321` is already one tool call away and permitted by default. Refusing
|
||||
//! the same origin to `web_fetch` and `screenshot` grants no protection whatsoever; it only breaks
|
||||
//! the thing `screenshot mode=url` exists to do, and the model works around it with `bash` and a
|
||||
//! headless browser.
|
||||
//!
|
||||
//! So loopback is [`AddressClass::Loopback`] and allowed, and everything non-public is
|
||||
//! [`AddressClass::Blocked`] and refused. `file://` stays refused separately: a local file read is
|
||||
//! not a network fetch, and `read` already does it with the project's own path rules.
|
||||
//!
|
||||
//! `LUXE_WEB_ALLOW_PRIVATE=1` remains the coarse opt-out for someone who intentionally fetches a LAN
|
||||
//! host or a TUN/fake-IP proxy.
|
||||
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
|
||||
|
||||
use reqwest::header::LOCATION;
|
||||
use url::Url;
|
||||
|
||||
use crate::web::WebError;
|
||||
|
||||
/// Max redirect hops before giving up.
|
||||
const MAX_REDIRECTS: usize = 6;
|
||||
|
||||
/// Default request timeout in seconds.
|
||||
const DEFAULT_WEB_TIMEOUT_SECS: u64 = 30;
|
||||
|
||||
/// How long name resolution gets before the host counts as unreachable.
|
||||
///
|
||||
/// The system resolver has its own timeouts and they are not ours: `getaddrinfo` against a
|
||||
/// misconfigured or blackholed nameserver can sit for tens of seconds, and it happens *outside*
|
||||
/// reqwest's request timeout, so the per-request bound below never sees it.
|
||||
const RESOLVE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
/// Returns the per-request timeout for outbound web fetches.
|
||||
///
|
||||
/// Reads `LUXE_WEB_TIMEOUT_SECS` from the environment. If the variable is unset, not a valid
|
||||
/// positive integer, or zero, the default of 30 seconds is returned instead.
|
||||
pub(crate) fn web_timeout() -> std::time::Duration {
|
||||
let secs = std::env::var("LUXE_WEB_TIMEOUT_SECS")
|
||||
.ok()
|
||||
.and_then(|v| v.trim().parse::<u64>().ok())
|
||||
.filter(|&s| s > 0)
|
||||
.unwrap_or(DEFAULT_WEB_TIMEOUT_SECS);
|
||||
std::time::Duration::from_secs(secs)
|
||||
}
|
||||
|
||||
/// Whether the guard is disabled via the explicit opt-out.
|
||||
pub(crate) fn guard_disabled() -> bool {
|
||||
std::env::var("LUXE_WEB_ALLOW_PRIVATE").as_deref() == Ok("1")
|
||||
}
|
||||
|
||||
/// Where an address lives, which is what decides whether reaching it is a problem.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum AddressClass {
|
||||
/// Globally routable. Ordinary web traffic.
|
||||
Public,
|
||||
/// This machine (`127.0.0.0/8`, `::1`, and their IPv4-mapped forms).
|
||||
Loopback,
|
||||
/// Somewhere else that is not the public internet: cloud metadata, private LAN, CGNAT, ULA,
|
||||
/// link-local, and the reserved/documentation ranges.
|
||||
Blocked,
|
||||
}
|
||||
|
||||
impl AddressClass {
|
||||
/// Whether a fetch under `local` may reach this class of address.
|
||||
pub(crate) fn is_reachable(self, local: LocalAccess) -> bool {
|
||||
match self {
|
||||
Self::Public => true,
|
||||
Self::Loopback => local == LocalAccess::Allowed,
|
||||
Self::Blocked => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a fetch may reach the machine it is running on.
|
||||
///
|
||||
/// A named type rather than a `bool`, because it is the switch that decides what a model-supplied URL
|
||||
/// can touch, and `safe_get(url, ua, true)` says nothing at the call site about which `true` that is.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum LocalAccess {
|
||||
/// A local origin is part of this tool's job — a dev server on this machine.
|
||||
Allowed,
|
||||
/// The public internet only.
|
||||
Denied,
|
||||
}
|
||||
|
||||
/// Classify an address: globally routable, this machine, or somewhere it must not reach.
|
||||
pub(crate) fn classify_ip(ip: IpAddr) -> AddressClass {
|
||||
match ip {
|
||||
IpAddr::V4(v4) => classify_v4(v4),
|
||||
// IPv4-mapped (`::ffff:a.b.c.d`) is the same address wearing a different hat, so classify
|
||||
// the address it actually names — otherwise `::ffff:127.0.0.1` slips past as its own case.
|
||||
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
|
||||
Some(v4) => classify_v4(v4),
|
||||
None => classify_v6(v6),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_v4(ip: Ipv4Addr) -> AddressClass {
|
||||
if ip.is_loopback() {
|
||||
return AddressClass::Loopback;
|
||||
}
|
||||
if is_public_v4(ip) {
|
||||
AddressClass::Public
|
||||
} else {
|
||||
AddressClass::Blocked
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_v6(ip: Ipv6Addr) -> AddressClass {
|
||||
if ip.is_loopback() {
|
||||
return AddressClass::Loopback;
|
||||
}
|
||||
// a translated address reaches the IPv4 it carries, so that is the one to judge; even an
|
||||
// embedded loopback is someone else's machine by then
|
||||
if let Some(v4) = embedded_v4(ip) {
|
||||
return match classify_v4(v4) {
|
||||
AddressClass::Public => AddressClass::Public,
|
||||
_ => AddressClass::Blocked,
|
||||
};
|
||||
}
|
||||
if is_public_v6(ip) {
|
||||
AddressClass::Public
|
||||
} else {
|
||||
AddressClass::Blocked
|
||||
}
|
||||
}
|
||||
|
||||
fn is_public_v4(ip: Ipv4Addr) -> bool {
|
||||
let [a, b, ..] = ip.octets();
|
||||
if ip.is_private()
|
||||
|| ip.is_loopback()
|
||||
|| ip.is_link_local()
|
||||
|| ip.is_broadcast()
|
||||
|| ip.is_documentation()
|
||||
|| ip.is_unspecified()
|
||||
|| ip.is_multicast()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// 0.0.0.0/8 (this network), CGNAT 100.64/10, benchmarking 198.18/15, reserved 240/4.
|
||||
if a == 0
|
||||
|| (a == 100 && (64..=127).contains(&b))
|
||||
|| (a == 198 && (b == 18 || b == 19))
|
||||
|| a >= 240
|
||||
{
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn is_public_v6(ip: Ipv6Addr) -> bool {
|
||||
if ip.is_loopback() || ip.is_unspecified() || ip.is_multicast() {
|
||||
return false;
|
||||
}
|
||||
// IPv4-mapped (::ffff:a.b.c.d) — validate the embedded v4.
|
||||
if let Some(v4) = ip.to_ipv4_mapped() {
|
||||
return is_public_v4(v4);
|
||||
}
|
||||
let [first, second, ..] = ip.segments();
|
||||
// ULA fc00::/7, link-local fe80::/10, site-local fec0::/10, documentation 2001:db8::/32
|
||||
!((0xfc00..=0xfdff).contains(&first)
|
||||
|| (0xfe80..=0xfeff).contains(&first)
|
||||
|| (first, second) == (0x2001, 0x0db8))
|
||||
}
|
||||
|
||||
/// The IPv4 address an IPv6 one carries when it is a translation of it: NAT64 (`64:ff9b::/96`),
|
||||
/// 6to4 (`2002::/16`), Teredo (`2001::/32`, whose client address is stored inverted) and the old
|
||||
/// IPv4-compatible form (`::a.b.c.d`).
|
||||
fn embedded_v4(ip: Ipv6Addr) -> Option<Ipv4Addr> {
|
||||
let v4 = |high: u16, low: u16| Ipv4Addr::from((u32::from(high) << 16) | u32::from(low));
|
||||
match ip.segments() {
|
||||
[0x64, 0xff9b, 0, 0, 0, 0, high, low] => Some(v4(high, low)),
|
||||
[0x2002, high, low, ..] => Some(v4(high, low)),
|
||||
[0x2001, 0, _, _, _, _, high, low] => Some(v4(!high, !low)),
|
||||
// `::` and `::1` are their own addresses, not IPv4-compatible ones
|
||||
[0, 0, 0, 0, 0, 0, high, low] if (high, low) > (0, 1) => Some(v4(high, low)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate a URL's scheme + host and resolve it to a set of reachable socket addresses.
|
||||
///
|
||||
/// `allow_loopback` admits this machine's own addresses; see [`AddressClass`] for why that is a
|
||||
/// different question from admitting a private LAN host. Errors if the scheme isn't http/https,
|
||||
/// resolution fails or times out, or any resolved address is one the caller may not reach.
|
||||
///
|
||||
/// Every address is checked, not just the one that gets pinned: a host that resolves to both a public
|
||||
/// and a blocked address is a rebinding attempt wearing a single DNS answer.
|
||||
pub(crate) async fn resolve_validated(
|
||||
url: &Url,
|
||||
local: LocalAccess,
|
||||
) -> Result<Vec<SocketAddr>, WebError> {
|
||||
if url.scheme() != "http" && url.scheme() != "https" {
|
||||
return Err(WebError::Network(format!(
|
||||
"only http/https URLs are allowed (got {})",
|
||||
url.scheme()
|
||||
)));
|
||||
}
|
||||
let host = url.host_str().ok_or_else(|| WebError::Network("URL has no host".to_string()))?;
|
||||
let lower = host.to_ascii_lowercase();
|
||||
// `localhost` (and the reserved `.localhost` suffix) names this machine by definition, so it
|
||||
// follows the loopback policy rather than getting a name-based rule of its own. It still has to
|
||||
// resolve: a hosts file can point `localhost` anywhere.
|
||||
if (lower == "localhost" || lower.ends_with(".localhost")) && local == LocalAccess::Denied {
|
||||
return Err(WebError::Network(format!(
|
||||
"blocked local host '{host}': this tool does not fetch from the machine it runs on"
|
||||
)));
|
||||
}
|
||||
let port = url.port_or_known_default().unwrap_or(80);
|
||||
// An IP literal is already an address, and handing one to the resolver is worse than
|
||||
// unnecessary: `host_str` returns an IPv6 literal *with its brackets* (`[::1]`), which
|
||||
// `getaddrinfo` has never heard of — so every `http://[::1]:4321/` would fail as a name lookup.
|
||||
// That is the address a dual-stack dev server prints.
|
||||
let addrs: Vec<SocketAddr> = match url.host() {
|
||||
Some(url::Host::Ipv4(ip)) => vec![SocketAddr::new(IpAddr::V4(ip), port)],
|
||||
Some(url::Host::Ipv6(ip)) => vec![SocketAddr::new(IpAddr::V6(ip), port)],
|
||||
Some(url::Host::Domain(name)) => resolve_host(name, port).await?,
|
||||
None => return Err(WebError::Network("URL has no host".to_string())),
|
||||
};
|
||||
if addrs.is_empty() {
|
||||
return Err(WebError::Network(format!("no addresses for '{host}'")));
|
||||
}
|
||||
for addr in &addrs {
|
||||
let class = classify_ip(addr.ip());
|
||||
if class.is_reachable(local) {
|
||||
continue;
|
||||
}
|
||||
return Err(match class {
|
||||
AddressClass::Loopback => WebError::Network(format!(
|
||||
"blocked loopback address {} for '{host}': this tool does not fetch from the \
|
||||
machine it runs on",
|
||||
addr.ip()
|
||||
)),
|
||||
_ => WebError::Network(format!(
|
||||
"blocked {} for '{host}': not a public address, and not this machine — private \
|
||||
networks and cloud metadata endpoints are off limits. Set \
|
||||
LUXE_WEB_ALLOW_PRIVATE=1 if you meant to reach it.",
|
||||
addr.ip()
|
||||
)),
|
||||
});
|
||||
}
|
||||
Ok(addrs)
|
||||
}
|
||||
|
||||
/// Resolve a domain name, bounded by [`RESOLVE_TIMEOUT`].
|
||||
async fn resolve_host(name: &str, port: u16) -> Result<Vec<SocketAddr>, WebError> {
|
||||
match tokio::time::timeout(RESOLVE_TIMEOUT, tokio::net::lookup_host((name, port))).await {
|
||||
Ok(Ok(addrs)) => Ok(addrs.collect()),
|
||||
Ok(Err(e)) => Err(WebError::Network(format!("failed to resolve '{name}': {e}"))),
|
||||
Err(_) => Err(WebError::Timeout(format!(
|
||||
"resolving '{name}' took longer than {}s",
|
||||
RESOLVE_TIMEOUT.as_secs()
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
/// SSRF-safe HTTP GET returning the response body. Redirects are followed manually, re-validating
|
||||
/// each hop and pinning the connection to the validated IP. The opt-out bypasses validation but
|
||||
/// still fetches (for intentional internal fetches).
|
||||
///
|
||||
/// [`web_timeout`] bounds the **whole** fetch, not each hop. Per-hop was the same number multiplied
|
||||
/// by six, and then doubled again by `web_fetch`'s stealth retry: a host that completed the
|
||||
/// handshake and then went quiet cost six minutes against a setting that reads as thirty seconds.
|
||||
pub(crate) async fn safe_get(
|
||||
url_str: &str,
|
||||
user_agent: &str,
|
||||
local: LocalAccess,
|
||||
) -> Result<Fetched, WebError> {
|
||||
follow(url_str, user_agent, local, Hops { origin_local: None, body_cap: MAX_BODY_BYTES }).await
|
||||
}
|
||||
|
||||
/// Most of a body a fetch reads; past it the rest is left unread.
|
||||
pub(crate) const MAX_BODY_BYTES: usize = 10 * 1024 * 1024;
|
||||
|
||||
/// A fetched body, and whether it stopped at [`MAX_BODY_BYTES`].
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Fetched {
|
||||
/// The body as text, in the charset the server declared
|
||||
pub(crate) body: String,
|
||||
/// Whether the rest was left unread; a caller says so after it has reduced the page
|
||||
pub(crate) truncated: bool,
|
||||
}
|
||||
|
||||
impl Fetched {
|
||||
/// The body reduced by `reduce` (to markdown, say), with a note after it when the body was
|
||||
/// cut: one written into the HTML might not survive the reduction.
|
||||
pub(crate) fn reduced(self, reduce: impl FnOnce(&str) -> String) -> String {
|
||||
let mut text = reduce(&self.body);
|
||||
if self.truncated {
|
||||
let megabytes = MAX_BODY_BYTES / (1024 * 1024);
|
||||
text.push_str(&format!(
|
||||
"\n\n[truncated: the page passed {megabytes} MB, and the rest was not read]"
|
||||
));
|
||||
}
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every address names this machine: the fetch started here, and may come back here.
|
||||
fn is_local(addrs: &[SocketAddr]) -> bool {
|
||||
addrs.iter().all(|addr| classify_ip(addr.ip()) == AddressClass::Loopback)
|
||||
}
|
||||
|
||||
/// Whether a hop would land on this machine though the fetch started elsewhere: SSRF by redirect,
|
||||
/// since the carve-out for this machine covers a URL the caller asked for, not one a page picked.
|
||||
/// One loopback address is enough, as the connection may fall back to it.
|
||||
fn lands_here_from_elsewhere(origin_local: bool, hop: &[SocketAddr]) -> bool {
|
||||
!origin_local && hop.iter().any(|addr| classify_ip(addr.ip()) == AddressClass::Loopback)
|
||||
}
|
||||
|
||||
/// What a fetch holds itself to across its hops.
|
||||
struct Hops {
|
||||
/// Whether the first URL is on this machine; `None` works it out from that URL's addresses.
|
||||
origin_local: Option<bool>,
|
||||
body_cap: usize,
|
||||
}
|
||||
|
||||
async fn follow(
|
||||
url_str: &str,
|
||||
user_agent: &str,
|
||||
local: LocalAccess,
|
||||
mut hops: Hops,
|
||||
) -> Result<Fetched, WebError> {
|
||||
let mut current =
|
||||
Url::parse(url_str).map_err(|e| WebError::Network(format!("invalid URL: {e}")))?;
|
||||
let origin = current.clone();
|
||||
let budget = web_timeout();
|
||||
let deadline = tokio::time::Instant::now() + budget;
|
||||
|
||||
for hop in 0..MAX_REDIRECTS {
|
||||
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
|
||||
if remaining.is_zero() {
|
||||
return Err(WebError::Timeout(format!(
|
||||
"fetching {current} took longer than {}s",
|
||||
budget.as_secs()
|
||||
)));
|
||||
}
|
||||
let mut builder = reqwest::Client::builder()
|
||||
.user_agent(user_agent)
|
||||
.timeout(remaining)
|
||||
.redirect(reqwest::redirect::Policy::none());
|
||||
|
||||
if !guard_disabled() {
|
||||
let addrs = resolve_validated(¤t, local).await?;
|
||||
let origin_local = *hops.origin_local.get_or_insert_with(|| is_local(&addrs));
|
||||
if hop > 0 && lands_here_from_elsewhere(origin_local, &addrs) {
|
||||
return Err(WebError::Network(format!(
|
||||
"refused a redirect from {origin} to {current}: a page on another host may not \
|
||||
send this fetch to the machine it runs on"
|
||||
)));
|
||||
}
|
||||
// Pin only a *name*: the rebinding window this closes is the gap between our lookup and
|
||||
// the client's, and an IP literal never had one. `host_str` also brackets an IPv6
|
||||
// literal, which is not a name reqwest could match anyway.
|
||||
//
|
||||
// Pin the whole validated set, not its first entry. Every address in it passed the same
|
||||
// check, and handing over only one throws away the connect fallback a dual-stack host
|
||||
// depends on — a name resolving to `::1` and `127.0.0.1` where the server listens on just
|
||||
// one of them is the ordinary shape of a local dev server, not an edge case.
|
||||
if let Some(url::Host::Domain(host)) = current.host() {
|
||||
builder = builder.resolve_to_addrs(host, &addrs);
|
||||
}
|
||||
}
|
||||
|
||||
let client = builder.build().map_err(|e| WebError::Network(e.to_string()))?;
|
||||
// Ask reqwest which kind of failure this was rather than reading its message: a timeout must
|
||||
// be typed as one, because it is the failure a retry cannot improve on.
|
||||
let response = client.get(current.clone()).send().await.map_err(|e| {
|
||||
if e.is_timeout() {
|
||||
WebError::Timeout(format!("{current} did not answer within {}s", budget.as_secs()))
|
||||
} else {
|
||||
WebError::Network(e.to_string())
|
||||
}
|
||||
})?;
|
||||
let status = response.status();
|
||||
|
||||
if status.is_redirection() {
|
||||
let location =
|
||||
response.headers().get(LOCATION).and_then(|v| v.to_str().ok()).ok_or_else(
|
||||
|| WebError::Http(format!("redirect {status} without a Location header")),
|
||||
)?;
|
||||
current = current
|
||||
.join(location)
|
||||
.map_err(|e| WebError::Network(format!("bad redirect target: {e}")))?;
|
||||
continue;
|
||||
}
|
||||
if !status.is_success() {
|
||||
return Err(WebError::Http(format!("HTTP {status} for {current}")));
|
||||
}
|
||||
return bounded_body(response, hops.body_cap).await;
|
||||
}
|
||||
Err(WebError::Http("too many redirects".to_string()))
|
||||
}
|
||||
|
||||
/// The body, reading no more than `cap` bytes of it: a server streaming without end must not fill
|
||||
/// memory inside the time budget. Decoded in the declared charset, as `text()` would.
|
||||
async fn bounded_body(mut response: reqwest::Response, cap: usize) -> Result<Fetched, WebError> {
|
||||
let charset = response
|
||||
.headers()
|
||||
.get(reqwest::header::CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(|value| value.split(';').find_map(|part| part.trim().strip_prefix("charset=")))
|
||||
.and_then(|label| encoding_rs::Encoding::for_label(label.trim_matches('"').as_bytes()))
|
||||
.unwrap_or(encoding_rs::UTF_8);
|
||||
let mut body = Vec::new();
|
||||
let mut truncated = false;
|
||||
while let Some(chunk) = response.chunk().await.map_err(|e| WebError::Parse(e.to_string()))? {
|
||||
let room = cap - body.len();
|
||||
body.extend_from_slice(&chunk[..chunk.len().min(room)]);
|
||||
if chunk.len() > room {
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (text, _, _) = charset.decode(&body);
|
||||
Ok(Fetched { body: text.into_owned(), truncated })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
229
crates/luxe-tools/src/ssrf/tests.rs
Normal file
229
crates/luxe-tools/src/ssrf/tests.rs
Normal file
@@ -0,0 +1,229 @@
|
||||
use super::*;
|
||||
|
||||
/// A one-route-table HTTP server on loopback: `/hop` redirects to `/landed`, `/big` sends 64
|
||||
/// bytes, anything else answers `landed`.
|
||||
async fn serve() -> u16 {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
tokio::spawn(async move {
|
||||
while let Ok((mut socket, _)) = listener.accept().await {
|
||||
let mut request = [0u8; 1024];
|
||||
let read = socket.read(&mut request).await.unwrap_or(0);
|
||||
let request = String::from_utf8_lossy(&request[..read]).into_owned();
|
||||
let response = if request.starts_with("GET /hop ") {
|
||||
"HTTP/1.1 302 Found\r\nLocation: /landed\r\nContent-Length: 0\r\n\r\n".into()
|
||||
} else if request.starts_with("GET /big ") {
|
||||
format!("HTTP/1.1 200 OK\r\nContent-Length: 64\r\n\r\n{}", "x".repeat(64))
|
||||
} else if request.starts_with("GET /latin1 ") {
|
||||
let head = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=iso-8859-1\r\n";
|
||||
let _ = socket
|
||||
.write_all(format!("{head}Content-Length: 4\r\n\r\ncaf").as_bytes())
|
||||
.await;
|
||||
let _ = socket.write_all(&[0xE9]).await;
|
||||
continue;
|
||||
} else {
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: 6\r\n\r\nlanded".to_string()
|
||||
};
|
||||
let _ = socket.write_all(response.as_bytes()).await;
|
||||
}
|
||||
});
|
||||
port
|
||||
}
|
||||
|
||||
/// A page on another host must not steer the fetch onto this machine; a local origin
|
||||
/// redirecting to itself is the dev server it always was.
|
||||
#[tokio::test]
|
||||
async fn a_redirect_onto_this_machine_needs_a_local_origin() {
|
||||
let port = serve().await;
|
||||
let url = format!("http://127.0.0.1:{port}/hop");
|
||||
let local = Hops { origin_local: None, body_cap: MAX_BODY_BYTES };
|
||||
assert_eq!(follow(&url, "t", LocalAccess::Allowed, local).await.unwrap().body, "landed");
|
||||
let from_public = Hops { origin_local: Some(false), body_cap: MAX_BODY_BYTES };
|
||||
let error = follow(&url, "t", LocalAccess::Allowed, from_public).await.unwrap_err();
|
||||
assert!(error.to_string().contains("redirect"), "{error}");
|
||||
}
|
||||
|
||||
/// Whether a hop may land on this machine is decided by where the fetch started: never from
|
||||
/// elsewhere, whatever spelling of loopback the hop resolves to, and not when only one of its
|
||||
/// addresses is loopback.
|
||||
#[test]
|
||||
fn a_hop_onto_this_machine_is_refused_unless_the_origin_was_here() {
|
||||
let addrs = |ips: &[&str]| -> Vec<SocketAddr> {
|
||||
ips.iter().map(|ip| SocketAddr::new(ip.parse().unwrap(), 80)).collect()
|
||||
};
|
||||
let public = addrs(&["93.184.216.34"]);
|
||||
assert!(!is_local(&public));
|
||||
assert!(is_local(&addrs(&["127.0.0.1", "::1"])));
|
||||
assert!(!is_local(&addrs(&["93.184.216.34", "127.0.0.1"])), "a mixed answer is not local");
|
||||
for hop in [&["127.0.0.1"][..], &["::ffff:127.0.0.1"], &["93.184.216.34", "127.0.0.1"]] {
|
||||
assert!(lands_here_from_elsewhere(false, &addrs(hop)), "{hop:?}");
|
||||
assert!(!lands_here_from_elsewhere(true, &addrs(hop)), "{hop:?}");
|
||||
}
|
||||
assert!(!lands_here_from_elsewhere(false, &public));
|
||||
}
|
||||
|
||||
/// The body is decoded in the charset the server declared, as `text()` did before the cap.
|
||||
#[tokio::test]
|
||||
async fn a_declared_charset_is_honored() {
|
||||
let port = serve().await;
|
||||
let url = format!("http://127.0.0.1:{port}/latin1");
|
||||
let fetched = safe_get(&url, "t", LocalAccess::Allowed).await.unwrap();
|
||||
assert_eq!(fetched.body, "café");
|
||||
assert!(!fetched.truncated);
|
||||
}
|
||||
|
||||
/// A body past the cap stops being read, and the text says it was cut.
|
||||
#[tokio::test]
|
||||
async fn a_body_past_the_cap_is_cut_and_says_so() {
|
||||
let port = serve().await;
|
||||
let url = format!("http://127.0.0.1:{port}/big");
|
||||
let hops = Hops { origin_local: None, body_cap: 16 };
|
||||
let fetched = follow(&url, "t", LocalAccess::Allowed, hops).await.unwrap();
|
||||
assert_eq!(fetched.body, "x".repeat(16));
|
||||
assert!(fetched.truncated);
|
||||
}
|
||||
|
||||
/// One test, not four: the thing under test is a **process-global** variable and the harness runs
|
||||
/// tests in parallel threads, so four of them setting and clearing the same name raced. The
|
||||
/// failure read as a broken parser when it was really the neighboring test.
|
||||
#[test]
|
||||
fn web_timeout_takes_a_valid_override_and_ignores_the_rest() {
|
||||
struct Restore(Option<String>);
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
match self.0.take() {
|
||||
Some(value) => std::env::set_var("LUXE_WEB_TIMEOUT_SECS", value),
|
||||
None => std::env::remove_var("LUXE_WEB_TIMEOUT_SECS"),
|
||||
}
|
||||
}
|
||||
}
|
||||
let _restore = Restore(std::env::var("LUXE_WEB_TIMEOUT_SECS").ok());
|
||||
|
||||
std::env::remove_var("LUXE_WEB_TIMEOUT_SECS");
|
||||
assert_eq!(web_timeout(), std::time::Duration::from_secs(30), "default");
|
||||
|
||||
std::env::set_var("LUXE_WEB_TIMEOUT_SECS", "60");
|
||||
assert_eq!(web_timeout(), std::time::Duration::from_secs(60), "honored");
|
||||
|
||||
// A typo must not silently remove the bound, and neither must a zero.
|
||||
for bad in ["not_a_number", "0", "", "-5"] {
|
||||
std::env::set_var("LUXE_WEB_TIMEOUT_SECS", bad);
|
||||
assert_eq!(web_timeout(), std::time::Duration::from_secs(30), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The distinction the guard is built on: somewhere else, versus this machine.
|
||||
#[test]
|
||||
fn addresses_split_into_public_loopback_and_off_limits() {
|
||||
for ip in [
|
||||
"8.8.8.8",
|
||||
"1.1.1.1",
|
||||
"140.82.112.3",
|
||||
"2606:4700:4700::1111",
|
||||
"64:ff9b::808:808", // NAT64 of a public address is still public
|
||||
"2002:808:808::1", // 6to4 likewise
|
||||
] {
|
||||
assert_eq!(classify_ip(ip.parse().unwrap()), AddressClass::Public, "{ip}");
|
||||
}
|
||||
for ip in ["127.0.0.1", "127.1.2.3", "::1", "::ffff:127.0.0.1"] {
|
||||
assert_eq!(classify_ip(ip.parse().unwrap()), AddressClass::Loopback, "{ip}");
|
||||
}
|
||||
for ip in [
|
||||
"10.1.2.3",
|
||||
"172.16.0.1",
|
||||
"192.168.1.1",
|
||||
"169.254.169.254", // cloud metadata
|
||||
"100.64.0.1", // CGNAT
|
||||
"0.0.0.0",
|
||||
"198.18.0.1", // benchmarking
|
||||
"240.0.0.1", // reserved
|
||||
"fe80::1",
|
||||
"fc00::1",
|
||||
"::ffff:192.168.1.1", // the same private host, IPv4-mapped
|
||||
"64:ff9b::a9fe:a9fe", // NAT64 of the metadata endpoint
|
||||
"64:ff9b::c0a8:101", // NAT64 of a LAN host
|
||||
"2002:a9fe:a9fe::1", // 6to4 of the metadata endpoint
|
||||
"2001:0:4136:e378:8000:63bf:5601:5efe", // Teredo, client 169.254.161.1
|
||||
"::a9fe:a9fe", // IPv4-compatible
|
||||
"fec0::1", // site-local
|
||||
"2001:db8::1", // documentation
|
||||
] {
|
||||
assert_eq!(classify_ip(ip.parse().unwrap()), AddressClass::Blocked, "{ip}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Loopback is a *policy* question, and the answer is the caller's. Nothing else moves with it —
|
||||
/// admitting a dev server on this machine must not admit the cloud metadata endpoint.
|
||||
#[test]
|
||||
fn only_loopback_follows_the_local_access_policy() {
|
||||
let cases = [
|
||||
("1.1.1.1", true, true),
|
||||
("127.0.0.1", true, false),
|
||||
("::1", true, false),
|
||||
("169.254.169.254", false, false),
|
||||
("192.168.1.1", false, false),
|
||||
];
|
||||
for (ip, when_allowed, when_denied) in cases {
|
||||
let class = classify_ip(ip.parse().unwrap());
|
||||
assert_eq!(class.is_reachable(LocalAccess::Allowed), when_allowed, "{ip} allowed");
|
||||
assert_eq!(class.is_reachable(LocalAccess::Denied), when_denied, "{ip} denied");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_non_http_schemes_whatever_the_local_policy() {
|
||||
for local in [LocalAccess::Allowed, LocalAccess::Denied] {
|
||||
for url in ["file:///etc/passwd", "ftp://example.com", "data:text/html,hi"] {
|
||||
assert!(
|
||||
resolve_validated(&Url::parse(url).unwrap(), local).await.is_err(),
|
||||
"{url} under {local:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The bug this split fixes: a dev server on this machine is the `screenshot`/`web_fetch` use
|
||||
/// case, not an attack. It resolves and passes; it does not need an env var set before launch.
|
||||
#[tokio::test]
|
||||
async fn a_local_dev_server_resolves_when_local_access_is_allowed() {
|
||||
for url in ["http://127.0.0.1:4321/", "http://localhost:4321/", "http://[::1]:4321/"] {
|
||||
let addrs = resolve_validated(&Url::parse(url).unwrap(), LocalAccess::Allowed)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("{url} must resolve: {error}"));
|
||||
assert!(!addrs.is_empty(), "{url}");
|
||||
assert!(addrs.iter().all(|addr| addr.ip().is_loopback()), "{url} stayed on loopback");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refuses_local_origins_when_local_access_is_denied() {
|
||||
for url in ["http://127.0.0.1:8080/x", "http://localhost:8080/x", "http://foo.localhost/x"] {
|
||||
assert!(
|
||||
resolve_validated(&Url::parse(url).unwrap(), LocalAccess::Denied).await.is_err(),
|
||||
"{url}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata and private-LAN targets stay refused even for the tools that are allowed loopback.
|
||||
/// This is the assertion that keeps the carve-out from quietly becoming a hole.
|
||||
#[tokio::test]
|
||||
async fn metadata_and_private_hosts_stay_refused_even_with_local_access() {
|
||||
for url in [
|
||||
"http://169.254.169.254/latest/meta-data",
|
||||
"http://192.168.0.5/admin",
|
||||
"http://10.0.0.1/",
|
||||
"http://172.16.5.5/",
|
||||
"http://100.64.0.1/",
|
||||
] {
|
||||
let error = resolve_validated(&Url::parse(url).unwrap(), LocalAccess::Allowed)
|
||||
.await
|
||||
.expect_err(&format!("{url} must stay blocked"));
|
||||
let message = error.to_string();
|
||||
assert!(
|
||||
message.contains("not this machine"),
|
||||
"the refusal should say which boundary it is: {message}"
|
||||
);
|
||||
}
|
||||
}
|
||||
161
crates/luxe-tools/src/tavily.rs
Normal file
161
crates/luxe-tools/src/tavily.rs
Normal file
@@ -0,0 +1,161 @@
|
||||
//! Tavily — a search API built for agents, so it takes Luxe's whole option set as parameters.
|
||||
//!
|
||||
//! Domain include/exclude, a recency window and a result cap are all first-class here, and the
|
||||
//! `content` field on each result is already the query-relevant extract rather than a meta
|
||||
//! description. The key goes in the `Authorization` header: Tavily's original body-field auth
|
||||
//! still answers, but it is the deprecated spelling and not what a new integration should send.
|
||||
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::web::{SearchBackend, SearchHit, SearchOptions, WebError};
|
||||
|
||||
/// Tavily Search API request.
|
||||
#[derive(Debug, Serialize)]
|
||||
struct TavilyRequest {
|
||||
query: String,
|
||||
max_results: usize,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
include_domains: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
exclude_domains: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
time_range: Option<&'static str>,
|
||||
/// `advanced` costs a second credit and buys longer, better-targeted extracts, which is the
|
||||
/// trade this tool exists to make when the caller asked for content.
|
||||
search_depth: &'static str,
|
||||
}
|
||||
|
||||
/// Tavily Search API response.
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct TavilyResponse {
|
||||
results: Option<Vec<TavilyResult>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct TavilyResult {
|
||||
title: Option<String>,
|
||||
url: Option<String>,
|
||||
content: Option<String>,
|
||||
}
|
||||
|
||||
/// Tavily search backend.
|
||||
pub struct TavilyBackend {
|
||||
api_key: String,
|
||||
base_url: String,
|
||||
}
|
||||
|
||||
impl TavilyBackend {
|
||||
/// A backend against Tavily's public endpoint.
|
||||
pub fn new(api_key: String) -> Self {
|
||||
Self { api_key, base_url: "https://api.tavily.com/search".to_string() }
|
||||
}
|
||||
|
||||
/// Point the backend at a stand-in endpoint (tests, a proxy).
|
||||
pub fn with_base_url(api_key: String, base_url: impl Into<String>) -> Self {
|
||||
Self { api_key, base_url: base_url.into() }
|
||||
}
|
||||
|
||||
/// The body for one search.
|
||||
fn request_body(&self, query: &str, n: usize, options: &SearchOptions) -> TavilyRequest {
|
||||
TavilyRequest {
|
||||
query: query.to_string(),
|
||||
max_results: n.max(1),
|
||||
include_domains: options.include_domains.clone(),
|
||||
exclude_domains: options.exclude_domains.clone(),
|
||||
time_range: options.recency.map(|recency| recency.tavily_range()),
|
||||
search_depth: match options.include_content {
|
||||
true => "advanced",
|
||||
false => "basic",
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl SearchBackend for TavilyBackend {
|
||||
async fn search(
|
||||
&self,
|
||||
query: &str,
|
||||
n: usize,
|
||||
options: &SearchOptions,
|
||||
) -> Result<Vec<SearchHit>, WebError> {
|
||||
let response = reqwest::Client::new()
|
||||
.post(&self.base_url)
|
||||
.header("Content-Type", "application/json")
|
||||
.bearer_auth(&self.api_key)
|
||||
.json(&self.request_body(query, n, options))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| WebError::Network(e.to_string()))?;
|
||||
|
||||
let status = response.status();
|
||||
let body = response.text().await.map_err(|e| WebError::Network(e.to_string()))?;
|
||||
if !status.is_success() {
|
||||
return Err(WebError::Http(format!("Tavily returned {status}: {}", body.trim())));
|
||||
}
|
||||
|
||||
let parsed: TavilyResponse =
|
||||
serde_json::from_str(&body).map_err(|e| WebError::Parse(e.to_string()))?;
|
||||
Ok(parsed
|
||||
.results
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|result| SearchHit {
|
||||
title: result.title.unwrap_or_default(),
|
||||
url: result.url.unwrap_or_default(),
|
||||
snippet: result.content.unwrap_or_default(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn body(options: &SearchOptions) -> serde_json::Value {
|
||||
let backend = TavilyBackend::new("test-key".to_string());
|
||||
serde_json::to_value(backend.request_body("tokio", 3, options)).expect("serializes")
|
||||
}
|
||||
|
||||
/// Every filter the tool schema advertises is a real Tavily parameter, so all of them have to
|
||||
/// reach the request. Dropping them returns plausible results for a question nobody asked.
|
||||
#[test]
|
||||
fn the_advertised_filters_all_reach_the_request() {
|
||||
let body = body(&SearchOptions {
|
||||
include_domains: vec!["docs.rs".to_string()],
|
||||
exclude_domains: vec!["reddit.com".to_string()],
|
||||
recency: Some(crate::web::Recency::Year),
|
||||
include_content: true,
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(body["query"], "tokio");
|
||||
assert_eq!(body["max_results"], 3);
|
||||
assert_eq!(body["include_domains"][0], "docs.rs");
|
||||
assert_eq!(body["exclude_domains"][0], "reddit.com");
|
||||
assert_eq!(body["time_range"], "year");
|
||||
assert_eq!(body["search_depth"], "advanced");
|
||||
}
|
||||
|
||||
/// An unasked filter is absent rather than empty: Tavily reads `include_domains: []` as a
|
||||
/// filter matching nothing on some plans, and an empty key is noise on every request.
|
||||
#[test]
|
||||
fn unset_filters_are_left_out_of_the_body_entirely() {
|
||||
let body = body(&SearchOptions::default());
|
||||
assert!(body.get("include_domains").is_none());
|
||||
assert!(body.get("exclude_domains").is_none());
|
||||
assert!(body.get("time_range").is_none());
|
||||
assert_eq!(body["search_depth"], "basic");
|
||||
}
|
||||
|
||||
/// The key belongs in the header. Tavily's body-field auth is the deprecated spelling, and a
|
||||
/// key in a JSON body is also a key in every log that captures one.
|
||||
#[test]
|
||||
fn the_key_never_travels_in_the_body() {
|
||||
let body = body(&SearchOptions::default());
|
||||
assert!(body.get("api_key").is_none(), "{body}");
|
||||
assert!(!body.to_string().contains("test-key"), "{body}");
|
||||
}
|
||||
}
|
||||
206
crates/luxe-tools/src/test_baseline.rs
Normal file
206
crates/luxe-tools/src/test_baseline.rs
Normal file
@@ -0,0 +1,206 @@
|
||||
//! Test baseline — what was failing last time, so this run can name what changed.
|
||||
//!
|
||||
//! A pass/fail count answers "is it green?" and hides the question that actually matters after an
|
||||
//! edit: *did I break something that used to work?* Agents introduce regressions at a rate the
|
||||
//! benchmarks mostly don't measure, because a suite that was already red stays red and a newly-red
|
||||
//! test looks identical to an old one in a raw runner dump.
|
||||
//!
|
||||
//! So each unfiltered run records the set of failing test names, and the next run of the same
|
||||
//! command diffs against it. Filtered runs read the baseline but never write it — a subset that
|
||||
//! passes is not evidence the suite is green, and letting it overwrite the record would erase the
|
||||
//! very failures it skipped.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// What one recorded run remembers.
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
struct Baseline {
|
||||
/// Failing test names from the last full run of this command.
|
||||
failing: BTreeSet<String>,
|
||||
passed: usize,
|
||||
failed: usize,
|
||||
}
|
||||
|
||||
/// The whole store: one baseline per command.
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
struct Store {
|
||||
runs: std::collections::BTreeMap<String, Baseline>,
|
||||
}
|
||||
|
||||
/// What changed between the previous run and this one.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct Delta {
|
||||
/// Tests failing now that passed before — regressions, the thing worth interrupting for.
|
||||
pub(crate) broke: Vec<String>,
|
||||
/// Tests passing now that failed before.
|
||||
pub(crate) fixed: Vec<String>,
|
||||
/// Whether a previous run of this command was on record at all.
|
||||
pub(crate) had_baseline: bool,
|
||||
}
|
||||
|
||||
impl Delta {
|
||||
/// Whether there is anything worth saying.
|
||||
pub(crate) fn is_interesting(&self) -> bool {
|
||||
!self.broke.is_empty() || !self.fixed.is_empty()
|
||||
}
|
||||
|
||||
/// The delta as a line for the model, or `None` when nothing moved.
|
||||
///
|
||||
/// Regressions lead, because they are the finding: everything else in the reply is about the
|
||||
/// change that was intended, and this is the part that wasn't.
|
||||
pub(crate) fn render(&self) -> Option<String> {
|
||||
if !self.is_interesting() {
|
||||
return None;
|
||||
}
|
||||
let mut out = String::new();
|
||||
if !self.broke.is_empty() {
|
||||
out.push_str(&format!(
|
||||
"REGRESSION — {} test(s) passed before this change and fail now:\n",
|
||||
self.broke.len()
|
||||
));
|
||||
for name in self.broke.iter().take(MAX_LISTED) {
|
||||
out.push_str(&format!(" - {name}\n"));
|
||||
}
|
||||
if self.broke.len() > MAX_LISTED {
|
||||
out.push_str(&format!(" … and {} more\n", self.broke.len() - MAX_LISTED));
|
||||
}
|
||||
}
|
||||
if !self.fixed.is_empty() {
|
||||
out.push_str(&format!("Fixed since the last run: {}\n", self.fixed.len()));
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Most test names listed before the rest is counted.
|
||||
const MAX_LISTED: usize = 10;
|
||||
|
||||
/// Compare this run against the recorded one, and record it when the run was unfiltered.
|
||||
///
|
||||
/// `filtered` runs are read-only against the store: a passing subset says nothing about the tests
|
||||
/// it never executed.
|
||||
pub(crate) fn diff_and_record(
|
||||
cwd: &Path,
|
||||
command: &str,
|
||||
failing: &BTreeSet<String>,
|
||||
passed: usize,
|
||||
failed: usize,
|
||||
filtered: bool,
|
||||
) -> Delta {
|
||||
let path = store_path(cwd);
|
||||
let mut store = load(&path);
|
||||
|
||||
let delta = match store.runs.get(command) {
|
||||
Some(previous) => Delta {
|
||||
broke: failing.difference(&previous.failing).cloned().collect(),
|
||||
fixed: previous.failing.difference(failing).cloned().collect(),
|
||||
had_baseline: true,
|
||||
},
|
||||
None => Delta::default(),
|
||||
};
|
||||
|
||||
if !filtered {
|
||||
store
|
||||
.runs
|
||||
.insert(command.to_string(), Baseline { failing: failing.clone(), passed, failed });
|
||||
save(&path, &store);
|
||||
}
|
||||
|
||||
delta
|
||||
}
|
||||
|
||||
fn store_path(cwd: &Path) -> PathBuf {
|
||||
cwd.join(".luxe").join("test-baseline.json")
|
||||
}
|
||||
|
||||
fn load(path: &Path) -> Store {
|
||||
std::fs::read_to_string(path)
|
||||
.ok()
|
||||
.and_then(|raw| serde_json::from_str(&raw).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Best-effort persistence: losing a baseline costs one run's delta, never the run itself.
|
||||
fn save(path: &Path, store: &Store) {
|
||||
let Some(parent) = path.parent() else { return };
|
||||
if std::fs::create_dir_all(parent).is_err() {
|
||||
return;
|
||||
}
|
||||
if let Ok(encoded) = serde_json::to_string_pretty(store) {
|
||||
let _ = std::fs::write(path, encoded);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn names(list: &[&str]) -> BTreeSet<String> {
|
||||
list.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_newly_failing_test_is_reported_as_a_regression() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
let cmd = "pytest";
|
||||
|
||||
diff_and_record(dir.path(), cmd, &names(&["test_old"]), 5, 1, false);
|
||||
let delta =
|
||||
diff_and_record(dir.path(), cmd, &names(&["test_old", "test_new"]), 4, 2, false);
|
||||
|
||||
assert_eq!(delta.broke, vec!["test_new".to_string()], "only the new one is a regression");
|
||||
assert!(delta.fixed.is_empty());
|
||||
let rendered = delta.render().expect("something to say");
|
||||
assert!(rendered.starts_with("REGRESSION"), "{rendered}");
|
||||
assert!(rendered.contains("test_new"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_test_that_starts_passing_is_reported_as_fixed() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
diff_and_record(dir.path(), "pytest", &names(&["a", "b"]), 0, 2, false);
|
||||
let delta = diff_and_record(dir.path(), "pytest", &names(&["a"]), 1, 1, false);
|
||||
|
||||
assert_eq!(delta.fixed, vec!["b".to_string()]);
|
||||
assert!(delta.broke.is_empty());
|
||||
assert!(delta.render().expect("something to say").contains("Fixed since the last run: 1"));
|
||||
}
|
||||
|
||||
/// A green subset is not evidence the suite is green, so it must not overwrite the record of
|
||||
/// the failures it never ran.
|
||||
#[test]
|
||||
fn a_filtered_run_reads_the_baseline_but_never_replaces_it() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
diff_and_record(dir.path(), "pytest", &names(&["broken_one"]), 3, 1, false);
|
||||
|
||||
// A filtered run that touched only the healthy tests.
|
||||
diff_and_record(dir.path(), "pytest", &BTreeSet::new(), 1, 0, true);
|
||||
|
||||
// The known failure is still on record, so it is not reported as "fixed" next time.
|
||||
let delta = diff_and_record(dir.path(), "pytest", &names(&["broken_one"]), 3, 1, false);
|
||||
assert!(delta.broke.is_empty(), "still failing, not a new break");
|
||||
assert!(delta.fixed.is_empty(), "and never wrongly credited as fixed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_commands_keep_separate_baselines() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
diff_and_record(dir.path(), "pytest unit", &names(&["u1"]), 1, 1, false);
|
||||
let delta = diff_and_record(dir.path(), "pytest integration", &names(&["i1"]), 1, 1, false);
|
||||
|
||||
assert!(!delta.had_baseline, "a different suite is not a baseline for this one");
|
||||
assert!(delta.broke.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_run_reports_nothing_to_compare() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
let delta = diff_and_record(dir.path(), "pytest", &names(&["a"]), 0, 1, false);
|
||||
|
||||
assert!(!delta.had_baseline);
|
||||
assert!(delta.render().is_none(), "nothing moved because nothing came before");
|
||||
}
|
||||
}
|
||||
349
crates/luxe-tools/src/test_runner.rs
Normal file
349
crates/luxe-tools/src/test_runner.rs
Normal file
@@ -0,0 +1,349 @@
|
||||
//! `test` tool — run the project's tests and return a structured pass/fail summary.
|
||||
//!
|
||||
//! Auto-detects the test command from project markers (Cargo.toml, go.mod, pyproject/pytest,
|
||||
//! package.json) — preferring the environment the *project* pinned over whatever shares its name on
|
||||
//! `PATH` — or takes an explicit `command`, runs it, and parses the output into a compact
|
||||
//! `framework: verdict — N passed, M failed` summary with failing names + file:line (via the shared
|
||||
//! [`luxe_core::compression`] test reducer), saving the untouched output under `.luxe/artifacts/`
|
||||
//! as `bash` does. Unlike `bash "cargo test"`, this always renders the structured summary (even for
|
||||
//! a small passing run) and figures out the command for you.
|
||||
|
||||
use async_trait::async_trait;
|
||||
use luxe_core::compression::{
|
||||
compress, parse_test_output, CommandInvocation, CommandOutput, CompressionConfig,
|
||||
ReducerRegistry,
|
||||
};
|
||||
use luxe_core::{ContentBlock, Tool, ToolContext, ToolResultData, ToolSchema};
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
mod detect;
|
||||
mod shell;
|
||||
|
||||
use detect::*;
|
||||
use shell::{run_shell, ShellResult};
|
||||
|
||||
/// Default test timeout (tests can be slow: builds + suites).
|
||||
const DEFAULT_TIMEOUT_SECS: u64 = 300;
|
||||
|
||||
/// Ceiling on the model-supplied `timeout`, in seconds (one hour).
|
||||
///
|
||||
/// Higher than any real suite needs, and low enough that a runaway is still bounded. See
|
||||
/// `bash`'s equivalent: the argument is honored because the model knows which run is slow, and
|
||||
/// clamped because it is also the one number that can remove the safety net.
|
||||
const MAX_TIMEOUT_SECS: u64 = 3_600;
|
||||
|
||||
/// The detected/overridden runner, so we can apply a filter with the right flag.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Framework {
|
||||
Cargo,
|
||||
Go,
|
||||
Pytest,
|
||||
Node,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct TestTool;
|
||||
|
||||
impl TestTool {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for TestTool {
|
||||
fn name(&self) -> &str {
|
||||
"test"
|
||||
}
|
||||
|
||||
/// No engine-side deadline: like `bash`, this tool spawns its suite as its own process group and
|
||||
/// kills the tree itself. A test run is also the one call that legitimately outlasts every
|
||||
/// harness-wide bound — a cold `cargo test` on a large workspace is minutes of compilation
|
||||
/// before a single test runs.
|
||||
fn timeout(&self) -> Option<Duration> {
|
||||
None
|
||||
}
|
||||
|
||||
fn schema(&self) -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: "test".to_string(),
|
||||
description: "Run the project's tests and return a structured summary: counts, each \
|
||||
failing test with its file:line and message, and which tests were \
|
||||
passing before your change and fail now. Auto-detects the command from project markers (Cargo.toml→cargo \
|
||||
test/nextest, go.mod→go test, pyproject/pytest→pytest, package.json→the \
|
||||
manifest's test script) and runs it in the environment the project \
|
||||
pinned — its virtualenv, its package manager — rather than whatever \
|
||||
shares the name on PATH; `command` overrides. Output is saved to \
|
||||
.luxe/artifacts/ (each stream whole up to 8 MB, its first and \
|
||||
last 4 MB past that). Prefer this over `bash` for running tests.\n\
|
||||
Before calling work done, run every test that covers what you \
|
||||
changed: the full suite when it is quick, and when it is not (a large \
|
||||
project's can take many minutes) the modules around your change. \
|
||||
`filter` is for iterating on one failure, and a filtered run proves \
|
||||
nothing about the tests it skipped."
|
||||
.to_string(),
|
||||
parameters: json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"command": {
|
||||
"type": "string",
|
||||
"description": "Full test command to run (overrides auto-detection), e.g. `cargo nextest run -p mycrate`"
|
||||
},
|
||||
"filter": {
|
||||
"type": "string",
|
||||
"description": "Only run tests matching this name/substring (applied with the framework's filter flag)"
|
||||
},
|
||||
"timeout": {
|
||||
"type": "integer",
|
||||
"description": "Timeout in seconds (default 300)"
|
||||
}
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(&self, args: serde_json::Value, cx: &ToolContext) -> ToolResultData {
|
||||
// A strict-schema model sends `filter: ""` for no filter, which read as a filtered run and
|
||||
// drew the warning that it proved nothing
|
||||
let filter = args.get("filter").and_then(|v| v.as_str()).filter(|f| !f.trim().is_empty());
|
||||
let (command, framework) = match resolve_command(&args, &cx.cwd) {
|
||||
Ok(resolved) => resolved,
|
||||
Err(message) => return ToolResultData::error(format!("Error: {}", message)),
|
||||
};
|
||||
let command = apply_filter(&command, framework, filter, crate::process::posix_shell());
|
||||
let timeout = Duration::from_secs(
|
||||
args.get("timeout")
|
||||
.and_then(|v| v.as_u64())
|
||||
.filter(|secs| *secs > 0)
|
||||
.unwrap_or(DEFAULT_TIMEOUT_SECS)
|
||||
.min(MAX_TIMEOUT_SECS),
|
||||
);
|
||||
let output = match run_shell(&command, &cx.cwd, timeout).await {
|
||||
Ok(output) => output,
|
||||
Err(message) => return ToolResultData::error(format!("Error: {}", message)),
|
||||
};
|
||||
let run = Run { command: &command, framework, filter, output: &output };
|
||||
let summary = summarize(&run, &cx.cwd);
|
||||
ToolResultData {
|
||||
content: vec![ContentBlock::Text(compose_reply(&run, &cx.cwd, summary))],
|
||||
is_error: !output.success,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The command to run: the caller's, or the one the project's markers name.
|
||||
fn resolve_command(args: &serde_json::Value, cwd: &Path) -> Result<(String, Framework), String> {
|
||||
match args.get("command").and_then(|v| v.as_str()) {
|
||||
Some(explicit) => Ok((explicit.to_string(), classify_command(explicit))),
|
||||
None => detect_command(cwd).map(|detected| (detected.command, detected.framework)),
|
||||
}
|
||||
}
|
||||
|
||||
/// One finished run, as the reply is written from it.
|
||||
struct Run<'a> {
|
||||
command: &'a str,
|
||||
framework: Framework,
|
||||
filter: Option<&'a str>,
|
||||
output: &'a ShellResult,
|
||||
}
|
||||
|
||||
/// What a run comes to: its rendered body, the regressions since the last run, and whether it ran
|
||||
/// anything at all.
|
||||
struct Summary {
|
||||
body: String,
|
||||
delta_note: Option<String>,
|
||||
ran_nothing: bool,
|
||||
}
|
||||
|
||||
/// The structured summary for a recognized runner; otherwise the generic compression, so output
|
||||
/// isn't lost.
|
||||
fn summarize(run: &Run<'_>, cwd: &Path) -> Summary {
|
||||
let output = run.output;
|
||||
let Some(summary) = parse_test_output(&output.stdout, &output.stderr) else {
|
||||
let captured = CommandOutput {
|
||||
stdout: output.stdout.clone(),
|
||||
stderr: output.stderr.clone(),
|
||||
exit_code: output.exit_code,
|
||||
};
|
||||
let invocation = CommandInvocation::parse(run.command);
|
||||
let config = CompressionConfig::default();
|
||||
return Summary {
|
||||
body: compress(&invocation, &captured, &config, &ReducerRegistry::new()).output,
|
||||
delta_note: None,
|
||||
ran_nothing: executed_nothing(&output.stdout, &output.stderr),
|
||||
};
|
||||
};
|
||||
// A count answers "is it green?". After an edit the live question is "did I break something
|
||||
// that worked?", and only a diff against the last run answers that.
|
||||
let failing: std::collections::BTreeSet<String> =
|
||||
summary.failures.iter().map(|f| f.name.clone()).collect();
|
||||
let delta_note = crate::test_baseline::diff_and_record(
|
||||
cwd,
|
||||
run.command,
|
||||
&failing,
|
||||
summary.passed,
|
||||
summary.failed,
|
||||
run.filter.is_some(),
|
||||
)
|
||||
.render();
|
||||
Summary {
|
||||
ran_nothing: summary.passed == 0 && summary.failed == 0 && summary.ignored == 0,
|
||||
body: summary.render(),
|
||||
delta_note,
|
||||
}
|
||||
}
|
||||
|
||||
/// The reply: the command, its regressions first, the capped body, and every note that applies.
|
||||
fn compose_reply(run: &Run<'_>, cwd: &Path, summary: Summary) -> String {
|
||||
let output = run.output;
|
||||
// Teed before the cap, because the cap's hint has to name what actually happened: no artifact
|
||||
// on a read-only tree or a full disk
|
||||
let streams = (output.stdout.as_str(), output.stderr.as_str(), output.exit_code);
|
||||
let artifact = crate::process::tee_artifact(cwd, "test", run.command, streams);
|
||||
// A broken suite is the case that produces the most output: the first failures reveal the
|
||||
// pattern, the rest repeat it, and the untouched run is on disk
|
||||
let hint = match &artifact {
|
||||
Some(path) => format!("Fix these first. Saved run: {}", luxe_core::paths::display(path)),
|
||||
None => "Fix these first, then run again — or pass `filter` to narrow the run.".to_string(),
|
||||
};
|
||||
let body = crate::output_limit::cap_lines(&summary.body, TEST_MAX_LINES, "lines", &hint);
|
||||
// The regression note leads: it is the one part of the reply a reader must not scroll past.
|
||||
let command = run.command;
|
||||
let mut text = match &summary.delta_note {
|
||||
Some(note) => format!("$ {command}\n{note}{body}"),
|
||||
None => format!("$ {command}\n{body}"),
|
||||
};
|
||||
if summary.ran_nothing {
|
||||
text.push_str(&format!(
|
||||
"\n\nNo tests actually ran{} — that is not a green suite, whatever the exit code \
|
||||
says. Check the path or filter you passed.",
|
||||
run.filter.map(|f| format!(" (filter: `{f}`)")).unwrap_or_default()
|
||||
));
|
||||
}
|
||||
if let Some(active) = run.filter {
|
||||
text.push_str(&format!(
|
||||
"\n\nThis run was filtered to `{active}` — it says nothing about the tests it \
|
||||
skipped. Run everything your change touches before calling the work done."
|
||||
));
|
||||
}
|
||||
if let Some(note) = foreign_interpreter_note(cwd, command, run.framework, output) {
|
||||
text.push_str(&format!("\n\n{note}"));
|
||||
}
|
||||
if let Some(path) = &artifact {
|
||||
text.push_str(&format!("\n\nFull output: {}", luxe_core::paths::display(path)));
|
||||
}
|
||||
if output.detached_writer {
|
||||
text.push_str(crate::process::DETACHED_WRITER_NOTE);
|
||||
}
|
||||
text.push_str(&format!("\n\nExit code: {}", output.exit_code.unwrap_or(-1)));
|
||||
text
|
||||
}
|
||||
|
||||
/// Whether a run selected no tests at all, for output the summary parsers don't recognize.
|
||||
///
|
||||
/// Every runner reports an empty selection quietly and exits 0 for it, so "1 deselected" reads as
|
||||
/// success to anyone skimming the exit code — including a model that just filtered by a name it
|
||||
/// guessed slightly wrong.
|
||||
fn executed_nothing(stdout: &str, stderr: &str) -> bool {
|
||||
const EMPTY_RUN: [&str; 6] = [
|
||||
"no tests ran",
|
||||
"no tests collected",
|
||||
"collected 0 items",
|
||||
"no test files",
|
||||
"no tests found",
|
||||
"0 tests run",
|
||||
];
|
||||
let haystack = format!("{stdout}\n{stderr}").to_ascii_lowercase();
|
||||
if EMPTY_RUN.iter().any(|needle| haystack.contains(needle)) {
|
||||
return true;
|
||||
}
|
||||
// pytest's deselect line: "N deselected" with nothing selected alongside it.
|
||||
haystack.contains("deselected")
|
||||
&& !haystack.contains(" passed")
|
||||
&& !haystack.contains(" failed")
|
||||
}
|
||||
|
||||
/// Most rendered lines a test run returns before the rest defers to the artifact file.
|
||||
const TEST_MAX_LINES: usize = 120;
|
||||
|
||||
/// Whether a program can be run, injected so detection is decidable without the host's `PATH`.
|
||||
type Available<'a> = &'a dyn Fn(&str) -> bool;
|
||||
|
||||
/// A note for a pytest run that died on an import under an interpreter that is not the project's.
|
||||
///
|
||||
/// Only reachable when the caller passed `command` itself — detection prefers the environment — and
|
||||
/// that is exactly when it is needed, because the traceback names a missing plugin and says nothing
|
||||
/// about the interpreter that was missing it.
|
||||
fn foreign_interpreter_note(
|
||||
cwd: &Path,
|
||||
command: &str,
|
||||
framework: Framework,
|
||||
output: &ShellResult,
|
||||
) -> Option<String> {
|
||||
if framework != Framework::Pytest || output.success {
|
||||
return None;
|
||||
}
|
||||
if !format!("{}\n{}", output.stdout, output.stderr).contains("No module named") {
|
||||
return None;
|
||||
}
|
||||
if ["uv run", "poetry run", "pipenv run", "pdm run", "hatch run", "tox"]
|
||||
.iter()
|
||||
.any(|runner| command.contains(runner))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let venv = luxe_core::program::project_venv(cwd)?;
|
||||
let python = luxe_core::program::venv_program(&venv, "python")?;
|
||||
let interpreter = shell_word(cwd, &python);
|
||||
if command.contains(&interpreter) {
|
||||
return None;
|
||||
}
|
||||
Some(format!(
|
||||
"That ran outside `{}`, which is where this project's dependencies are installed — a missing \
|
||||
module is the symptom. Retry with `command: \"{interpreter} -m pytest\"`.",
|
||||
shell_word(cwd, &venv)
|
||||
))
|
||||
}
|
||||
|
||||
/// Best-effort framework classification of an explicit command (for filter flag selection).
|
||||
fn classify_command(command: &str) -> Framework {
|
||||
let lower = command.to_ascii_lowercase();
|
||||
if lower.contains("cargo") {
|
||||
Framework::Cargo
|
||||
} else if lower.contains("go test") {
|
||||
Framework::Go
|
||||
} else if lower.contains("pytest") {
|
||||
Framework::Pytest
|
||||
} else if ["jest", "vitest", "mocha", "npm", "pnpm", "yarn", "bun", "deno"]
|
||||
.iter()
|
||||
.any(|runner| lower.contains(runner))
|
||||
{
|
||||
Framework::Node
|
||||
} else {
|
||||
Framework::Unknown
|
||||
}
|
||||
}
|
||||
|
||||
/// Append a name filter using the framework's flag, quoted as one argument for the shell that
|
||||
/// runs it.
|
||||
///
|
||||
/// The filter is one value, and pytest's `-k "a or b"` is the ordinary case: pasted in raw, a space
|
||||
/// split it and a `;` ran whatever followed.
|
||||
fn apply_filter(command: &str, framework: Framework, filter: Option<&str>, posix: bool) -> String {
|
||||
let Some(filter) = filter.filter(|f| !f.is_empty()) else {
|
||||
return command.to_string();
|
||||
};
|
||||
let filter = crate::process::quote_argument(filter, posix);
|
||||
match framework {
|
||||
Framework::Cargo | Framework::Unknown => format!("{command} {filter}"),
|
||||
Framework::Go => format!("{command} -run {filter}"),
|
||||
Framework::Pytest => format!("{command} -k {filter}"),
|
||||
Framework::Node => format!("{command} -- {filter}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
186
crates/luxe-tools/src/test_runner/detect.rs
Normal file
186
crates/luxe-tools/src/test_runner/detect.rs
Normal file
@@ -0,0 +1,186 @@
|
||||
//! Detection — which test command a project runs, and how its package manager says so.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// What detection settled on.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Detected {
|
||||
pub(super) command: String,
|
||||
pub(super) framework: Framework,
|
||||
}
|
||||
|
||||
impl Detected {
|
||||
fn new(command: impl Into<String>, framework: Framework) -> Self {
|
||||
Self { command: command.into(), framework }
|
||||
}
|
||||
}
|
||||
|
||||
/// Detect the project's test command from marker files.
|
||||
///
|
||||
/// `Err` is a message for the model: either there is no project here to detect, or there is one
|
||||
/// whose manifest declares no way to test it — and saying which beats running a command that was
|
||||
/// never going to work.
|
||||
pub(super) fn detect_command(cwd: &Path) -> Result<Detected, String> {
|
||||
detect_with(cwd, &|program| luxe_core::program::resolve(program).is_some())
|
||||
}
|
||||
|
||||
pub(super) fn detect_with(cwd: &Path, available: Available) -> Result<Detected, String> {
|
||||
if cwd.join("Cargo.toml").exists() {
|
||||
let base = if available("cargo-nextest") { "cargo nextest run" } else { "cargo test" };
|
||||
return Ok(Detected::new(base, Framework::Cargo));
|
||||
}
|
||||
if cwd.join("go.mod").exists() {
|
||||
// `-v` because go otherwise prints nothing for a test that passed: a green suite came back
|
||||
// as `0 passed, 0 failed`, which this tool then reported as "no tests actually ran".
|
||||
return Ok(Detected::new("go test -v ./...", Framework::Go));
|
||||
}
|
||||
if ["pyproject.toml", "setup.py", "pytest.ini", "tox.ini", "setup.cfg"]
|
||||
.iter()
|
||||
.any(|f| cwd.join(f).exists())
|
||||
{
|
||||
return Ok(Detected::new(python_command(cwd, available), Framework::Pytest));
|
||||
}
|
||||
if cwd.join("package.json").exists() {
|
||||
return node_command(cwd, available);
|
||||
}
|
||||
Err("Could not detect a test command (no Cargo.toml / go.mod / pyproject.toml / \
|
||||
package.json). Pass `command` explicitly."
|
||||
.to_string())
|
||||
}
|
||||
|
||||
/// How to run pytest for the project at `cwd`.
|
||||
///
|
||||
/// Python's convention is one environment per project, so a global `pytest` is not a slightly worse
|
||||
/// choice than the project's — it is a *different* project's interpreter, with none of this one's
|
||||
/// dependencies on its path, and the failure it produces blames the suite. The environment is
|
||||
/// driven through its interpreter rather than its `pytest` shim because `-m` also puts `cwd` on
|
||||
/// `sys.path`, which is what a project whose own package is not installed needs.
|
||||
pub(super) fn python_command(cwd: &Path, available: Available) -> String {
|
||||
let venv = luxe_core::program::project_venv(cwd);
|
||||
let installed = venv
|
||||
.as_deref()
|
||||
.filter(|venv| luxe_core::program::venv_program(venv, "pytest").is_some())
|
||||
.and_then(|venv| venv_pytest(cwd, venv));
|
||||
if let Some(command) = installed {
|
||||
return command;
|
||||
}
|
||||
// Nothing to run in the environment yet, but the manager that owns it can install what its
|
||||
// lock file pins. A global pytest cannot.
|
||||
if let Some(runner) = python_manager(cwd, available) {
|
||||
return format!("{runner} run pytest");
|
||||
}
|
||||
if let Some(command) = venv.as_deref().and_then(|venv| venv_pytest(cwd, venv)) {
|
||||
// Still the project's interpreter: `no module named pytest` names the real problem, where a
|
||||
// global run reports a missing dependency and points at the wrong thing entirely.
|
||||
return command;
|
||||
}
|
||||
if available("pytest") {
|
||||
return "pytest".to_string();
|
||||
}
|
||||
let python = if available("python3") { "python3" } else { "python" };
|
||||
format!("{python} -m pytest")
|
||||
}
|
||||
|
||||
/// `pytest` run through the interpreter of the environment at `venv`.
|
||||
pub(super) fn venv_pytest(cwd: &Path, venv: &Path) -> Option<String> {
|
||||
let python = luxe_core::program::venv_program(venv, "python")?;
|
||||
Some(format!("{} -m pytest", shell_word(cwd, &python)))
|
||||
}
|
||||
|
||||
/// The dependency manager that owns this project's environment, if it is installed.
|
||||
///
|
||||
/// A lock file is the marker rather than a `pyproject.toml` section, because the lock is what says
|
||||
/// the manager really runs here — and `<manager> run` is what a human in this repository types.
|
||||
pub(super) fn python_manager(cwd: &Path, available: Available) -> Option<&'static str> {
|
||||
[("uv.lock", "uv"), ("poetry.lock", "poetry"), ("Pipfile.lock", "pipenv")]
|
||||
.into_iter()
|
||||
.find(|(lock, runner)| cwd.join(lock).exists() && available(runner))
|
||||
.map(|(_, runner)| runner)
|
||||
}
|
||||
|
||||
/// Lock file, program, and the words that run one of its scripts, most specific first.
|
||||
pub(super) const NODE_MANAGERS: [(&str, &str, &str); 6] = [
|
||||
("pnpm-lock.yaml", "pnpm", "pnpm test"),
|
||||
("yarn.lock", "yarn", "yarn test"),
|
||||
("bun.lockb", "bun", "bun run test"),
|
||||
("bun.lock", "bun", "bun run test"),
|
||||
("package-lock.json", "npm", "npm test"),
|
||||
("npm-shrinkwrap.json", "npm", "npm test"),
|
||||
];
|
||||
|
||||
/// How to run the tests of a JavaScript project.
|
||||
///
|
||||
/// The manifest is consulted rather than assumed: `npm test` against a project that declares no
|
||||
/// `test` script fails with `Missing script: "test"`, which reads as a broken tool. A manifest we
|
||||
/// cannot parse is npm's error to report, not ours, so that case still runs.
|
||||
pub(super) fn node_command(cwd: &Path, available: Available) -> Result<Detected, String> {
|
||||
let manager = node_manager(cwd, available);
|
||||
let Some(manifest) = std::fs::read_to_string(cwd.join("package.json"))
|
||||
.ok()
|
||||
.and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
|
||||
else {
|
||||
return Ok(Detected::new(manager, Framework::Node));
|
||||
};
|
||||
let declared = manifest
|
||||
.get("scripts")
|
||||
.and_then(|scripts| scripts.get("test"))
|
||||
.and_then(|script| script.as_str())
|
||||
.is_some_and(|script| !script.trim().is_empty());
|
||||
if declared {
|
||||
return Ok(Detected::new(manager, Framework::Node));
|
||||
}
|
||||
Err(missing_test_script(&manifest, manager))
|
||||
}
|
||||
|
||||
/// The package manager this project is installed with, as the words that run one of its scripts.
|
||||
///
|
||||
/// The lock file is the project's own statement of which manager it uses, and it decides more than
|
||||
/// style: a pnpm workspace's dependencies are not linked the way npm expects to find them.
|
||||
pub(super) fn node_manager(cwd: &Path, available: Available) -> &'static str {
|
||||
NODE_MANAGERS
|
||||
.iter()
|
||||
.find(|(lock, program, _)| cwd.join(lock).exists() && available(program))
|
||||
.map(|(_, _, run)| *run)
|
||||
.or_else(|| available("npm").then_some("npm test"))
|
||||
.or_else(|| {
|
||||
NODE_MANAGERS.iter().find(|(_, program, _)| available(program)).map(|(_, _, run)| *run)
|
||||
})
|
||||
.unwrap_or("npm test")
|
||||
}
|
||||
|
||||
/// Refusal for a JavaScript project whose manifest declares no test script.
|
||||
///
|
||||
/// Naming the runner already in its dependencies turns a dead end into a command the caller can
|
||||
/// pass. `npx` regardless of manager: it resolves `node_modules/.bin` the same way in all of them.
|
||||
pub(super) fn missing_test_script(manifest: &serde_json::Value, manager: &str) -> String {
|
||||
let depends_on = |name: &str| {
|
||||
["devDependencies", "dependencies"]
|
||||
.iter()
|
||||
.any(|section| manifest.get(section).and_then(|deps| deps.get(name)).is_some())
|
||||
};
|
||||
let suggestion = [("vitest", "npx vitest run"), ("jest", "npx jest"), ("mocha", "npx mocha")]
|
||||
.into_iter()
|
||||
.find(|(name, _)| depends_on(name));
|
||||
match suggestion {
|
||||
Some((name, command)) => format!(
|
||||
"package.json declares no `test` script, so `{manager}` would fail on that rather than \
|
||||
on your tests. This project depends on {name} — pass `command: \"{command}\"` (the \
|
||||
`run` matters: a bare watcher never exits), or add a `test` script."
|
||||
),
|
||||
None => format!(
|
||||
"package.json declares no `test` script, so `{manager}` would fail on that rather than \
|
||||
on your tests. Add one, or pass `command` with the runner this project uses."
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// A path as one shell word: relative to `cwd` when it is inside it, forward slashes, quoted only
|
||||
/// when it has to be.
|
||||
pub(super) fn shell_word(cwd: &Path, path: &Path) -> String {
|
||||
let rendered = luxe_core::paths::display(path.strip_prefix(cwd).unwrap_or(path));
|
||||
if rendered.contains(char::is_whitespace) {
|
||||
format!("\"{rendered}\"")
|
||||
} else {
|
||||
rendered
|
||||
}
|
||||
}
|
||||
36
crates/luxe-tools/src/test_runner/shell.rs
Normal file
36
crates/luxe-tools/src/test_runner/shell.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
//! Shell — how a test command runs, and what comes back.
|
||||
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Captured shell result.
|
||||
pub(super) struct ShellResult {
|
||||
pub(super) stdout: String,
|
||||
pub(super) stderr: String,
|
||||
pub(super) exit_code: Option<i32>,
|
||||
pub(super) success: bool,
|
||||
/// The shell exited while something it started still held the output pipe
|
||||
pub(super) detached_writer: bool,
|
||||
}
|
||||
|
||||
/// Runs `command` through [`crate::process`], the runner `bash` uses: its own process group,
|
||||
/// killed whole on a timeout or a cancel, output bounded.
|
||||
pub(super) async fn run_shell(
|
||||
command: &str,
|
||||
cwd: &Path,
|
||||
timeout: Duration,
|
||||
) -> Result<ShellResult, String> {
|
||||
match crate::process::run_captured(command, cwd, timeout).await {
|
||||
Ok(crate::process::Outcome::Finished(output)) => Ok(ShellResult {
|
||||
exit_code: output.status.code(),
|
||||
success: output.status.success(),
|
||||
stdout: output.stdout,
|
||||
stderr: output.stderr,
|
||||
detached_writer: output.detached_writer,
|
||||
}),
|
||||
Ok(crate::process::Outcome::TimedOut(_)) => {
|
||||
Err(format!("tests timed out after {}s", timeout.as_secs()))
|
||||
}
|
||||
Err(error) => Err(format!("could not run the test command: {error}")),
|
||||
}
|
||||
}
|
||||
372
crates/luxe-tools/src/test_runner/tests.rs
Normal file
372
crates/luxe-tools/src/test_runner/tests.rs
Normal file
@@ -0,0 +1,372 @@
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
fn test_context(tmp_dir: &std::path::Path) -> ToolContext {
|
||||
let (event_tx, _event_rx) = mpsc::channel(64);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
ToolContext {
|
||||
cwd: tmp_dir.to_path_buf(),
|
||||
session_id: "test-session".to_string(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Nothing is installed, so a detection test says what the *project* implies and nothing about
|
||||
/// the machine it runs on.
|
||||
fn nothing_installed(_: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// A virtualenv laid out the way the platform lays one out.
|
||||
fn write_venv(root: &Path, name: &str, programs: &[&str]) -> PathBuf {
|
||||
let bin = root.join(name).join(if cfg!(windows) { "Scripts" } else { "bin" });
|
||||
std::fs::create_dir_all(&bin).expect("mkdir");
|
||||
for program in programs {
|
||||
let path =
|
||||
bin.join(if cfg!(windows) { format!("{program}.exe") } else { (*program).to_string() });
|
||||
std::fs::write(&path, "#!/bin/sh\nexit 0\n").expect("write");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mut perms = std::fs::metadata(&path).expect("metadata").permissions();
|
||||
perms.set_mode(0o755);
|
||||
std::fs::set_permissions(&path, perms).expect("chmod");
|
||||
}
|
||||
}
|
||||
root.join(name)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_cargo_project() {
|
||||
let tmp = tempfile::tempdir().expect("temp dir");
|
||||
std::fs::write(tmp.path().join("Cargo.toml"), "[package]").unwrap();
|
||||
let detected = detect_command(tmp.path()).expect("a cargo project");
|
||||
assert!(detected.command.starts_with("cargo"), "{}", detected.command);
|
||||
assert_eq!(detected.framework, Framework::Cargo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_markers_no_detection() {
|
||||
let tmp = tempfile::tempdir().expect("temp dir");
|
||||
assert!(detect_command(tmp.path()).is_err());
|
||||
}
|
||||
|
||||
/// The defect this ladder exists for: a project with its own environment had its tests run by
|
||||
/// the interpreter on `PATH`, which is a different installation with none of its dependencies.
|
||||
#[test]
|
||||
fn a_python_project_is_tested_by_its_own_environment() {
|
||||
let project = tempfile::tempdir().expect("temp dir");
|
||||
std::fs::write(project.path().join("pyproject.toml"), "[project]").expect("write");
|
||||
write_venv(project.path(), ".venv", &["python", "pytest"]);
|
||||
|
||||
// `pytest` is on this PATH as far as detection can tell, and must still lose.
|
||||
let detected = detect_with(project.path(), &|_| true).expect("a python project");
|
||||
assert_eq!(detected.framework, Framework::Pytest);
|
||||
assert!(
|
||||
detected.command.starts_with(".venv/") && detected.command.ends_with("-m pytest"),
|
||||
"the project's interpreter, not the one on PATH: {}",
|
||||
detected.command
|
||||
);
|
||||
}
|
||||
|
||||
/// An environment with nothing in it yet: the manager holding the lock file can fix that.
|
||||
#[test]
|
||||
fn a_locked_project_runs_through_the_manager_that_owns_its_environment() {
|
||||
let project = tempfile::tempdir().expect("temp dir");
|
||||
std::fs::write(project.path().join("pyproject.toml"), "[project]").expect("write");
|
||||
std::fs::write(project.path().join("uv.lock"), "version = 1").expect("write");
|
||||
|
||||
assert_eq!(
|
||||
detect_with(project.path(), &|program| program == "uv").expect("detected").command,
|
||||
"uv run pytest"
|
||||
);
|
||||
// Not installed is not a suggestion: fall through rather than name a program that is absent.
|
||||
let without = detect_with(project.path(), ¬hing_installed).expect("detected").command;
|
||||
assert!(!without.contains("uv"), "{without}");
|
||||
}
|
||||
|
||||
/// A missing pytest is reported by the interpreter that would have imported it, not by a
|
||||
/// stranger.
|
||||
#[test]
|
||||
fn an_environment_without_pytest_still_beats_a_global_one() {
|
||||
let project = tempfile::tempdir().expect("temp dir");
|
||||
std::fs::write(project.path().join("pyproject.toml"), "[project]").expect("write");
|
||||
write_venv(project.path(), ".venv", &["python"]);
|
||||
|
||||
let detected = detect_with(project.path(), &|_| true).expect("a python project");
|
||||
assert!(detected.command.starts_with(".venv/"), "{}", detected.command);
|
||||
}
|
||||
|
||||
/// With no environment anywhere, the fallbacks are still ordered by what exists.
|
||||
#[test]
|
||||
fn a_bare_python_project_falls_back_through_path() {
|
||||
let project = tempfile::tempdir().expect("temp dir");
|
||||
std::fs::write(project.path().join("pytest.ini"), "[pytest]").expect("write");
|
||||
assert_eq!(python_command(project.path(), &|p| p == "pytest"), "pytest");
|
||||
assert_eq!(python_command(project.path(), &|p| p == "python3"), "python3 -m pytest");
|
||||
assert_eq!(python_command(project.path(), ¬hing_installed), "python -m pytest");
|
||||
}
|
||||
|
||||
/// A lock file is the project saying which manager linked its dependencies.
|
||||
#[test]
|
||||
fn a_javascript_project_runs_its_script_through_its_own_package_manager() {
|
||||
let project = tempfile::tempdir().expect("temp dir");
|
||||
std::fs::write(project.path().join("package.json"), r#"{"scripts": {"test": "vitest run"}}"#)
|
||||
.expect("write");
|
||||
std::fs::write(project.path().join("pnpm-lock.yaml"), "lockfileVersion: 9").expect("write");
|
||||
|
||||
let detected = detect_with(project.path(), &|_| true).expect("a node project");
|
||||
assert_eq!(detected.command, "pnpm test");
|
||||
assert_eq!(detected.framework, Framework::Node);
|
||||
// A manager the project pins but the machine does not have cannot run anything.
|
||||
assert_eq!(
|
||||
detect_with(project.path(), &|program| program == "npm").expect("detected").command,
|
||||
"npm test"
|
||||
);
|
||||
}
|
||||
|
||||
/// `npm test` against a manifest with no test script fails on the manifest, which reads as a
|
||||
/// broken tool rather than a project that never declared one.
|
||||
#[test]
|
||||
fn a_manifest_with_no_test_script_says_so_instead_of_running() {
|
||||
let project = tempfile::tempdir().expect("temp dir");
|
||||
std::fs::write(project.path().join("package.json"), r#"{"devDependencies": {"vitest": "^2"}}"#)
|
||||
.expect("write");
|
||||
|
||||
let refusal = detect_with(project.path(), &|_| true).expect_err("no test script");
|
||||
assert!(refusal.contains("no `test` script"), "{refusal}");
|
||||
assert!(refusal.contains("npx vitest run"), "and names what to run instead: {refusal}");
|
||||
|
||||
// A manifest nobody can parse is npm's error to report, not ours.
|
||||
std::fs::write(project.path().join("package.json"), "{ not json").expect("write");
|
||||
assert!(detect_with(project.path(), &|_| true).is_ok());
|
||||
}
|
||||
|
||||
/// The note is for the run the model launched itself, and it must not fire on a healthy failure.
|
||||
#[test]
|
||||
fn a_run_outside_the_projects_environment_is_named_as_the_cause() {
|
||||
let project = tempfile::tempdir().expect("temp dir");
|
||||
let venv = write_venv(project.path(), ".venv", &["python"]);
|
||||
let own = venv_pytest(project.path(), &venv).expect("the environment's interpreter");
|
||||
let import_error = |success: bool| ShellResult {
|
||||
stdout: String::new(),
|
||||
stderr: "ModuleNotFoundError: No module named 'pytest_asyncio'".to_string(),
|
||||
exit_code: Some(if success { 0 } else { 1 }),
|
||||
success,
|
||||
detached_writer: false,
|
||||
};
|
||||
|
||||
let note = foreign_interpreter_note(
|
||||
project.path(),
|
||||
"pytest -k hubspot",
|
||||
Framework::Pytest,
|
||||
&import_error(false),
|
||||
)
|
||||
.expect("a diagnosis");
|
||||
assert!(note.contains(".venv"), "{note}");
|
||||
|
||||
for (command, output, why) in [
|
||||
(own.as_str(), import_error(false), "already the project's interpreter"),
|
||||
("uv run pytest", import_error(false), "the manager owns the environment"),
|
||||
("pytest", import_error(true), "a passing run has nothing to diagnose"),
|
||||
] {
|
||||
assert_eq!(
|
||||
foreign_interpreter_note(project.path(), command, Framework::Pytest, &output),
|
||||
None,
|
||||
"{why}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
foreign_interpreter_note(
|
||||
project.path(),
|
||||
"cargo test",
|
||||
Framework::Cargo,
|
||||
&import_error(false)
|
||||
),
|
||||
None,
|
||||
"not a python question"
|
||||
);
|
||||
}
|
||||
|
||||
/// The zero-test guard, without needing a runner on the host to produce the lines.
|
||||
///
|
||||
/// Its whole job is telling an empty selection from a green one, and a runner reports the first
|
||||
/// quietly and exits 0 for it — so every case here is one a reader would otherwise skim past.
|
||||
#[test]
|
||||
fn an_empty_selection_is_told_from_a_real_run() {
|
||||
for empty in [
|
||||
"no tests ran in 0.01s",
|
||||
"collected 0 items",
|
||||
"No test files found",
|
||||
"1 deselected in 0.02s",
|
||||
] {
|
||||
assert!(executed_nothing(empty, ""), "{empty}");
|
||||
assert!(executed_nothing("", empty), "on stderr too: {empty}");
|
||||
}
|
||||
for real in [
|
||||
"19 passed, 1 deselected in 0.30s",
|
||||
"1 failed, 41 deselected in 0.40s",
|
||||
"test result: ok. 3457 passed; 0 failed",
|
||||
] {
|
||||
assert!(!executed_nothing(real, ""), "{real}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filter_uses_framework_flag() {
|
||||
assert_eq!(apply_filter("pytest", Framework::Pytest, Some("foo"), true), "pytest -k foo");
|
||||
assert_eq!(
|
||||
apply_filter("go test ./...", Framework::Go, Some("TestX"), true),
|
||||
"go test ./... -run TestX"
|
||||
);
|
||||
assert_eq!(apply_filter("cargo test", Framework::Cargo, Some("bar"), true), "cargo test bar");
|
||||
assert_eq!(apply_filter("npm test", Framework::Node, Some("baz"), true), "npm test -- baz");
|
||||
assert_eq!(apply_filter("cargo test", Framework::Cargo, None, true), "cargo test");
|
||||
}
|
||||
|
||||
/// A filter is one argument, however it is spelled.
|
||||
///
|
||||
/// The break this catches: the filter was pasted into the shell line raw, so pytest's ordinary
|
||||
/// `-k "a or b"` arrived as three words and `x;y` ran `y`.
|
||||
#[test]
|
||||
fn a_filter_is_one_argument() {
|
||||
let pytest = apply_filter("pytest", Framework::Pytest, Some("a or b"), true);
|
||||
assert_eq!(shlex::split(&pytest).unwrap(), ["pytest", "-k", "a or b"]);
|
||||
let hostile = apply_filter("cargo test", Framework::Cargo, Some("x; touch pwned"), true);
|
||||
assert_eq!(shlex::split(&hostile).unwrap(), ["cargo", "test", "x; touch pwned"]);
|
||||
let quoted = apply_filter("pytest", Framework::Pytest, Some("it's"), true);
|
||||
assert_eq!(shlex::split("ed).unwrap(), ["pytest", "-k", "it's"]);
|
||||
let cmd = apply_filter("pytest", Framework::Pytest, Some("a or \"b\""), false);
|
||||
assert_eq!(cmd, "pytest -k \"a or \"\"b\"\"\"");
|
||||
}
|
||||
|
||||
/// A filtered pytest run gets its expression as one argument, end to end through the shell.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_spaced_filter_reaches_the_runner_whole() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let runner = dir.path().join("pytest");
|
||||
std::fs::write(&runner, "#!/bin/sh\nfor a in \"$@\"; do echo \"ARG[$a]\"; done\n").unwrap();
|
||||
std::fs::set_permissions(&runner, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
|
||||
let command = format!("{} -q", runner.display());
|
||||
let args = json!({ "command": command, "filter": "test_a or test_b" });
|
||||
let result = TestTool::new().run(args, &test_context(dir.path())).await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("ARG[test_a or test_b]"), "{text}");
|
||||
}
|
||||
|
||||
/// `filter: ""` is a strict-schema model saying "no filter", and must not draw the warning a
|
||||
/// real filter earns — a real session got it on every full run.
|
||||
#[tokio::test]
|
||||
async fn an_empty_filter_is_no_filter() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
let result = TestTool::new()
|
||||
.run(serde_json::json!({"command": "true", "filter": ""}), &test_context(dir.path()))
|
||||
.await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(!text.contains("filtered"), "{text}");
|
||||
assert!(text.starts_with("$ true\n"), "and the command is run as written: {text}");
|
||||
}
|
||||
|
||||
/// A filtered run that passes is the easiest way to believe work is done when it isn't.
|
||||
#[tokio::test]
|
||||
async fn a_filtered_run_says_it_proves_nothing_about_what_it_skipped() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
std::fs::write(dir.path().join("test_x.py"), "def test_x():\n assert True\n")
|
||||
.expect("write");
|
||||
let result = TestTool::new()
|
||||
.run(
|
||||
serde_json::json!({"command": "python3 -m pytest -q", "filter": "test_x"}),
|
||||
&test_context(dir.path()),
|
||||
)
|
||||
.await;
|
||||
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("filtered"), "{text}");
|
||||
assert!(text.contains("touches"), "and says what to do about it: {text}");
|
||||
}
|
||||
|
||||
/// Whether this machine can actually *collect and run* a pytest suite.
|
||||
///
|
||||
/// Probes with a real run rather than `--version`, because those are different questions: an
|
||||
/// installed pytest that autoloads a broken third-party plugin answers `--version` happily and
|
||||
/// then dies during collection, which failed this test on a machine where nothing was wrong with
|
||||
/// Luxe. Probe the capability you need, not a proxy for it.
|
||||
async fn pytest_can_run(dir: &Path) -> bool {
|
||||
let Some(python) = luxe_core::program::resolve("python3") else {
|
||||
return false;
|
||||
};
|
||||
tokio::process::Command::new(python)
|
||||
.args(["-m", "pytest", "-q"])
|
||||
.current_dir(dir)
|
||||
.kill_on_drop(true)
|
||||
.output()
|
||||
.await
|
||||
.is_ok_and(|output| output.status.success())
|
||||
}
|
||||
|
||||
/// Every runner reports an empty selection quietly, and a zero-test run reads as a pass.
|
||||
#[tokio::test]
|
||||
async fn a_run_that_executed_nothing_does_not_read_as_green() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
std::fs::write(dir.path().join("test_x.py"), "def test_x():\n assert True\n")
|
||||
.expect("write");
|
||||
// The assertion is about how a zero-test run is *reported*, which needs a runner that can
|
||||
// report one. A missing or broken pytest is a different message entirely.
|
||||
if !pytest_can_run(dir.path()).await {
|
||||
return;
|
||||
}
|
||||
let result = TestTool::new()
|
||||
.run(
|
||||
serde_json::json!({
|
||||
"command": "python3 -m pytest -q", "filter": "no_such_test_zzz"
|
||||
}),
|
||||
&test_context(dir.path()),
|
||||
)
|
||||
.await;
|
||||
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("No tests actually ran"), "{text}");
|
||||
assert!(text.contains("not a green suite"), "{text}");
|
||||
}
|
||||
|
||||
/// A cancelled test run stops, and so does everything it started.
|
||||
///
|
||||
/// The break this catches: the suite ran under `wait_with_output` with no tree guard, so a
|
||||
/// dropped call reaped only the shell and left `cargo test` running, holding its locks.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_dropped_test_run_leaves_no_child() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let marker = dir.path().join("alive");
|
||||
let script =
|
||||
format!("(for _ in $(seq 1 40); do touch {}; sleep 0.25; done) & wait", marker.display());
|
||||
let cx = test_context(dir.path());
|
||||
{
|
||||
let tool = TestTool::new();
|
||||
let run = tool.run(json!({ "command": script }), &cx);
|
||||
tokio::pin!(run);
|
||||
// far enough to spawn the tree, then dropped, exactly as a cancel does
|
||||
let _ = tokio::time::timeout(Duration::from_millis(900), &mut run).await;
|
||||
}
|
||||
let _ = std::fs::remove_file(&marker);
|
||||
tokio::time::sleep(Duration::from_millis(1_200)).await;
|
||||
assert!(!marker.exists(), "a cancelled test run left its grandchild running");
|
||||
}
|
||||
|
||||
/// A suite that leaves a process holding its output says so, as `bash` does, rather than
|
||||
/// dropping what came after the shell exited without a word.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_run_that_left_a_writer_behind_says_so() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let args = json!({ "command": "echo ok; (sleep 3; echo late) &" });
|
||||
let result = TestTool::new().run(args, &test_context(dir.path())).await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.contains("still held its output"), "{text}");
|
||||
}
|
||||
414
crates/luxe-tools/src/todo.rs
Normal file
414
crates/luxe-tools/src/todo.rs
Normal file
@@ -0,0 +1,414 @@
|
||||
//! `todo` tool — the agent's live checklist, persisted per session.
|
||||
//!
|
||||
//! Delegates to [`TodoStore`] for durability: one file per session, so the plan survives
|
||||
//! compaction, restart and resume.
|
||||
//!
|
||||
//! Tool arguments use the surface's camelCase convention (`activeForm`/`blockedBy`).
|
||||
//! [`Todo`] still serializes `active_form`/`blocked_by`: renaming those would orphan existing
|
||||
//! checklists under `.luxe/todos/`.
|
||||
|
||||
use async_trait::async_trait;
|
||||
use luxe_core::{Todo, TodoStatus, TodoStore, Tool, ToolContext, ToolResultData, ToolSchema};
|
||||
use serde_json::json;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
use tracing::{debug, warn};
|
||||
|
||||
/// JSON-schema for the todo tool arguments.
|
||||
fn todo_schema() -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: "todo".to_string(),
|
||||
description:
|
||||
"Your live checklist for the current effort, and the only view the user has into \
|
||||
your plan. Scoped to this session and persisted to disk, so it survives compaction \
|
||||
and restart and is restored when the session resumes.\n\
|
||||
Actions: add{subjects[] | subject, blockedBy?}; update{id, status?, activeForm?, \
|
||||
blockedBy?}; complete{id}; list{}.\n\
|
||||
Use it when the work takes three or more distinct steps, touches more than one file, \
|
||||
or arrives as a list — open the whole plan in ONE `add` with `subjects`, never one \
|
||||
item at a time. The list moves itself along: `add` starts the first item when \
|
||||
nothing is in progress, and `complete` starts the next open one, so working down the \
|
||||
plan in order takes one `complete` per item and nothing else. Use `update` only to \
|
||||
start a different item or to put one back. Exactly one item is in_progress. Never \
|
||||
mark something \
|
||||
completed while its tests fail or the work is partial — leave it in_progress and add \
|
||||
a todo for the blocker. `blockedBy` (todo ids) records a dependency; blocked items \
|
||||
are flagged in `list` until their blockers finish, and clear themselves once those \
|
||||
blockers do.\n\
|
||||
Use it for: 'rename items_list to lines across the repo' (one grep, fifteen call \
|
||||
sites); 'add a dark mode toggle and run the tests'; any numbered request. Skip it \
|
||||
for: a single edit, one command, a question. When in doubt, use it.\n\
|
||||
It is a checklist, not a notebook: durable prose — a plan, a finding, a hand-off \
|
||||
note — goes in the repository as a real file."
|
||||
.to_string(),
|
||||
parameters: json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["add", "update", "list", "complete"],
|
||||
"description": "Action to perform."
|
||||
},
|
||||
"subjects": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Whole plan in one call: every todo subject, in order. Prefer \
|
||||
this over repeated single 'add' calls. Each subject is a short \
|
||||
imperative label, ideally under 50 characters."
|
||||
},
|
||||
"subject": {
|
||||
"type": "string",
|
||||
"description": "Short imperative label for the todo, ideally under 50 \
|
||||
characters (required for 'add' action)."
|
||||
},
|
||||
"id": {
|
||||
"type": "integer",
|
||||
"description": "Todo ID (required for 'update', 'complete' actions)."
|
||||
},
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": ["pending", "in_progress", "completed", "deleted"],
|
||||
"description": "New status for 'update' action."
|
||||
},
|
||||
"activeForm": {
|
||||
"type": "string",
|
||||
"description": "Present-continuous label (optional, for 'update' action)."
|
||||
},
|
||||
"blockedBy": {
|
||||
"type": "array",
|
||||
"items": { "type": "integer" },
|
||||
"description": "Todo ids this item depends on (optional, for 'add'/'update'). \
|
||||
On 'update' a non-empty list replaces the existing \
|
||||
dependencies; an empty one leaves them alone. Blocks clear \
|
||||
themselves when the blocker completes."
|
||||
}
|
||||
},
|
||||
"required": ["action"]
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `todo` tool implementation.
|
||||
pub struct TodoTool {
|
||||
store: Arc<RwLock<TodoStore>>,
|
||||
}
|
||||
|
||||
impl TodoTool {
|
||||
/// Create a new todo tool with the given store root.
|
||||
pub fn new(store_root: PathBuf) -> Self {
|
||||
Self { store: Arc::new(RwLock::new(TodoStore::new(store_root))) }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for TodoTool {
|
||||
fn name(&self) -> &str {
|
||||
"todo"
|
||||
}
|
||||
|
||||
fn schema(&self) -> ToolSchema {
|
||||
todo_schema()
|
||||
}
|
||||
|
||||
async fn run(&self, args: serde_json::Value, cx: &ToolContext) -> ToolResultData {
|
||||
let Some(action) = args.get("action").and_then(|v| v.as_str()) else {
|
||||
return ToolResultData::error("Error: 'action' argument is required");
|
||||
};
|
||||
|
||||
let todos = {
|
||||
let store = self.store.read().await;
|
||||
match store.read(&cx.session_id) {
|
||||
Ok(todos) => todos,
|
||||
Err(error) => {
|
||||
warn!(%error, "failed to read todos");
|
||||
return ToolResultData::error(format!("Failed to read todos: {error}"));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
match action {
|
||||
"add" => self.add(&args, cx, todos).await,
|
||||
"update" => self.update(&args, cx, todos).await,
|
||||
"complete" => self.complete(&args, cx, todos).await,
|
||||
"list" => {
|
||||
debug!("listing todos");
|
||||
ToolResultData::text(render_list(&todos))
|
||||
}
|
||||
_ => {
|
||||
ToolResultData::error("Unknown action. Use 'add', 'update', 'list', or 'complete'.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TodoTool {
|
||||
/// Adds one todo, or a whole plan of them, and starts the first that is unblocked.
|
||||
async fn add(
|
||||
&self,
|
||||
args: &serde_json::Value,
|
||||
cx: &ToolContext,
|
||||
mut todos: Vec<Todo>,
|
||||
) -> ToolResultData {
|
||||
let subjects = collect_subjects(args);
|
||||
if subjects.is_empty() {
|
||||
return ToolResultData::error(
|
||||
"Error: 'add' needs `subject` (one item) or `subjects` (a whole plan in \
|
||||
one call).",
|
||||
);
|
||||
}
|
||||
|
||||
debug!(count = subjects.len(), "adding todos");
|
||||
let first_id = todos.iter().map(|todo| todo.id).max().unwrap_or(0) + 1;
|
||||
|
||||
// Per-item metadata only makes sense for a single add; a batch is the plan's
|
||||
// shape, and its items get their labels and dependencies as they are worked.
|
||||
let single = subjects.len() == 1;
|
||||
let active_form = single.then(|| active_form_arg(args)).flatten();
|
||||
let blocked_by =
|
||||
if single { collect_blockers(args).unwrap_or_default() } else { Vec::new() };
|
||||
|
||||
for (offset, subject) in subjects.iter().enumerate() {
|
||||
todos.push(Todo {
|
||||
id: first_id + offset as u32,
|
||||
subject: subject.clone(),
|
||||
status: TodoStatus::Pending,
|
||||
active_form: active_form.clone(),
|
||||
blocked_by: blocked_by.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
let started = start_next(&mut todos);
|
||||
if let Err(error) = self.commit(cx, &todos).await {
|
||||
return error;
|
||||
}
|
||||
|
||||
let added = if single {
|
||||
format!("Added todo #{first_id}: {}", subjects[0])
|
||||
} else {
|
||||
let listing = subjects
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, s)| format!(" #{} {s}", first_id + i as u32))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
format!("Added {} todos:\n{listing}", subjects.len())
|
||||
};
|
||||
ToolResultData::text(with_started(added, started))
|
||||
}
|
||||
|
||||
/// Changes one todo: its status, its label, its dependencies.
|
||||
async fn update(
|
||||
&self,
|
||||
args: &serde_json::Value,
|
||||
cx: &ToolContext,
|
||||
mut todos: Vec<Todo>,
|
||||
) -> ToolResultData {
|
||||
let Some(id) = args.get("id").and_then(|v| v.as_u64()).map(|n| n as u32) else {
|
||||
return ToolResultData::error("Error: 'id' argument is required for 'update' action");
|
||||
};
|
||||
debug!(id, "updating todo");
|
||||
|
||||
let Some(todo) = todos.iter_mut().find(|todo| todo.id == id) else {
|
||||
return ToolResultData::error(format!("Todo #{id} not found"));
|
||||
};
|
||||
let subject = todo.subject.clone();
|
||||
let mut moved_to = None;
|
||||
if let Some(raw) = args.get("status").and_then(|v| v.as_str()) {
|
||||
let Some(status) = parse_status(raw) else {
|
||||
return ToolResultData::error(format!("Invalid status: {raw}"));
|
||||
};
|
||||
moved_to = Some(raw.to_string());
|
||||
todo.status = status;
|
||||
}
|
||||
if let Some(active_form) = active_form_arg(args) {
|
||||
todo.active_form = Some(active_form);
|
||||
}
|
||||
// A supplied `blockedBy` replaces the dependency list wholesale.
|
||||
if let Some(blocked_by) = collect_blockers(args) {
|
||||
todo.blocked_by = blocked_by;
|
||||
}
|
||||
|
||||
if let Err(error) = self.commit(cx, &todos).await {
|
||||
return error;
|
||||
}
|
||||
|
||||
// Naming the item is not decoration: the card's header only has the id to go on,
|
||||
// so this is where "which todo did it just start?" is answered. The subject comes
|
||||
// last and whole, so a reader of this line — model or card — can take everything
|
||||
// past the colon without having to know what else was said.
|
||||
ToolResultData::text(match moved_to {
|
||||
Some(status) => format!("Updated todo #{id} → {status}: {subject}"),
|
||||
None => format!("Updated todo #{id}: {subject}"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Marks one done, and starts the next that is unblocked.
|
||||
async fn complete(
|
||||
&self,
|
||||
args: &serde_json::Value,
|
||||
cx: &ToolContext,
|
||||
mut todos: Vec<Todo>,
|
||||
) -> ToolResultData {
|
||||
let Some(id) = args.get("id").and_then(|v| v.as_u64()).map(|n| n as u32) else {
|
||||
return ToolResultData::error("Error: 'id' argument is required for 'complete' action");
|
||||
};
|
||||
debug!(id, "completing todo");
|
||||
|
||||
let Some(todo) = todos.iter_mut().find(|todo| todo.id == id) else {
|
||||
return ToolResultData::error(format!("Todo #{id} not found"));
|
||||
};
|
||||
todo.status = TodoStatus::Completed;
|
||||
let subject = todo.subject.clone();
|
||||
let started = start_next(&mut todos);
|
||||
|
||||
if let Err(error) = self.commit(cx, &todos).await {
|
||||
return error;
|
||||
}
|
||||
ToolResultData::text(with_started(format!("Completed todo #{id}: {subject}"), started))
|
||||
}
|
||||
|
||||
/// Persists the list, returning the failure as a ready tool result.
|
||||
async fn commit(&self, cx: &ToolContext, todos: &[Todo]) -> Result<(), ToolResultData> {
|
||||
let store = self.store.write().await;
|
||||
store.write(&cx.session_id, todos).map_err(|error| {
|
||||
warn!(%error, "failed to write todos");
|
||||
ToolResultData::error(format!("Failed to save todos: {error}"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the first open item nothing blocks, unless something is already in progress.
|
||||
///
|
||||
/// Marking each item in progress was a call of its own, which made a three-step plan seven calls:
|
||||
/// GPT models spent more than a quarter of their tool calls on this list that way. Returns the
|
||||
/// started item's `(id, subject)`.
|
||||
fn start_next(todos: &mut [Todo]) -> Option<(u32, String)> {
|
||||
if todos.iter().any(|todo| todo.status == TodoStatus::InProgress) {
|
||||
return None;
|
||||
}
|
||||
let next = todos.iter().position(|todo| {
|
||||
todo.status == TodoStatus::Pending && todo.open_blockers(todos).is_empty()
|
||||
})?;
|
||||
let todo = &mut todos[next];
|
||||
todo.status = TodoStatus::InProgress;
|
||||
Some((todo.id, todo.subject.clone()))
|
||||
}
|
||||
|
||||
/// `text`, with a line saying which item [`start_next`] started. A line of its own, because a card
|
||||
/// reads its item's name off the first.
|
||||
fn with_started(text: String, started: Option<(u32, String)>) -> String {
|
||||
match started {
|
||||
Some((id, subject)) => format!("{text}\nStarted todo #{id}: {subject}"),
|
||||
None => text,
|
||||
}
|
||||
}
|
||||
|
||||
/// The model-facing rendering of the list.
|
||||
///
|
||||
/// Markdown-checkbox markers rather than glyphs, because the model reads this output.
|
||||
fn render_list(todos: &[Todo]) -> String {
|
||||
let live: Vec<&Todo> = todos.iter().filter(|todo| todo.status.is_live()).collect();
|
||||
if live.is_empty() {
|
||||
return "No todos".to_string();
|
||||
}
|
||||
// An item is "blocked" only while a dependency is still incomplete.
|
||||
let completed: std::collections::HashSet<u32> = todos
|
||||
.iter()
|
||||
.filter(|todo| todo.status == TodoStatus::Completed)
|
||||
.map(|todo| todo.id)
|
||||
.collect();
|
||||
live.iter()
|
||||
.map(|todo| {
|
||||
let marker = match todo.status {
|
||||
TodoStatus::Pending => "[ ]",
|
||||
TodoStatus::InProgress => "[~]",
|
||||
TodoStatus::Completed => "[x]",
|
||||
TodoStatus::Deleted => "[-]",
|
||||
};
|
||||
let unresolved: Vec<String> = todo
|
||||
.blocked_by
|
||||
.iter()
|
||||
.filter(|id| !completed.contains(id))
|
||||
.map(|id| format!("#{id}"))
|
||||
.collect();
|
||||
if todo.status != TodoStatus::Completed && !unresolved.is_empty() {
|
||||
format!(
|
||||
"{marker} #{}: {} (blocked by {})",
|
||||
todo.id,
|
||||
todo.subject,
|
||||
unresolved.join(", ")
|
||||
)
|
||||
} else {
|
||||
format!("{marker} #{}: {}", todo.id, todo.subject)
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn parse_status(raw: &str) -> Option<TodoStatus> {
|
||||
match raw {
|
||||
"pending" => Some(TodoStatus::Pending),
|
||||
"in_progress" => Some(TodoStatus::InProgress),
|
||||
"completed" => Some(TodoStatus::Completed),
|
||||
"deleted" => Some(TodoStatus::Deleted),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The subjects an `add` is creating: one via `subject`, or a whole plan via `subjects`.
|
||||
///
|
||||
/// Batch creation is the point. With one item per call a six-step plan costs six round-trips, and a
|
||||
/// model weighing cost against benefit correctly skips planning altogether.
|
||||
///
|
||||
/// `subjects` wins only when it holds something. A model under a strict JSON schema sends **every**
|
||||
/// property, so `{subject: "real text", subjects: []}` is an ordinary single add, and treating the
|
||||
/// empty array as the answer would refuse it.
|
||||
fn collect_subjects(args: &serde_json::Value) -> Vec<String> {
|
||||
let batch: Vec<String> = args
|
||||
.get("subjects")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|list| list.iter().filter_map(|v| v.as_str()).filter_map(non_blank).collect())
|
||||
.unwrap_or_default();
|
||||
if !batch.is_empty() {
|
||||
return batch;
|
||||
}
|
||||
args.get("subject").and_then(|v| v.as_str()).and_then(non_blank).into_iter().collect()
|
||||
}
|
||||
|
||||
/// `text` with its surrounding space gone, or `None` if that leaves nothing.
|
||||
///
|
||||
/// The blank is the common case, not the odd one: a strict schema makes the model fill in every
|
||||
/// optional property, and what it fills them with is `""`.
|
||||
fn non_blank(text: &str) -> Option<String> {
|
||||
let trimmed = text.trim();
|
||||
(!trimmed.is_empty()).then(|| trimmed.to_string())
|
||||
}
|
||||
|
||||
/// The spinner label a call is setting, under either spelling, or `None` if it set none.
|
||||
fn active_form_arg(args: &serde_json::Value) -> Option<String> {
|
||||
luxe_core::tool::arg(args, &["activeForm", "active_form"])
|
||||
.and_then(|value| value.as_str())
|
||||
.and_then(non_blank)
|
||||
}
|
||||
|
||||
/// The dependencies a call is declaring, or `None` for "leave them alone".
|
||||
///
|
||||
/// An empty list means the latter. Clearing is the reading the schema invites — but a strict-schema
|
||||
/// model sends `blockedBy: []` on *every* call it makes, which would wipe a real dependency the
|
||||
/// first time the item was touched for any other reason. Nothing is lost by dropping it: a block
|
||||
/// clears itself the moment its blocker completes.
|
||||
fn collect_blockers(args: &serde_json::Value) -> Option<Vec<u32>> {
|
||||
let ids: Vec<u32> = luxe_core::tool::arg(args, &["blockedBy", "blocked_by"])?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter_map(|value| value.as_u64())
|
||||
.filter(|id| *id > 0)
|
||||
.map(|id| id as u32)
|
||||
.collect();
|
||||
(!ids.is_empty()).then_some(ids)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
326
crates/luxe-tools/src/todo/tests.rs
Normal file
326
crates/luxe-tools/src/todo/tests.rs
Normal file
@@ -0,0 +1,326 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::*;
|
||||
use luxe_core::ContentBlock;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
fn context(cwd: &std::path::Path, session_id: &str) -> ToolContext {
|
||||
let (event_tx, _event_rx) = mpsc::channel(64);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
ToolContext {
|
||||
cwd: cwd.to_path_buf(),
|
||||
session_id: session_id.to_string(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The tool, its store root, and a context on one session.
|
||||
fn tool(tmp: &tempfile::TempDir) -> (TodoTool, ToolContext) {
|
||||
(TodoTool::new(tmp.path().join("todos")), context(tmp.path(), "test-session"))
|
||||
}
|
||||
|
||||
fn text(result: &ToolResultData) -> String {
|
||||
match &result.content[0] {
|
||||
ContentBlock::Text(text) => text.clone(),
|
||||
_ => panic!("expected a text block"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_fresh_session_lists_nothing_and_is_not_an_error() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (tool, cx) = tool(&tmp);
|
||||
|
||||
let result = tool.run(json!({"action": "list"}), &cx).await;
|
||||
|
||||
assert!(!result.is_error);
|
||||
assert_eq!(text(&result), "No todos");
|
||||
}
|
||||
|
||||
/// The list is the whole point of the durable store: it has to come back after a restart.
|
||||
#[tokio::test]
|
||||
async fn the_list_survives_a_restart_and_belongs_to_its_own_session() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("todos");
|
||||
let cx = context(tmp.path(), "session-a");
|
||||
|
||||
TodoTool::new(root.clone()).run(json!({"action": "add", "subject": "wire it"}), &cx).await;
|
||||
|
||||
// A new tool over the same root is the restart.
|
||||
let listed = text(&TodoTool::new(root.clone()).run(json!({"action": "list"}), &cx).await);
|
||||
assert_eq!(listed, "[~] #1: wire it");
|
||||
|
||||
// Another session is another list.
|
||||
let other = context(tmp.path(), "session-b");
|
||||
let listed = text(&TodoTool::new(root).run(json!({"action": "list"}), &other).await);
|
||||
assert_eq!(listed, "No todos");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn todo_tool_complete() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (tool, cx) = tool(&tmp);
|
||||
|
||||
tool.run(json!({"action": "add", "subject": "Do thing B"}), &cx).await;
|
||||
let result = tool.run(json!({"action": "complete", "id": 1}), &cx).await;
|
||||
|
||||
assert!(!result.is_error);
|
||||
assert_eq!(text(&result), "Completed todo #1: Do thing B");
|
||||
assert_eq!(text(&tool.run(json!({"action": "list"}), &cx).await), "[x] #1: Do thing B");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn todo_tool_missing_action() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (tool, cx) = tool(&tmp);
|
||||
|
||||
assert!(tool.run(json!({}), &cx).await.is_error);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unknown_id_is_reported_rather_than_written() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (tool, cx) = tool(&tmp);
|
||||
|
||||
let missing = tool.run(json!({"action": "update", "id": 7, "status": "completed"}), &cx);
|
||||
assert_eq!(text(&missing.await), "Todo #7 not found");
|
||||
|
||||
tool.run(json!({"action": "add", "subject": "real"}), &cx).await;
|
||||
let bad_status = tool.run(json!({"action": "update", "id": 1, "status": "napping"}), &cx);
|
||||
assert_eq!(text(&bad_status.await), "Invalid status: napping");
|
||||
// The rejected status left the item alone.
|
||||
assert_eq!(text(&tool.run(json!({"action": "list"}), &cx).await), "[~] #1: real");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn todo_blocked_by_is_recorded_and_flagged() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (tool, cx) = tool(&tmp);
|
||||
|
||||
// #1 is a prerequisite; #2 depends on it via `add { blocked_by }`.
|
||||
tool.run(json!({"action": "add", "subject": "lay foundation"}), &cx).await;
|
||||
tool.run(json!({"action": "add", "subject": "build wall", "blockedBy": [1]}), &cx).await;
|
||||
|
||||
// `list` flags #2 as blocked while #1 is incomplete.
|
||||
let listed = text(&tool.run(json!({"action": "list"}), &cx).await);
|
||||
assert!(listed.contains("#2: build wall (blocked by #1)"), "got: {listed}");
|
||||
|
||||
// Completing the blocker clears the flag.
|
||||
tool.run(json!({"action": "complete", "id": 1}), &cx).await;
|
||||
let listed = text(&tool.run(json!({"action": "list"}), &cx).await);
|
||||
assert!(!listed.contains("blocked by"), "block should clear once #1 done: {listed}");
|
||||
|
||||
// `update { blocked_by }` sets dependencies after creation.
|
||||
tool.run(json!({"action": "add", "subject": "paint"}), &cx).await; // #3
|
||||
tool.run(json!({"action": "update", "id": 2, "blockedBy": [3]}), &cx).await;
|
||||
let listed = text(&tool.run(json!({"action": "list"}), &cx).await);
|
||||
assert!(listed.contains("#2: build wall (blocked by #3)"), "update sets deps: {listed}");
|
||||
|
||||
// An empty list is not an instruction. Every call from a strict-schema model carries one,
|
||||
// so honoring it would wipe a real dependency the next time the item was touched at all.
|
||||
tool.run(json!({"action": "update", "id": 2, "blockedBy": []}), &cx).await;
|
||||
let listed = text(&tool.run(json!({"action": "list"}), &cx).await);
|
||||
assert!(listed.contains("blocked by #3"), "[] must not clear deps: {listed}");
|
||||
|
||||
// Completing the blocker is what clears a block, and it needs no argument at all.
|
||||
tool.run(json!({"action": "complete", "id": 3}), &cx).await;
|
||||
let listed = text(&tool.run(json!({"action": "list"}), &cx).await);
|
||||
assert!(!listed.contains("blocked by"), "a finished blocker clears the flag: {listed}");
|
||||
}
|
||||
|
||||
/// A deleted item is a tombstone: gone from the list, but its id is never reused.
|
||||
#[tokio::test]
|
||||
async fn a_deleted_todo_leaves_the_list_without_freeing_its_id() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (tool, cx) = tool(&tmp);
|
||||
|
||||
tool.run(json!({"action": "add", "subjects": ["one", "two"]}), &cx).await;
|
||||
tool.run(json!({"action": "update", "id": 1, "status": "deleted"}), &cx).await;
|
||||
assert_eq!(text(&tool.run(json!({"action": "list"}), &cx).await), "[ ] #2: two");
|
||||
|
||||
tool.run(json!({"action": "add", "subject": "three"}), &cx).await;
|
||||
let listed = text(&tool.run(json!({"action": "list"}), &cx).await);
|
||||
assert!(listed.contains("#3: three"), "the next id follows the tombstone: {listed}");
|
||||
}
|
||||
|
||||
/// A plan has to cost one call. With one item per call a six-step plan cost six round-trips,
|
||||
/// and a model weighing cost against benefit skipped planning altogether.
|
||||
#[tokio::test]
|
||||
async fn a_whole_plan_is_created_in_one_call() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (tool, cx) = tool(&tmp);
|
||||
|
||||
let result = tool
|
||||
.run(
|
||||
json!({
|
||||
"action": "add",
|
||||
"subjects": ["rename the field", "add total_quantity", "add tests"]
|
||||
}),
|
||||
&cx,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(!result.is_error, "batch add succeeds");
|
||||
let added = text(&result);
|
||||
assert!(added.contains("Added 3 todos"), "{added}");
|
||||
assert!(added.contains("#1") && added.contains("#3"), "ids are reported: {added}");
|
||||
|
||||
let listed = text(&tool.run(json!({"action": "list"}), &cx).await);
|
||||
for subject in ["rename the field", "add total_quantity", "add tests"] {
|
||||
assert!(listed.contains(subject), "{subject} survived: {listed}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_single_add_still_works_and_keeps_its_metadata() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (tool, cx) = tool(&tmp);
|
||||
|
||||
let result =
|
||||
tool.run(json!({"action": "add", "subject": "just one", "blockedBy": []}), &cx).await;
|
||||
assert_eq!(text(&result), "Added todo #1: just one\nStarted todo #1: just one");
|
||||
}
|
||||
|
||||
/// Working down a plan in order is one `complete` per item: each starts the next open item,
|
||||
/// skipping one still blocked, and an item already in progress is never displaced.
|
||||
#[tokio::test]
|
||||
async fn the_list_moves_itself_along() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (tool, cx) = tool(&tmp);
|
||||
let list = || async { text(&tool.run(json!({"action": "list"}), &cx).await) };
|
||||
|
||||
let added = text(&tool.run(json!({"action": "add", "subjects": ["a", "b", "c"]}), &cx).await);
|
||||
assert!(added.ends_with("\nStarted todo #1: a"), "{added}");
|
||||
tool.run(json!({"action": "update", "id": 2, "blockedBy": [3]}), &cx).await;
|
||||
|
||||
let done = text(&tool.run(json!({"action": "complete", "id": 1}), &cx).await);
|
||||
assert_eq!(done, "Completed todo #1: a\nStarted todo #3: c", "#2 waits on #3");
|
||||
assert_eq!(list().await, "[x] #1: a\n[ ] #2: b (blocked by #3)\n[~] #3: c");
|
||||
|
||||
// Adding while something is in progress leaves it be
|
||||
let added = text(&tool.run(json!({"action": "add", "subject": "d"}), &cx).await);
|
||||
assert_eq!(added, "Added todo #4: d");
|
||||
|
||||
let done = text(&tool.run(json!({"action": "complete", "id": 3}), &cx).await);
|
||||
assert_eq!(done, "Completed todo #3: c\nStarted todo #2: b");
|
||||
// Finishing an item out of order does not start a second one
|
||||
let done = text(&tool.run(json!({"action": "complete", "id": 4}), &cx).await);
|
||||
assert_eq!(done, "Completed todo #4: d");
|
||||
assert_eq!(list().await, "[x] #1: a\n[~] #2: b\n[x] #3: c\n[x] #4: d");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subjects_wins_over_subject_and_blanks_are_dropped() {
|
||||
let batch = collect_subjects(&json!({
|
||||
"subjects": ["a", " ", "b"], "subject": "ignored"
|
||||
}));
|
||||
assert_eq!(batch, vec!["a", "b"]);
|
||||
|
||||
let single = collect_subjects(&json!({"subject": " solo "}));
|
||||
assert_eq!(single, vec!["solo"]);
|
||||
|
||||
assert!(collect_subjects(&json!({"subjects": []})).is_empty());
|
||||
}
|
||||
|
||||
/// A model under a strict JSON schema fills in every property it was shown, so an ordinary
|
||||
/// single `add` arrives carrying `subjects: []` beside the real subject. Reading the empty
|
||||
/// array as the answer rejected it — twice in a row in a real session, before the model gave up
|
||||
/// and rephrased the call to get past a tool that was wrong about its own arguments.
|
||||
#[tokio::test]
|
||||
async fn a_default_filled_add_is_not_an_empty_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (tool, cx) = tool(&tmp);
|
||||
|
||||
let result = tool
|
||||
.run(
|
||||
json!({
|
||||
"action": "add", "activeForm": "", "blockedBy": [], "id": 0,
|
||||
"status": "pending", "subject": "scope the SSRF failure", "subjects": []
|
||||
}),
|
||||
&cx,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(!result.is_error, "{:?}", result.content);
|
||||
assert!(text(&result).starts_with("Added todo #1: scope the SSRF failure\n"));
|
||||
}
|
||||
|
||||
/// The same default-filling makes every call carry `blocked_by: []` and `active_form: ""`. Read
|
||||
/// literally, one `update` that meant only "start this" also wiped a real dependency and
|
||||
/// labeled the item with an empty string.
|
||||
#[tokio::test]
|
||||
async fn a_default_filled_update_leaves_what_it_did_not_mention_alone() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (tool, cx) = tool(&tmp);
|
||||
|
||||
tool.run(json!({"action": "add", "subject": "lay foundation"}), &cx).await;
|
||||
tool.run(json!({"action": "add", "subject": "build wall", "blockedBy": [1]}), &cx).await;
|
||||
tool.run(
|
||||
json!({
|
||||
"action": "update", "activeForm": "", "blockedBy": [], "id": 2,
|
||||
"status": "in_progress", "subject": "", "subjects": []
|
||||
}),
|
||||
&cx,
|
||||
)
|
||||
.await;
|
||||
|
||||
let listed = text(&tool.run(json!({"action": "list"}), &cx).await);
|
||||
assert!(listed.contains("blocked by #1"), "the dependency survived: {listed}");
|
||||
|
||||
// A dependency the model actually names still replaces the list wholesale.
|
||||
tool.run(json!({"action": "update", "id": 2, "blockedBy": [1, 3]}), &cx).await;
|
||||
let listed = text(&tool.run(json!({"action": "list"}), &cx).await);
|
||||
assert!(listed.contains("blocked by #1, #3"), "{listed}");
|
||||
}
|
||||
|
||||
/// The card's header only has `#3` to show, so the result is where the item gets named.
|
||||
#[tokio::test]
|
||||
async fn an_update_names_the_item_it_moved() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (tool, cx) = tool(&tmp);
|
||||
|
||||
tool.run(json!({"action": "add", "subject": "wire the dock"}), &cx).await;
|
||||
let moved =
|
||||
text(&tool.run(json!({"action": "update", "id": 1, "status": "in_progress"}), &cx).await);
|
||||
assert_eq!(moved, "Updated todo #1 → in_progress: wire the dock");
|
||||
|
||||
let relabeled =
|
||||
text(&tool.run(json!({"action": "update", "id": 1, "activeForm": "Wiring"}), &cx).await);
|
||||
assert_eq!(relabeled, "Updated todo #1: wire the dock");
|
||||
}
|
||||
|
||||
/// The spellings these two arguments used to be advertised under still land.
|
||||
///
|
||||
/// Both are optional, so the failure mode of dropping one is not an error the model can see —
|
||||
/// the label never appears, the dependency is never recorded, and the call reports success. A
|
||||
/// session resumed from a transcript full of the old spelling would hit that on every update.
|
||||
#[tokio::test]
|
||||
async fn the_spellings_these_arguments_used_to_have_are_still_accepted() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (tool, cx) = tool(&tmp);
|
||||
|
||||
tool.run(json!({"action": "add", "subject": "lay the foundation"}), &cx).await;
|
||||
tool.run(json!({"action": "add", "subject": "build the wall", "blocked_by": [1]}), &cx).await;
|
||||
tool.run(json!({"action": "update", "id": 2, "active_form": "Building"}), &cx).await;
|
||||
|
||||
let listing = text(&tool.run(json!({"action": "list"}), &cx).await);
|
||||
assert!(listing.contains("blocked by #1"), "`blocked_by` was dropped: {listing}");
|
||||
|
||||
let stored = TodoStore::new(tmp.path().join("todos")).read("test-session").unwrap();
|
||||
assert_eq!(stored[1].active_form.as_deref(), Some("Building"), "`active_form` was dropped");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_add_with_nothing_to_add_says_which_argument_to_pass() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (tool, cx) = tool(&tmp);
|
||||
|
||||
let result = tool.run(json!({"action": "add"}), &cx).await;
|
||||
|
||||
assert!(result.is_error);
|
||||
assert!(text(&result).contains("subjects"), "names the batch form too");
|
||||
}
|
||||
154
crates/luxe-tools/src/web.rs
Normal file
154
crates/luxe-tools/src/web.rs
Normal file
@@ -0,0 +1,154 @@
|
||||
// Web search and fetch tools.
|
||||
//
|
||||
// web_search — pluggable search backend (Brave/Tavily/Exa/Firecrawl) returning normalized hits.
|
||||
// web_fetch — GET URL, extract readable content → markdown, with optional stealth fallback.
|
||||
|
||||
mod clone;
|
||||
mod fetch;
|
||||
mod render;
|
||||
mod search;
|
||||
|
||||
pub use fetch::WebFetchTool;
|
||||
pub use search::{create_backend, Recency, SearchBackend, SearchHit, SearchOptions, WebSearchTool};
|
||||
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use luxe_core::provider::ToolSchema;
|
||||
use luxe_core::tool::{Tool, ToolContext, ToolResultData};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
use url::Url;
|
||||
|
||||
/// Web tool error.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum WebError {
|
||||
#[error("HTTP error: {0}")]
|
||||
Http(String),
|
||||
#[error("network error: {0}")]
|
||||
Network(String),
|
||||
/// The far end never finished answering: a name that would not resolve, or a socket that
|
||||
/// connected and then went quiet. Its own variant because it is the one failure a retry cannot
|
||||
/// help — see `WebError::worth_a_second_try`.
|
||||
#[error("timeout: {0}")]
|
||||
Timeout(String),
|
||||
#[error("parse error: {0}")]
|
||||
Parse(String),
|
||||
#[error("backend error: {0}")]
|
||||
Backend(String),
|
||||
}
|
||||
|
||||
impl WebError {
|
||||
/// Whether refetching with a browser-like user agent could plausibly do better.
|
||||
///
|
||||
/// The stealth retry exists to get past bot protection — a 403, a challenge page, a body that is
|
||||
/// all JavaScript — and it works by looking like a browser. A host that never answered does not
|
||||
/// care what we call ourselves, so retrying a timeout only spends the budget twice: two 30s
|
||||
/// attempts against a silent host is a minute of nothing, which is exactly how a dead domain came
|
||||
/// to look like a hung agent.
|
||||
fn worth_a_second_try(&self) -> bool {
|
||||
!matches!(self, Self::Timeout(_))
|
||||
}
|
||||
}
|
||||
|
||||
/// Configuration for web tools.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct WebConfig {
|
||||
/// Search backend to use (brave, tavily, exa, firecrawl).
|
||||
pub search_backend: Option<String>,
|
||||
/// API key for the search backend.
|
||||
pub search_api_key: Option<String>,
|
||||
/// Enable stealth fetch fallback.
|
||||
pub enable_stealth: bool,
|
||||
/// Firecrawl key, held apart from the search key because it also backs `web_fetch`'s last
|
||||
/// resort — so it is worth having even when another vendor won the search slot.
|
||||
#[serde(default)]
|
||||
pub firecrawl_api_key: Option<String>,
|
||||
/// Whether a GitHub repository URL is cloned into `.luxe/gh-cache/` rather than read as a page.
|
||||
#[serde(default = "clone_by_default")]
|
||||
pub clone_repositories: bool,
|
||||
}
|
||||
|
||||
impl Default for WebConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
search_backend: None,
|
||||
search_api_key: None,
|
||||
enable_stealth: false,
|
||||
firecrawl_api_key: None,
|
||||
clone_repositories: clone_by_default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn clone_by_default() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// The keyed search vendors, in the order a configured key claims the slot.
|
||||
const SEARCH_KEYS: &[(&str, &str)] = &[
|
||||
("brave", "BRAVE_API_KEY"),
|
||||
("tavily", "TAVILY_API_KEY"),
|
||||
("exa", "EXA_API_KEY"),
|
||||
("firecrawl", "FIRECRAWL_API_KEY"),
|
||||
];
|
||||
|
||||
impl WebConfig {
|
||||
/// Build config from the environment: a configured key picks its backend, in `SEARCH_KEYS`
|
||||
/// order, and otherwise search falls back to Exa's keyless MCP endpoint.
|
||||
///
|
||||
/// An explicit key outranks the fallback — someone who configured one chose it. But search is
|
||||
/// a *capability*, not a setup step: without this fallback, `web_search` was registered and
|
||||
/// then failed on first use for every user who had not signed up for a search vendor.
|
||||
pub fn from_env() -> Self {
|
||||
let (backend, key) = SEARCH_KEYS
|
||||
.iter()
|
||||
.find_map(|(name, var)| env_key(var).map(|key| ((*name).to_string(), key)))
|
||||
.map_or((None, None), |(name, key)| (Some(name), Some(key)));
|
||||
Self {
|
||||
search_backend: backend,
|
||||
search_api_key: key,
|
||||
enable_stealth: true,
|
||||
firecrawl_api_key: env_key("FIRECRAWL_API_KEY"),
|
||||
clone_repositories: clone_by_default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a search backend key is configured. Search works either way — this only says
|
||||
/// whether it will go through a keyed vendor or the keyless fallback.
|
||||
pub fn has_search_key(&self) -> bool {
|
||||
self.search_api_key.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// A non-blank environment value, since an exported-but-empty key is not a key.
|
||||
fn env_key(var: &str) -> Option<String> {
|
||||
std::env::var(var).ok().map(|value| value.trim().to_string()).filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
/// Web tools (search + fetch) with shared configuration.
|
||||
pub struct WebTools {
|
||||
config: Arc<RwLock<WebConfig>>,
|
||||
/// Read out at construction, because the schema promises it and a schema is built synchronously
|
||||
clone_repositories: bool,
|
||||
}
|
||||
|
||||
impl WebTools {
|
||||
pub fn new(config: WebConfig) -> Self {
|
||||
let clone_repositories = config.clone_repositories;
|
||||
Self { config: Arc::new(RwLock::new(config)), clone_repositories }
|
||||
}
|
||||
|
||||
/// Create a web_search tool.
|
||||
pub fn web_search(&self) -> WebSearchTool {
|
||||
WebSearchTool { config: self.config.clone() }
|
||||
}
|
||||
|
||||
/// Create a web_fetch tool.
|
||||
pub fn web_fetch(&self) -> WebFetchTool {
|
||||
WebFetchTool { config: self.config.clone(), clone_repositories: self.clone_repositories }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
441
crates/luxe-tools/src/web/clone.rs
Normal file
441
crates/luxe-tools/src/web/clone.rs
Normal file
@@ -0,0 +1,441 @@
|
||||
//! Fetched repositories — a GitHub repository URL handed to `web_fetch`, checked out where the agent
|
||||
//! can read it.
|
||||
//!
|
||||
//! The checkout lives at `.luxe/gh-cache/<owner>/<repo>` ([`luxe_core::fetched`]), inside the
|
||||
//! project so reading it never trips the external-directory guard. That convenience is also the
|
||||
//! risk: it is a stranger's tree sitting inside the user's, judged by the same lexical path checks.
|
||||
//! So the clone is made to carry nothing that acts on its own:
|
||||
//!
|
||||
//! - **Symbolic links are checked out as plain files** holding their target
|
||||
//! (`core.symlinks=false`). A link is the one thing in a repository that can point *out* of it,
|
||||
//! and a `README.md` linked to `../../../../.env` would otherwise hand the project's secrets to
|
||||
//! the model past the `.env` rule.
|
||||
//! - **Nothing prompts.** A private or misspelled repository makes git ask for a username on the
|
||||
//! terminal, which here is the TUI's screen; with prompts off it fails at once and says why.
|
||||
//! - **No LFS objects, no submodules, no tags.** The source is the point, not the binaries.
|
||||
//! - **Nothing half-made is ever cached.** It clones into a staging directory and renames it into
|
||||
//! place, so a clone stopped by a timeout, a cancelled turn or the size cap leaves nothing that
|
||||
//! looks like a finished checkout.
|
||||
//!
|
||||
//! Language servers and format-on-save stay out of the cache too, but that is their check, not
|
||||
//! this module's — see [`luxe_core::fetched::contains`].
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use luxe_core::tool::{ToolContext, ToolResultData};
|
||||
|
||||
/// How old a checkout gets before the next fetch of it clones again.
|
||||
const REFRESH_AFTER: Duration = Duration::from_secs(24 * 60 * 60);
|
||||
|
||||
/// How long a checkout nobody has fetched is kept.
|
||||
const PRUNE_AFTER: Duration = Duration::from_secs(14 * 24 * 60 * 60);
|
||||
|
||||
/// How old a staging directory must be before it counts as left behind rather than in progress.
|
||||
const STAGING_STALE_AFTER: Duration = Duration::from_secs(60 * 60);
|
||||
|
||||
/// What a clone may run to, on disk.
|
||||
const MAX_CLONE_BYTES: u64 = 500 * 1024 * 1024;
|
||||
|
||||
/// Longest a clone runs. Under the tool's own network deadline, so a slow clone ends with this
|
||||
/// module's explanation and cleanup rather than dispatch dropping the call.
|
||||
const CLONE_DEADLINE: Duration = Duration::from_secs(45);
|
||||
|
||||
/// How often a running clone's size is checked against [`MAX_CLONE_BYTES`].
|
||||
const SIZE_POLL: Duration = Duration::from_millis(500);
|
||||
|
||||
/// Name prefix of a directory a clone is being made in, or a replaced checkout on its way out.
|
||||
const STAGING_PREFIX: &str = ".staging-";
|
||||
|
||||
/// When a checkout was cloned, in seconds since the epoch, inside its `.git`.
|
||||
const FETCHED_STAMP: &str = "luxe-fetched";
|
||||
|
||||
/// When a checkout was last fetched by anyone, inside its `.git`; what pruning goes by.
|
||||
const USED_STAMP: &str = "luxe-used";
|
||||
|
||||
/// What bounds one clone. A struct so a test can make the cap small enough to hit.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct Limits {
|
||||
max_bytes: u64,
|
||||
deadline: Duration,
|
||||
}
|
||||
|
||||
const LIMITS: Limits = Limits { max_bytes: MAX_CLONE_BYTES, deadline: CLONE_DEADLINE };
|
||||
|
||||
/// Why a clone did not produce a checkout.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum CloneError {
|
||||
#[error("git is not installed")]
|
||||
NoGit,
|
||||
#[error("git clone failed: {0}")]
|
||||
Git(String),
|
||||
#[error("the clone took longer than {}s and was stopped", .0.as_secs())]
|
||||
Timeout(Duration),
|
||||
#[error("the repository is larger than {} MB on disk and the clone was stopped", .0 / (1024 * 1024))]
|
||||
TooLarge(u64),
|
||||
#[error("{0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
/// Fetch `owner/repo` from GitHub for the project at `cx.cwd`, or reuse the checkout already there.
|
||||
pub(super) async fn fetch_repository(owner: &str, repo: &str, cx: &ToolContext) -> ToolResultData {
|
||||
let source = format!("https://github.com/{owner}/{repo}.git");
|
||||
fetch_into(&source, owner, repo, &cx.cwd, LIMITS).await
|
||||
}
|
||||
|
||||
/// [`fetch_repository`] from any `source` git can clone, so the tests can use a local repository.
|
||||
async fn fetch_into(
|
||||
source: &str,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
root: &Path,
|
||||
limits: Limits,
|
||||
) -> ToolResultData {
|
||||
let cache = luxe_core::fetched::cache_dir(root);
|
||||
let Some(dest) = checkout_dir(&cache, owner, repo) else {
|
||||
return ToolResultData::error(format!(
|
||||
"`{owner}/{repo}` is not a GitHub repository name Luxe will clone."
|
||||
));
|
||||
};
|
||||
{
|
||||
let cache = cache.clone();
|
||||
let _ = tokio::task::spawn_blocking(move || tidy(&cache, now_secs())).await;
|
||||
}
|
||||
|
||||
let fetched = read_stamp(&dest, FETCHED_STAMP);
|
||||
let have = dest.join(".git").is_dir();
|
||||
let stale = fetched.is_none_or(|at| now_secs().saturating_sub(at) >= REFRESH_AFTER.as_secs());
|
||||
let note = if have && !stale {
|
||||
None
|
||||
} else {
|
||||
match clone_into(source, &cache, &dest, owner, repo, limits).await {
|
||||
Ok(()) => None,
|
||||
// A copy that could not be refreshed is still a copy, and usually the right one
|
||||
Err(reason) if have => Some(format!(
|
||||
"Could not refresh it ({reason}), so this copy is from {}.",
|
||||
age(fetched.unwrap_or(0))
|
||||
)),
|
||||
Err(reason) => {
|
||||
return ToolResultData::error(format!(
|
||||
"Could not clone {owner}/{repo}: {reason}. If it exists and is private, git \
|
||||
needs credentials for github.com, such as `gh auth setup-git`."
|
||||
));
|
||||
}
|
||||
}
|
||||
};
|
||||
write_stamp(&dest, USED_STAMP);
|
||||
describe(owner, repo, &dest, note).await
|
||||
}
|
||||
|
||||
/// Where `owner/repo` is checked out, or `None` for a name that is not safe to use as a path.
|
||||
///
|
||||
/// One directory per owner, so `a-b/c` and `a/b-c` cannot share a checkout the way a joined
|
||||
/// `owner-repo` name let them.
|
||||
fn checkout_dir(cache: &Path, owner: &str, repo: &str) -> Option<PathBuf> {
|
||||
let owner_ok =
|
||||
!owner.is_empty() && owner.chars().all(|c| c.is_ascii_alphanumeric() || c == '-');
|
||||
let repo_ok = !repo.is_empty()
|
||||
&& repo.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
|
||||
&& !matches!(repo, "." | "..")
|
||||
&& !repo.eq_ignore_ascii_case(".git");
|
||||
(owner_ok && repo_ok).then(|| cache.join(owner).join(repo))
|
||||
}
|
||||
|
||||
/// Clone `source` into a staging directory and move it to `dest`, replacing what was there.
|
||||
async fn clone_into(
|
||||
source: &str,
|
||||
cache: &Path,
|
||||
dest: &Path,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
limits: Limits,
|
||||
) -> Result<(), CloneError> {
|
||||
let git = luxe_core::program::resolve("git").ok_or(CloneError::NoGit)?;
|
||||
std::fs::create_dir_all(cache)?;
|
||||
let staging = staging_dir(cache, owner, repo);
|
||||
let mut guard = Staging { dir: Some(staging.clone()), pid: None };
|
||||
|
||||
let child = clone_command(&git, source, &staging, cache).spawn()?;
|
||||
guard.pid = child.id();
|
||||
let wait = child.wait_with_output();
|
||||
tokio::pin!(wait);
|
||||
let deadline = tokio::time::sleep(limits.deadline);
|
||||
tokio::pin!(deadline);
|
||||
let mut poll = tokio::time::interval(SIZE_POLL);
|
||||
let output = loop {
|
||||
tokio::select! {
|
||||
output = &mut wait => break output?,
|
||||
() = &mut deadline => return Err(CloneError::Timeout(limits.deadline)),
|
||||
_ = poll.tick() => {
|
||||
let dir = staging.clone();
|
||||
let max = limits.max_bytes;
|
||||
let over = tokio::task::spawn_blocking(move || size_over(&dir, max))
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
if over {
|
||||
return Err(CloneError::TooLarge(limits.max_bytes));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
guard.pid = None;
|
||||
if !output.status.success() {
|
||||
return Err(CloneError::Git(String::from_utf8_lossy(&output.stderr).trim().to_string()));
|
||||
}
|
||||
// A clone that finished under the cap can still have gone over it on its last stretch
|
||||
if size_over(&staging, limits.max_bytes) {
|
||||
return Err(CloneError::TooLarge(limits.max_bytes));
|
||||
}
|
||||
write_stamp(&staging, FETCHED_STAMP);
|
||||
write_stamp(&staging, USED_STAMP);
|
||||
|
||||
if let Some(parent) = dest.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let retired = dest.exists().then(|| staging_dir(cache, owner, repo));
|
||||
if install(&staging, dest, retired.as_deref())? {
|
||||
guard.dir = None;
|
||||
}
|
||||
if let Some(retired) = retired {
|
||||
remove_in_background(retired);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Move a finished clone from `staging` to `dest`, first moving what was there to `retired`.
|
||||
///
|
||||
/// `Ok(false)` when another fetch of the same repository installed one in between; its checkout is
|
||||
/// as good as this one, and `staging` is left for the caller to remove. On failure the previous
|
||||
/// checkout is put back.
|
||||
fn install(staging: &Path, dest: &Path, retired: Option<&Path>) -> std::io::Result<bool> {
|
||||
if let Some(retired) = retired {
|
||||
std::fs::rename(dest, retired)?;
|
||||
}
|
||||
match std::fs::rename(staging, dest) {
|
||||
Ok(()) => Ok(true),
|
||||
Err(_) if dest.join(".git").is_dir() => Ok(false),
|
||||
Err(error) => {
|
||||
if let Some(retired) = retired {
|
||||
let _ = std::fs::rename(retired, dest);
|
||||
}
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `git clone` that makes a fetched checkout, with everything that would let it act on its own
|
||||
/// turned off.
|
||||
fn clone_command(git: &Path, source: &str, staging: &Path, cwd: &Path) -> tokio::process::Command {
|
||||
let staging = staging.to_string_lossy();
|
||||
let mut command = luxe_core::program::captured_command(
|
||||
git,
|
||||
&[
|
||||
"clone",
|
||||
"--depth",
|
||||
"1",
|
||||
"--no-tags",
|
||||
"--quiet",
|
||||
// `--config` rather than `git -c`: it is written into the new repository, so it holds
|
||||
// for the checkout this command makes and for anything run in it afterwards
|
||||
"--config",
|
||||
"core.symlinks=false",
|
||||
source,
|
||||
&staging,
|
||||
],
|
||||
cwd,
|
||||
);
|
||||
command
|
||||
.env("GIT_TERMINAL_PROMPT", "0")
|
||||
.env("GCM_INTERACTIVE", "never")
|
||||
.env("GIT_LFS_SKIP_SMUDGE", "1");
|
||||
command
|
||||
}
|
||||
|
||||
/// A fresh staging directory name under `cache`, carrying the time it was made so [`tidy`] can tell
|
||||
/// a leftover from a clone still running in another Luxe.
|
||||
fn staging_dir(cache: &Path, owner: &str, repo: &str) -> PathBuf {
|
||||
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |since| since.as_nanos());
|
||||
let secs = nanos / 1_000_000_000;
|
||||
cache.join(format!("{STAGING_PREFIX}{secs}-{nanos}-{}-{owner}-{repo}", std::process::id()))
|
||||
}
|
||||
|
||||
/// A clone in progress: on drop, its process tree is killed and its directory removed, which is
|
||||
/// what happens when the deadline, the size cap or a cancelled turn ends it early.
|
||||
struct Staging {
|
||||
dir: Option<PathBuf>,
|
||||
pid: Option<u32>,
|
||||
}
|
||||
|
||||
impl Drop for Staging {
|
||||
fn drop(&mut self) {
|
||||
if let Some(pid) = self.pid {
|
||||
luxe_core::program::kill_tree(pid);
|
||||
}
|
||||
if let Some(dir) = self.dir.take() {
|
||||
remove_in_background(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a directory off the async runtime; a checkout can be thousands of files.
|
||||
fn remove_in_background(dir: PathBuf) {
|
||||
std::thread::spawn(move || {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether the files under `dir` add up to more than `max` bytes. Links are not followed.
|
||||
fn size_over(dir: &Path, max: u64) -> bool {
|
||||
let mut total = 0u64;
|
||||
let mut pending = vec![dir.to_path_buf()];
|
||||
while let Some(dir) = pending.pop() {
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let Ok(kind) = entry.file_type() else { continue };
|
||||
if kind.is_dir() {
|
||||
pending.push(entry.path());
|
||||
} else if let Ok(metadata) = entry.metadata() {
|
||||
total += metadata.len();
|
||||
if total > max {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Clear out the cache: staging directories left behind, checkouts nobody has fetched in
|
||||
/// [`PRUNE_AFTER`], and clones made before this layout existed, which may hold live symbolic links.
|
||||
/// Best effort; a cache that cannot be tidied still works.
|
||||
fn tidy(cache: &Path, now: u64) {
|
||||
let Ok(entries) = std::fs::read_dir(cache) else { return };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = name.strip_prefix(STAGING_PREFIX) {
|
||||
let made = rest.split('-').next().and_then(|secs| secs.parse::<u64>().ok());
|
||||
if made.is_none_or(|made| now.saturating_sub(made) >= STAGING_STALE_AFTER.as_secs()) {
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
}
|
||||
} else if path.join(".git").exists() {
|
||||
// The old `<owner>-<repo>` layout, cloned with symbolic links intact
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
} else {
|
||||
let Ok(repos) = std::fs::read_dir(&path) else { continue };
|
||||
for repo in repos.flatten().map(|repo| repo.path()) {
|
||||
let used = read_stamp(&repo, USED_STAMP).unwrap_or(0);
|
||||
if now.saturating_sub(used) >= PRUNE_AFTER.as_secs() {
|
||||
let _ = std::fs::remove_dir_all(&repo);
|
||||
}
|
||||
}
|
||||
// Only succeeds once the owner has nothing left
|
||||
let _ = std::fs::remove_dir(&path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The reply: where the checkout is, which commit, how fresh, and enough of it to start from.
|
||||
async fn describe(owner: &str, repo: &str, dest: &Path, note: Option<String>) -> ToolResultData {
|
||||
let path = luxe_core::paths::display(dest);
|
||||
let fetched = read_stamp(dest, FETCHED_STAMP).unwrap_or(0);
|
||||
let commit =
|
||||
head_commit(dest).await.map(|commit| format!(", at commit {commit}")).unwrap_or_default();
|
||||
let mut text = format!("{owner}/{repo} is at {path}{commit}, fetched {}.", age(fetched));
|
||||
if let Some(note) = note {
|
||||
text.push(' ');
|
||||
text.push_str(¬e);
|
||||
}
|
||||
text.push_str(
|
||||
"\nSymbolic links in it are plain files holding the link's target, and language servers do \
|
||||
not start there.\n\nTop level:\n",
|
||||
);
|
||||
text.push_str(&top_level_listing(dest));
|
||||
text.push('\n');
|
||||
text.push_str(&readme_preview(dest));
|
||||
text.push_str("\nExplore it with the read, glob, and grep tools at that path.");
|
||||
ToolResultData::text(text)
|
||||
}
|
||||
|
||||
/// `abc1234 (2026-10-01)` for the checkout's `HEAD`, when git can say.
|
||||
async fn head_commit(dest: &Path) -> Option<String> {
|
||||
let git = luxe_core::program::resolve("git")?;
|
||||
let command =
|
||||
luxe_core::program::captured_command(git, &["log", "-1", "--format=%h (%cs)"], dest);
|
||||
let output = luxe_core::program::run_bounded(command, Duration::from_secs(5)).await.ok()?;
|
||||
let line = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
(output.status.success() && !line.is_empty()).then_some(line)
|
||||
}
|
||||
|
||||
/// Sorted top-level entries, directories suffixed `/`, bounded. Entry types are read without
|
||||
/// following links.
|
||||
fn top_level_listing(dir: &Path) -> String {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return " (unreadable)".to_string() };
|
||||
let mut names: Vec<String> = entries
|
||||
.flatten()
|
||||
.filter(|entry| entry.file_name() != ".git")
|
||||
.map(|entry| {
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
match entry.file_type() {
|
||||
Ok(kind) if kind.is_dir() => format!("{name}/"),
|
||||
_ => name,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
names.sort();
|
||||
names.truncate(60);
|
||||
names.iter().map(|name| format!(" {name}")).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
/// The first ~1.5KB of the README, if there is one and it is a regular file.
|
||||
///
|
||||
/// A link is skipped even though the clone should not contain any: this is the read that sends a
|
||||
/// file's contents to the model with no further step, so it does not get to trust the clone.
|
||||
fn readme_preview(dir: &Path) -> String {
|
||||
use std::io::Read;
|
||||
for candidate in ["README.md", "README.markdown", "README.rst", "README.txt", "README"] {
|
||||
let path = dir.join(candidate);
|
||||
if !std::fs::symlink_metadata(&path).is_ok_and(|metadata| metadata.is_file()) {
|
||||
continue;
|
||||
}
|
||||
let mut content = String::new();
|
||||
let Ok(file) = std::fs::File::open(&path) else { continue };
|
||||
if file.take(16 * 1024).read_to_string(&mut content).is_err() {
|
||||
continue;
|
||||
}
|
||||
let preview: String = content.chars().take(1500).collect();
|
||||
return format!("\nREADME ({candidate}):\n{preview}\n");
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
|
||||
fn read_stamp(checkout: &Path, stamp: &str) -> Option<u64> {
|
||||
std::fs::read_to_string(checkout.join(".git").join(stamp)).ok()?.trim().parse().ok()
|
||||
}
|
||||
|
||||
fn write_stamp(checkout: &Path, stamp: &str) {
|
||||
let _ = std::fs::write(checkout.join(".git").join(stamp), now_secs().to_string());
|
||||
}
|
||||
|
||||
fn now_secs() -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |since| since.as_secs())
|
||||
}
|
||||
|
||||
/// How long ago `then` was, in the largest whole unit.
|
||||
fn age(then: u64) -> String {
|
||||
let secs = now_secs().saturating_sub(then);
|
||||
let (count, unit) = match secs {
|
||||
0..60 => return "just now".to_string(),
|
||||
60..3_600 => (secs / 60, "minute"),
|
||||
3_600..86_400 => (secs / 3_600, "hour"),
|
||||
_ => (secs / 86_400, "day"),
|
||||
};
|
||||
let plural = if count == 1 { "" } else { "s" };
|
||||
format!("{count} {unit}{plural} ago")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
342
crates/luxe-tools/src/web/clone/tests.rs
Normal file
342
crates/luxe-tools/src/web/clone/tests.rs
Normal file
@@ -0,0 +1,342 @@
|
||||
use super::*;
|
||||
|
||||
const TEST_LIMITS: Limits = Limits { max_bytes: MAX_CLONE_BYTES, deadline: CLONE_DEADLINE };
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) {
|
||||
let status = std::process::Command::new("git")
|
||||
.args(["-c", "user.email=t@example.com", "-c", "user.name=t", "-c", "commit.gpgsign=false"])
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.status()
|
||||
.expect("git runs");
|
||||
assert!(status.success(), "git {args:?}");
|
||||
}
|
||||
|
||||
/// A repository with one committed file, and the `file://` URL git can clone it from.
|
||||
fn upstream(dir: &Path, file: &str, body: &str) -> String {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
git(dir, &["init", "-q"]);
|
||||
std::fs::write(dir.join(file), body).unwrap();
|
||||
git(dir, &["add", "-A"]);
|
||||
git(dir, &["commit", "-qm", "first"]);
|
||||
url::Url::from_directory_path(dir).expect("absolute path").to_string()
|
||||
}
|
||||
|
||||
fn text(result: &ToolResultData) -> String {
|
||||
match &result.content[0] {
|
||||
luxe_core::ContentBlock::Text(text) => text.clone(),
|
||||
other => panic!("expected text, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn staging_left(cache: &Path) -> Vec<String> {
|
||||
std::fs::read_dir(cache)
|
||||
.map(|entries| {
|
||||
entries
|
||||
.flatten()
|
||||
.map(|entry| entry.file_name().to_string_lossy().into_owned())
|
||||
.filter(|name| name.starts_with(STAGING_PREFIX))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The incident this module exists for: a repository whose README is a link to the project's
|
||||
/// `.env` handed the secret to the model in `web_fetch`'s own reply.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn a_link_to_the_projects_env_is_checked_out_as_text_and_the_secret_stays_home() {
|
||||
let scratch = tempfile::tempdir().unwrap();
|
||||
let source = scratch.path().join("evil");
|
||||
std::fs::create_dir_all(&source).unwrap();
|
||||
git(&source, &["init", "-q"]);
|
||||
// From `<project>/.luxe/gh-cache/o/r/`, four levels up is the project
|
||||
std::os::unix::fs::symlink("../../../../.env", source.join("README.md")).unwrap();
|
||||
git(&source, &["add", "-A"]);
|
||||
git(&source, &["commit", "-qm", "link"]);
|
||||
let project = scratch.path().join("project");
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
std::fs::write(project.join(".env"), "API_KEY=sk-live-SECRET\n").unwrap();
|
||||
|
||||
let url = url::Url::from_directory_path(&source).unwrap().to_string();
|
||||
let result = fetch_into(&url, "o", "r", &project, TEST_LIMITS).await;
|
||||
|
||||
assert!(!result.is_error, "{}", text(&result));
|
||||
assert!(!text(&result).contains("sk-live-SECRET"), "{}", text(&result));
|
||||
let readme = luxe_core::fetched::cache_dir(&project).join("o").join("r").join("README.md");
|
||||
let metadata = std::fs::symlink_metadata(&readme).unwrap();
|
||||
assert!(metadata.is_file(), "checked out as a plain file, not a link");
|
||||
assert_eq!(std::fs::read_to_string(&readme).unwrap(), "../../../../.env");
|
||||
}
|
||||
|
||||
/// The preview is the read that reaches the model with no further step, so it refuses a link
|
||||
/// even where one got into a checkout some other way.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_readme_preview_does_not_follow_a_link() {
|
||||
let scratch = tempfile::tempdir().unwrap();
|
||||
std::fs::write(scratch.path().join("secret"), "API_KEY=sk-live-SECRET").unwrap();
|
||||
let checkout = scratch.path().join("checkout");
|
||||
std::fs::create_dir_all(&checkout).unwrap();
|
||||
std::os::unix::fs::symlink("../secret", checkout.join("README.md")).unwrap();
|
||||
std::fs::write(checkout.join("README"), "the real one").unwrap();
|
||||
let preview = readme_preview(&checkout);
|
||||
assert!(!preview.contains("sk-live"), "{preview}");
|
||||
assert!(preview.contains("the real one"), "falls through to the next candidate");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_clone_is_checked_out_with_its_commit_and_readme() {
|
||||
let scratch = tempfile::tempdir().unwrap();
|
||||
let up = scratch.path().join("up");
|
||||
std::fs::create_dir_all(up.join("src")).unwrap();
|
||||
std::fs::write(up.join("src").join("lib.rs"), "").unwrap();
|
||||
let url = upstream(&up, "README.md", "# Widget\nIt widgets.\n");
|
||||
let head = std::process::Command::new("git")
|
||||
.args(["rev-parse", "--short", "HEAD"])
|
||||
.current_dir(&up)
|
||||
.output()
|
||||
.unwrap();
|
||||
let head = String::from_utf8_lossy(&head.stdout).trim().to_string();
|
||||
let project = scratch.path().join("project");
|
||||
let result = fetch_into(&url, "acme", "widget", &project, TEST_LIMITS).await;
|
||||
let said = text(&result);
|
||||
assert!(!result.is_error, "{said}");
|
||||
assert!(said.contains("acme/widget is at"), "{said}");
|
||||
assert!(said.contains("fetched just now"), "{said}");
|
||||
assert!(said.contains(&format!(", at commit {head} (")), "names the commit: {said}");
|
||||
assert!(said.contains("It widgets."), "README preview: {said}");
|
||||
assert!(said.contains(" README.md"), "listing: {said}");
|
||||
assert!(said.contains(" src/"), "a directory is marked as one: {said}");
|
||||
assert!(!said.contains(" README.md/"), "and a file is not: {said}");
|
||||
assert!(staging_left(&luxe_core::fetched::cache_dir(&project)).is_empty());
|
||||
}
|
||||
|
||||
/// The numbers the guide quotes, so changing one is a decision rather than a slip.
|
||||
#[test]
|
||||
fn the_limits_are_the_ones_the_guide_promises() {
|
||||
assert_eq!(MAX_CLONE_BYTES, 500 * 1024 * 1024, "500 MB on disk");
|
||||
assert_eq!(CLONE_DEADLINE, Duration::from_secs(45));
|
||||
assert_eq!(REFRESH_AFTER, Duration::from_secs(86_400), "a day");
|
||||
assert_eq!(PRUNE_AFTER, Duration::from_secs(14 * 86_400), "14 days");
|
||||
assert_eq!(STAGING_STALE_AFTER, Duration::from_secs(3_600));
|
||||
}
|
||||
|
||||
/// A staging directory carries the second it was made, which is all that stops one Luxe from
|
||||
/// tidying away a clone another is still making.
|
||||
#[test]
|
||||
fn a_staging_directory_made_just_now_survives_tidying() {
|
||||
let scratch = tempfile::tempdir().unwrap();
|
||||
let staging = staging_dir(scratch.path(), "o", "r");
|
||||
std::fs::create_dir_all(&staging).unwrap();
|
||||
tidy(scratch.path(), now_secs());
|
||||
assert!(staging.exists());
|
||||
tidy(scratch.path(), now_secs() + STAGING_STALE_AFTER.as_secs());
|
||||
assert!(!staging.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installing_replaces_a_checkout_and_defers_to_one_installed_meanwhile() {
|
||||
let scratch = tempfile::tempdir().unwrap();
|
||||
let checkout = |path: &Path, marker: &str| {
|
||||
std::fs::create_dir_all(path.join(".git")).unwrap();
|
||||
std::fs::write(path.join("marker"), marker).unwrap();
|
||||
};
|
||||
let marker = |path: &Path| std::fs::read_to_string(path.join("marker")).unwrap();
|
||||
let (staging, dest, retired) =
|
||||
(scratch.path().join("s"), scratch.path().join("d"), scratch.path().join("r"));
|
||||
|
||||
checkout(&staging, "new");
|
||||
assert!(install(&staging, &dest, None).unwrap(), "nothing there yet");
|
||||
assert_eq!(marker(&dest), "new");
|
||||
|
||||
checkout(&staging, "newer");
|
||||
assert!(install(&staging, &dest, Some(&retired)).unwrap(), "a refresh");
|
||||
assert_eq!((marker(&dest), marker(&retired)), ("newer".into(), "new".into()));
|
||||
|
||||
checkout(&staging, "late");
|
||||
assert!(!install(&staging, &dest, None).unwrap(), "another fetch got there first");
|
||||
assert_eq!(marker(&dest), "newer", "and its checkout is kept");
|
||||
|
||||
let junk = scratch.path().join("junk");
|
||||
std::fs::create_dir_all(&junk).unwrap();
|
||||
std::fs::write(junk.join("file"), "").unwrap();
|
||||
assert!(install(&staging, &junk, None).is_err(), "a directory that is not a checkout");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_size_cap_is_exceeded_only_past_it() {
|
||||
let scratch = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(scratch.path().join("nested")).unwrap();
|
||||
std::fs::write(scratch.path().join("a"), [0u8; 600]).unwrap();
|
||||
std::fs::write(scratch.path().join("nested").join("b"), [0u8; 400]).unwrap();
|
||||
assert!(!size_over(scratch.path(), 1_000), "exactly at the cap is within it");
|
||||
assert!(size_over(scratch.path(), 999), "nested files count");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_readme_preview_is_its_first_1500_characters() {
|
||||
let scratch = tempfile::tempdir().unwrap();
|
||||
let body: String = (0..3_000).map(|index| if index == 1_499 { 'Z' } else { 'a' }).collect();
|
||||
std::fs::write(scratch.path().join("README.md"), body).unwrap();
|
||||
let preview = readme_preview(scratch.path());
|
||||
assert!(preview.contains('Z'), "the 1500th character is in it");
|
||||
assert_eq!(preview.chars().filter(|c| *c == 'a').count(), 1_499);
|
||||
}
|
||||
|
||||
/// A repository git cannot reach fails fast and leaves nothing a later fetch would mistake for
|
||||
/// a finished checkout.
|
||||
#[tokio::test]
|
||||
async fn a_failed_clone_leaves_nothing_behind() {
|
||||
let scratch = tempfile::tempdir().unwrap();
|
||||
let missing = url::Url::from_directory_path(scratch.path().join("nowhere")).unwrap();
|
||||
let project = scratch.path().join("project");
|
||||
let result = fetch_into(missing.as_str(), "o", "r", &project, TEST_LIMITS).await;
|
||||
assert!(result.is_error);
|
||||
assert!(text(&result).contains("Could not clone o/r"), "{}", text(&result));
|
||||
let cache = luxe_core::fetched::cache_dir(&project);
|
||||
assert!(!cache.join("o").join("r").exists());
|
||||
assert!(staging_left(&cache).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_repository_over_the_cap_is_stopped_and_removed() {
|
||||
let scratch = tempfile::tempdir().unwrap();
|
||||
let url = upstream(&scratch.path().join("up"), "big.txt", &"x".repeat(64 * 1024));
|
||||
let project = scratch.path().join("project");
|
||||
let tiny = Limits { max_bytes: 1024, ..TEST_LIMITS };
|
||||
let result = fetch_into(&url, "o", "r", &project, tiny).await;
|
||||
assert!(result.is_error);
|
||||
assert!(text(&result).contains("larger than"), "{}", text(&result));
|
||||
let cache = luxe_core::fetched::cache_dir(&project);
|
||||
assert!(!cache.join("o").join("r").exists());
|
||||
// The staging directory goes on a background thread
|
||||
for _ in 0..50 {
|
||||
if staging_left(&cache).is_empty() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert!(staging_left(&cache).is_empty());
|
||||
}
|
||||
|
||||
/// A fresh checkout is reused as it stands; a stale one is cloned again, and a stale one that
|
||||
/// cannot be refreshed is still served, saying how old it is.
|
||||
#[tokio::test]
|
||||
async fn a_checkout_is_reused_then_refreshed_once_it_goes_stale() {
|
||||
let scratch = tempfile::tempdir().unwrap();
|
||||
let up = scratch.path().join("up");
|
||||
let url = upstream(&up, "a.txt", "one");
|
||||
let project = scratch.path().join("project");
|
||||
let checkout = luxe_core::fetched::cache_dir(&project).join("o").join("r");
|
||||
assert!(!fetch_into(&url, "o", "r", &project, TEST_LIMITS).await.is_error);
|
||||
|
||||
std::fs::write(up.join("b.txt"), "two").unwrap();
|
||||
git(&up, &["add", "-A"]);
|
||||
git(&up, &["commit", "-qm", "second"]);
|
||||
assert!(!fetch_into(&url, "o", "r", &project, TEST_LIMITS).await.is_error);
|
||||
assert!(!checkout.join("b.txt").exists(), "a fresh checkout is not cloned again");
|
||||
|
||||
let two_days_ago = now_secs() - 2 * 24 * 60 * 60;
|
||||
std::fs::write(checkout.join(".git").join(FETCHED_STAMP), two_days_ago.to_string()).unwrap();
|
||||
assert!(!fetch_into(&url, "o", "r", &project, TEST_LIMITS).await.is_error);
|
||||
assert!(checkout.join("b.txt").exists(), "a stale checkout is refreshed");
|
||||
|
||||
std::fs::write(checkout.join(".git").join(FETCHED_STAMP), two_days_ago.to_string()).unwrap();
|
||||
std::fs::remove_dir_all(&up).unwrap();
|
||||
let result = fetch_into(&url, "o", "r", &project, TEST_LIMITS).await;
|
||||
assert!(!result.is_error, "{}", text(&result));
|
||||
assert!(text(&result).contains("Could not refresh it"), "{}", text(&result));
|
||||
assert!(text(&result).contains("2 days ago"), "{}", text(&result));
|
||||
assert!(checkout.join("b.txt").exists(), "the old copy survives a failed refresh");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tidying_clears_leftovers_old_layouts_and_unused_checkouts() {
|
||||
let scratch = tempfile::tempdir().unwrap();
|
||||
let cache = scratch.path().to_path_buf();
|
||||
let now = 10_000_000;
|
||||
let checkout = |owner: &str, repo: &str, used: u64| {
|
||||
let git = cache.join(owner).join(repo).join(".git");
|
||||
std::fs::create_dir_all(&git).unwrap();
|
||||
std::fs::write(git.join(USED_STAMP), used.to_string()).unwrap();
|
||||
};
|
||||
checkout("keep", "recent", now - 60);
|
||||
checkout("gone", "unused", now - PRUNE_AFTER.as_secs());
|
||||
std::fs::create_dir_all(cache.join("acme-legacy").join(".git")).unwrap();
|
||||
let old = format!("{STAGING_PREFIX}{}-1-1-o-r", now - STAGING_STALE_AFTER.as_secs());
|
||||
let live = format!("{STAGING_PREFIX}{}-1-1-o-r", now - 30);
|
||||
std::fs::create_dir_all(cache.join(&old)).unwrap();
|
||||
std::fs::create_dir_all(cache.join(&live)).unwrap();
|
||||
|
||||
tidy(&cache, now);
|
||||
|
||||
assert!(cache.join("keep").join("recent").exists());
|
||||
assert!(!cache.join("gone").exists(), "the unused checkout and its empty owner");
|
||||
assert!(!cache.join("acme-legacy").exists(), "cloned before links were made plain");
|
||||
assert!(!cache.join(&old).exists(), "a staging directory left behind");
|
||||
assert!(cache.join(&live).exists(), "a clone still running elsewhere");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_plain_owner_and_repository_name_becomes_a_path() {
|
||||
let cache = Path::new("/p/.luxe/gh-cache");
|
||||
assert_eq!(
|
||||
checkout_dir(cache, "rust-lang", "cargo"),
|
||||
Some(cache.join("rust-lang").join("cargo"))
|
||||
);
|
||||
assert!(checkout_dir(cache, "acme", ".github").is_some(), "an org profile repository");
|
||||
assert_ne!(checkout_dir(cache, "a-b", "c"), checkout_dir(cache, "a", "b-c"));
|
||||
for (owner, repo) in [
|
||||
("o", ".."),
|
||||
("o", "."),
|
||||
("o", ".git"),
|
||||
("..", "r"),
|
||||
("o/x", "r"),
|
||||
("o", "r/x"),
|
||||
("o", "r%2F"),
|
||||
("", "r"),
|
||||
("o", ""),
|
||||
("o.x", "r"),
|
||||
] {
|
||||
assert_eq!(checkout_dir(cache, owner, repo), None, "{owner}/{repo}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Each of these is a way a clone could act on its own or wait on a person; pinned so none
|
||||
/// of them goes missing quietly.
|
||||
#[test]
|
||||
fn the_clone_turns_off_links_prompts_and_lfs() {
|
||||
let command = clone_command(
|
||||
Path::new("git"),
|
||||
"https://github.com/o/r.git",
|
||||
Path::new("s"),
|
||||
Path::new("."),
|
||||
);
|
||||
let command = command.as_std();
|
||||
let args: Vec<String> =
|
||||
command.get_args().map(|arg| arg.to_string_lossy().into_owned()).collect();
|
||||
let at = args.iter().position(|arg| arg == "--config").expect("--config");
|
||||
assert_eq!(args[at + 1], "core.symlinks=false");
|
||||
assert!(args.windows(2).any(|pair| pair == ["--depth", "1"]), "{args:?}");
|
||||
let env = |key: &str| {
|
||||
command
|
||||
.get_envs()
|
||||
.find(|(name, _)| *name == key)
|
||||
.and_then(|(_, value)| value.map(|value| value.to_string_lossy().into_owned()))
|
||||
};
|
||||
assert_eq!(env("GIT_TERMINAL_PROMPT").as_deref(), Some("0"));
|
||||
assert_eq!(env("GCM_INTERACTIVE").as_deref(), Some("never"));
|
||||
assert_eq!(env("GIT_LFS_SKIP_SMUDGE").as_deref(), Some("1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ages_read_in_the_largest_whole_unit() {
|
||||
let now = now_secs();
|
||||
assert_eq!(age(now), "just now");
|
||||
assert_eq!(age(now - 60), "1 minute ago");
|
||||
assert_eq!(age(now - 3 * 3_600), "3 hours ago");
|
||||
assert_eq!(age(now - 2 * 86_400), "2 days ago");
|
||||
}
|
||||
247
crates/luxe-tools/src/web/fetch.rs
Normal file
247
crates/luxe-tools/src/web/fetch.rs
Normal file
@@ -0,0 +1,247 @@
|
||||
//! Fetch — a page as readable markdown, with a stealth retry and a clone for a GitHub repository.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Default polite user agent.
|
||||
pub(super) const UA_DEFAULT: &str = concat!("Luxe/", env!("CARGO_PKG_VERSION"));
|
||||
/// Browser-like user agent for the bot-protection-bypass fallback.
|
||||
pub(super) const UA_STEALTH: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
|
||||
|
||||
/// Whether `web_fetch` may read from the machine it runs on.
|
||||
///
|
||||
/// It may. Luxe ships an unrestricted `bash`, so `curl http://127.0.0.1:4321` is already a tool call
|
||||
/// away — refusing the same origin here protects nothing and costs the ordinary case of reading your
|
||||
/// own dev server. The boundary that *is* real (private LAN, cloud metadata) is unaffected; see
|
||||
/// [`crate::ssrf`].
|
||||
pub(super) const LOCAL: crate::ssrf::LocalAccess = crate::ssrf::LocalAccess::Allowed;
|
||||
|
||||
/// Fetch a URL (SSRF-guarded) and reduce it to readable markdown.
|
||||
pub(super) async fn fetch_url(url: &str) -> Result<String, WebError> {
|
||||
let fetched = crate::ssrf::safe_get(url, UA_DEFAULT, LOCAL).await?;
|
||||
Ok(fetched.reduced(|html| extract_readable(html, url)))
|
||||
}
|
||||
|
||||
/// Same, with a browser-like user agent (for bot-protected pages).
|
||||
pub(super) async fn fetch_url_stealth(url: &str) -> Result<String, WebError> {
|
||||
let fetched = crate::ssrf::safe_get(url, UA_STEALTH, LOCAL).await?;
|
||||
Ok(fetched.reduced(|html| extract_readable(html, url)))
|
||||
}
|
||||
|
||||
/// Reduce an HTML page to readable markdown: extract the main article with a readability pass, then
|
||||
/// convert that to Markdown. Falls back to whole-page conversion when readability finds nothing.
|
||||
pub(super) fn extract_readable(html: &str, url: &str) -> String {
|
||||
if let Some((title, content_html)) = readability(html, url) {
|
||||
let body = htmd::convert(&content_html).unwrap_or(content_html);
|
||||
let body = body.trim();
|
||||
if body.is_empty() {
|
||||
fallback_markdown(html)
|
||||
} else if title.trim().is_empty() {
|
||||
body.to_string()
|
||||
} else {
|
||||
format!("# {}\n\n{body}", title.trim())
|
||||
}
|
||||
} else {
|
||||
fallback_markdown(html)
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the readability pass, returning `(title, main_content_html)` when it succeeds.
|
||||
pub(super) fn readability(html: &str, url: &str) -> Option<(String, String)> {
|
||||
let mut readability = dom_smoothie::Readability::new(html, Some(url), None).ok()?;
|
||||
let article = readability.parse().ok()?;
|
||||
Some((article.title.to_string(), article.content.to_string()))
|
||||
}
|
||||
|
||||
/// Whole-page HTML→Markdown, or the raw HTML if even that fails.
|
||||
pub(super) fn fallback_markdown(html: &str) -> String {
|
||||
htmd::convert(html).unwrap_or_else(|_| html.to_string())
|
||||
}
|
||||
|
||||
/// `(owner, repo)` for a GitHub repo-root URL (`github.com/owner/repo`), else `None`. Deeper paths
|
||||
/// (`/blob/...`, `/tree/...`, `/issues`, ...) are not repo roots.
|
||||
pub(super) fn github_repo(url: &Url) -> Option<(String, String)> {
|
||||
if url.host_str()? != "github.com" {
|
||||
return None;
|
||||
}
|
||||
let segs: Vec<&str> = url.path_segments()?.filter(|s| !s.is_empty()).collect();
|
||||
(segs.len() == 2).then(|| (segs[0].to_string(), segs[1].trim_end_matches(".git").to_string()))
|
||||
}
|
||||
|
||||
/// Map a GitHub blob URL (`github.com/owner/repo/blob/<ref>/<path>`) to its raw content URL.
|
||||
pub(super) fn github_blob_raw(url_str: &str) -> Option<String> {
|
||||
let url = Url::parse(url_str).ok()?;
|
||||
if url.host_str()? != "github.com" {
|
||||
return None;
|
||||
}
|
||||
let segs: Vec<&str> = url.path_segments()?.filter(|s| !s.is_empty()).collect();
|
||||
if segs.len() >= 5 && segs[2] == "blob" {
|
||||
let rest = segs[3..].join("/");
|
||||
Some(format!("https://raw.githubusercontent.com/{}/{}/{}", segs[0], segs[1], rest))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// web_fetch tool — fetch URL and extract readable content.
|
||||
pub struct WebFetchTool {
|
||||
pub(super) config: Arc<RwLock<WebConfig>>,
|
||||
pub(super) clone_repositories: bool,
|
||||
}
|
||||
|
||||
/// The tool description, which mentions cloning only where it is on.
|
||||
pub(super) fn web_fetch_description(clone_repositories: bool) -> String {
|
||||
let github = if clone_repositories {
|
||||
"A GitHub repo URL is shallow-cloned into the project's `.luxe/gh-cache/` and its path \
|
||||
returned so you can read/grep the real files; a GitHub blob URL fetches the raw file."
|
||||
} else {
|
||||
"A GitHub blob URL fetches the raw file."
|
||||
};
|
||||
format!(
|
||||
"Fetch a URL and extract the main content as Markdown (readability). {github} Long pages \
|
||||
come back one window at a time — the reply names the exact `offset` to pass for the next \
|
||||
one. Reaches public sites and this machine (localhost/127.0.0.1/::1); refuses \
|
||||
private-network hosts and cloud-metadata endpoints. Retries bot-protected pages behind a \
|
||||
browser user-agent, then in a real browser where one is configured."
|
||||
)
|
||||
}
|
||||
|
||||
/// Characters returned per fetched page.
|
||||
///
|
||||
/// Sized from a real measurement rather than a guess: the English Wikipedia article on Rust comes
|
||||
/// back as ~187,000 characters, roughly 47,000 tokens — close to a quarter of a 200K window spent
|
||||
/// on a single call.
|
||||
pub(super) const FETCH_MAX_CHARS: usize = 50_000;
|
||||
|
||||
/// Return one window of a fetched page, and say exactly how to get the next one.
|
||||
///
|
||||
/// A cap alone would be a trap. Plenty of pages — an RFC, a changelog, a single-page API reference
|
||||
/// — have no anchors and no sub-pages, so "fetch something more specific" is advice that cannot be
|
||||
/// followed and the remainder is simply unreachable. Paging by character offset always exists, and
|
||||
/// naming the *exact* next offset means the caller never has to work one out.
|
||||
pub(super) fn page_of(content: &str, offset: usize) -> String {
|
||||
let total = content.chars().count();
|
||||
if offset >= total && offset > 0 {
|
||||
return format!(
|
||||
"Offset {offset} is past the end of this page ({total} characters). \
|
||||
Re-fetch with offset 0 to start over."
|
||||
);
|
||||
}
|
||||
let window: String = content.chars().skip(offset).take(FETCH_MAX_CHARS).collect();
|
||||
let end = offset + window.chars().count();
|
||||
if end >= total {
|
||||
return if offset > 0 {
|
||||
format!("[characters {offset}–{end} of {total} — end of page]\n{window}")
|
||||
} else {
|
||||
window
|
||||
};
|
||||
}
|
||||
format!(
|
||||
"[characters {offset}–{end} of {total}]\n{window}\n\n… {} characters remain. \
|
||||
Continue with the same url and offset: {end}",
|
||||
total - end
|
||||
)
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for WebFetchTool {
|
||||
fn name(&self) -> &str {
|
||||
"web_fetch"
|
||||
}
|
||||
|
||||
/// A fetch is a network round-trip, so it takes the network bound rather than the generous
|
||||
/// default. This backs the per-request timeouts in `crate::ssrf` instead of duplicating them:
|
||||
/// those bound each hop, and a redirect chain plus the stealth retry still adds up to minutes —
|
||||
/// which is exactly what a host that accepts the connection and then says nothing costs.
|
||||
fn timeout(&self) -> Option<std::time::Duration> {
|
||||
Some(luxe_core::tool::NETWORK_TOOL_TIMEOUT)
|
||||
}
|
||||
|
||||
fn schema(&self) -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: "web_fetch".to_string(),
|
||||
description: web_fetch_description(self.clone_repositories),
|
||||
parameters: serde_json::json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"url": {"type": "string", "description": "URL to fetch"},
|
||||
"offset": {
|
||||
"type": "integer",
|
||||
"description": "Character offset into the page, for reading a long page in \
|
||||
sequence. Use the offset the previous reply reported."
|
||||
}
|
||||
},
|
||||
"required": ["url"]
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(&self, args: serde_json::Value, cx: &ToolContext) -> ToolResultData {
|
||||
let url = match args.get("url") {
|
||||
Some(v) => v.as_str().unwrap_or(""),
|
||||
None => {
|
||||
return ToolResultData::error("Error: 'url' argument is required");
|
||||
}
|
||||
};
|
||||
|
||||
let offset = args.get("offset").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
|
||||
|
||||
// A GitHub repo URL is far more useful cloned (real files + a path to explore) than scraped.
|
||||
if self.clone_repositories {
|
||||
if let Some((owner, repo)) = Url::parse(url).ok().as_ref().and_then(github_repo) {
|
||||
return clone::fetch_repository(&owner, &repo, cx).await;
|
||||
}
|
||||
}
|
||||
// A GitHub blob URL → its raw file (skips the noisy rendered page).
|
||||
let effective = github_blob_raw(url).unwrap_or_else(|| url.to_string());
|
||||
let url = effective.as_str();
|
||||
|
||||
let config = self.config.read().await;
|
||||
let page = fetch_with_fallbacks(url, &config).await;
|
||||
match page {
|
||||
Ok(content) => ToolResultData::text(page_of(&content, offset)),
|
||||
Err(attempts) => ToolResultData::error(format!("Fetch failed. {attempts}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch `url`, escalating through the ways of reading a page that does not want to be read.
|
||||
///
|
||||
/// Plainly first, then behind a browser user-agent, then — only where a Firecrawl key says we may
|
||||
/// — in an actual browser. Each step is strictly more capable and strictly more expensive, so none
|
||||
/// of them runs until the cheaper one has failed. A silent host skips the retries entirely: a
|
||||
/// browser cannot make an unanswered socket answer, and three thirty-second attempts against a
|
||||
/// dead domain is the minute that looks like a hung agent.
|
||||
///
|
||||
/// The error names every attempt, because "fetch failed" for a page that is merely JavaScript is a
|
||||
/// different problem from one that is offline, and the caller can only tell from the attempts.
|
||||
pub(super) async fn fetch_with_fallbacks(url: &str, config: &WebConfig) -> Result<String, String> {
|
||||
let first = match fetch_url(url).await {
|
||||
Ok(content) => return Ok(content),
|
||||
Err(error) => error,
|
||||
};
|
||||
if !first.worth_a_second_try() {
|
||||
return Err(format!("{first}"));
|
||||
}
|
||||
|
||||
let mut attempts = vec![format!("plain: {first}")];
|
||||
if config.enable_stealth {
|
||||
match fetch_url_stealth(url).await {
|
||||
Ok(content) => return Ok(content),
|
||||
Err(error) => attempts.push(format!("browser user-agent: {error}")),
|
||||
}
|
||||
}
|
||||
if let Some(key) = config.firecrawl_api_key.as_deref() {
|
||||
let firecrawl = crate::firecrawl::FirecrawlBackend::new(key.to_string());
|
||||
match firecrawl.scrape(url).await {
|
||||
Ok(content) => return Ok(content),
|
||||
Err(error) => attempts.push(format!("rendered browser: {error}")),
|
||||
}
|
||||
} else {
|
||||
attempts.push(
|
||||
"rendered browser: not tried — set FIRECRAWL_API_KEY to read pages that build \
|
||||
themselves in JavaScript"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
Err(attempts.join(" / "))
|
||||
}
|
||||
166
crates/luxe-tools/src/web/render.rs
Normal file
166
crates/luxe-tools/src/web/render.rs
Normal file
@@ -0,0 +1,166 @@
|
||||
//! Rendering — search hits as text a model can read, and the HTML to plain-text clean-up they need.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// `YYYY-MM-DD` for a Unix timestamp, by civil-date arithmetic (no date dependency in the tree).
|
||||
pub(super) fn iso_date(secs: u64) -> String {
|
||||
let days = (secs / 86_400) as i64;
|
||||
// Howard Hinnant's civil_from_days.
|
||||
let z = days + 719_468;
|
||||
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
|
||||
let doe = z - era * 146_097;
|
||||
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let y = yoe + era * 400;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let y = if m <= 2 { y + 1 } else { y };
|
||||
format!("{y:04}-{m:02}-{d:02}")
|
||||
}
|
||||
|
||||
/// Results as compact markdown: the queries that ran, then each hit with its passage.
|
||||
///
|
||||
/// Not raw JSON. A pretty-printed array of `{title, url, snippet}` spends a third of its characters
|
||||
/// on punctuation and field names the model already knows.
|
||||
///
|
||||
/// `caveats` names any filter the backend could not apply, and leads rather than trails: a model
|
||||
/// reading a domain-filtered list that was never filtered will draw a conclusion from it, and the
|
||||
/// correction has to arrive before the results do.
|
||||
pub(super) fn render_hits(queries: &[String], hits: &[SearchHit], caveats: &[String]) -> String {
|
||||
let mut out = String::new();
|
||||
for caveat in caveats {
|
||||
out.push_str(&format!("Note: {caveat}\n"));
|
||||
}
|
||||
if !caveats.is_empty() {
|
||||
out.push('\n');
|
||||
}
|
||||
if hits.is_empty() {
|
||||
out.push_str(&format!("No results for {}.", queries.join(" / ")));
|
||||
return out;
|
||||
}
|
||||
if queries.len() > 1 {
|
||||
out.push_str(&format!("Searched: {}\n\n", queries.join(" · ")));
|
||||
}
|
||||
for (index, hit) in hits.iter().enumerate() {
|
||||
out.push_str(&format!(
|
||||
"{}. {}\n {}\n",
|
||||
index + 1,
|
||||
plain_text(&hit.title, TITLE_CHARS),
|
||||
hit.url
|
||||
));
|
||||
let snippet = plain_text(&hit.snippet, SNIPPET_CHARS);
|
||||
if !snippet.is_empty() {
|
||||
out.push_str(&format!(" {snippet}\n"));
|
||||
}
|
||||
}
|
||||
crate::output_limit::cap_lines(
|
||||
out.trim_end(),
|
||||
SEARCH_MAX_LINES,
|
||||
"lines",
|
||||
"Narrow the query, or `web_fetch` a specific result for its full text.",
|
||||
)
|
||||
}
|
||||
|
||||
/// Most rendered lines a search returns, matching the bound the other search tools apply.
|
||||
pub(super) const SEARCH_MAX_LINES: usize = 200;
|
||||
|
||||
/// Longest snippet kept per result. Generous, because answering without a follow-up fetch is the
|
||||
/// point — but bounded, because Firecrawl's description can be several thousand characters of a
|
||||
/// page's markdown, and ten of those is a search that costs more than the page it replaced.
|
||||
pub(super) const SNIPPET_CHARS: usize = 1_000;
|
||||
|
||||
/// Longest title kept. A title that runs on is a page with a bad title, not information.
|
||||
pub(super) const TITLE_CHARS: usize = 160;
|
||||
|
||||
/// One line of readable text from whatever markup a vendor happened to send.
|
||||
///
|
||||
/// Every backend decorates differently and none of it survives being read aloud: Brave wraps the
|
||||
/// matched words in `<strong>`, Firecrawl hands back the page's own markdown — headings, fences and
|
||||
/// all — and any of them may return an HTML entity. Left alone, a numbered list of results turns
|
||||
/// into a numbered list of markup, which costs tokens and reads worse.
|
||||
pub(super) fn plain_text(raw: &str, limit: usize) -> String {
|
||||
let raw = unlink(raw);
|
||||
let mut out = String::with_capacity(raw.len());
|
||||
let mut in_tag = false;
|
||||
let mut last_was_space = true;
|
||||
for ch in raw.chars() {
|
||||
match ch {
|
||||
'<' => in_tag = true,
|
||||
'>' if in_tag => in_tag = false,
|
||||
_ if in_tag => {}
|
||||
_ if ch.is_whitespace() => {
|
||||
if !last_was_space {
|
||||
out.push(' ');
|
||||
last_was_space = true;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
out.push(ch);
|
||||
last_was_space = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
let out = decode_entities(out.trim());
|
||||
match out.chars().count() > limit {
|
||||
true => out.chars().take(limit).collect::<String>() + "…",
|
||||
false => out,
|
||||
}
|
||||
}
|
||||
|
||||
/// `[text](url)` → `text`.
|
||||
///
|
||||
/// A result already carries its own URL on the line above, so a snippet's inline links are pure
|
||||
/// weight — and Firecrawl's descriptions are the page's markdown, where a docs.rs paragraph can
|
||||
/// spend more characters on link targets than on prose.
|
||||
pub(super) fn unlink(raw: &str) -> String {
|
||||
let mut out = String::with_capacity(raw.len());
|
||||
let mut rest = raw;
|
||||
while let Some(open) = rest.find('[') {
|
||||
let (before, from_open) = rest.split_at(open);
|
||||
// `[text](url)`, with no nesting and no line break inside — anything else is not a link.
|
||||
let link = from_open
|
||||
.find("](")
|
||||
.filter(|close| !from_open[1..*close].contains(['[', '\n']))
|
||||
.and_then(|close| {
|
||||
let after_text = &from_open[close + 2..];
|
||||
let end = after_text.find(')')?;
|
||||
let target = &after_text[..end];
|
||||
// The target has to look like one, or `[0](1)` is an array index read as a link.
|
||||
let addressed = target.starts_with("http")
|
||||
|| target.starts_with(['/', '#', '.'])
|
||||
|| target.starts_with("mailto:");
|
||||
(addressed && !target.contains(' '))
|
||||
.then_some((&from_open[1..close], close + 2 + end + 1))
|
||||
});
|
||||
out.push_str(before);
|
||||
match link {
|
||||
Some((text, consumed)) => {
|
||||
out.push_str(text);
|
||||
rest = &from_open[consumed..];
|
||||
}
|
||||
None => {
|
||||
out.push('[');
|
||||
rest = &from_open[1..];
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// The handful of HTML entities that actually show up in a search snippet.
|
||||
pub(super) fn decode_entities(text: &str) -> String {
|
||||
// `&` last, so `&lt;` decodes to `<` rather than to `<`.
|
||||
[
|
||||
(""", "\""),
|
||||
("'", "'"),
|
||||
("'", "'"),
|
||||
("<", "<"),
|
||||
(">", ">"),
|
||||
(" ", " "),
|
||||
("&", "&"),
|
||||
]
|
||||
.iter()
|
||||
.fold(text.to_string(), |text, (entity, glyph)| text.replace(entity, glyph))
|
||||
}
|
||||
338
crates/luxe-tools/src/web/search.rs
Normal file
338
crates/luxe-tools/src/web/search.rs
Normal file
@@ -0,0 +1,338 @@
|
||||
//! Search — the backends a `web_search` can run on, and the tool itself.
|
||||
|
||||
use super::render::{iso_date, render_hits};
|
||||
use super::*;
|
||||
|
||||
/// A search backend (Brave, Tavily, Exa, Firecrawl, etc.).
|
||||
///
|
||||
/// Every backend is handed the whole [`SearchOptions`] set, because the tool schema advertises
|
||||
/// those filters to the model on every request: a backend that quietly drops them answers a
|
||||
/// different question from the one that was asked, and returns plausible results while doing it.
|
||||
/// Where a vendor spells a filter differently — Brave has no domain parameter and takes `site:`
|
||||
/// operators instead — the backend translates. Where it genuinely cannot, [`Self::honors`] says so
|
||||
/// and the caller tells the model rather than letting it believe the filter applied.
|
||||
#[async_trait]
|
||||
pub trait SearchBackend: Send + Sync {
|
||||
/// Run one search, shaped by everything the caller asked for.
|
||||
async fn search(
|
||||
&self,
|
||||
query: &str,
|
||||
n: usize,
|
||||
options: &SearchOptions,
|
||||
) -> Result<Vec<SearchHit>, WebError>;
|
||||
|
||||
/// What this backend does with the requested options, for the caller to report.
|
||||
fn honors(&self, _options: &SearchOptions) -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Whether one call covers every phrasing in [`SearchOptions::also`]. A plain search API does
|
||||
/// not, so the caller runs them itself and merges.
|
||||
fn batches_queries(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// How recent a result has to be — the four windows `web_search` offers, in each vendor's terms.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Recency {
|
||||
Day,
|
||||
Week,
|
||||
Month,
|
||||
Year,
|
||||
}
|
||||
|
||||
impl Recency {
|
||||
/// Parse the tool schema's spelling.
|
||||
pub fn parse(window: &str) -> Option<Self> {
|
||||
match window {
|
||||
"day" => Some(Self::Day),
|
||||
"week" => Some(Self::Week),
|
||||
"month" => Some(Self::Month),
|
||||
"year" => Some(Self::Year),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The window as a count of days.
|
||||
pub fn days(self) -> i64 {
|
||||
match self {
|
||||
Self::Day => 1,
|
||||
Self::Week => 7,
|
||||
Self::Month => 31,
|
||||
Self::Year => 365,
|
||||
}
|
||||
}
|
||||
|
||||
/// The earliest publication date still inside the window, as `YYYY-MM-DD`.
|
||||
pub fn since(self) -> String {
|
||||
let secs = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|elapsed| elapsed.as_secs())
|
||||
.unwrap_or_default()
|
||||
.saturating_sub((self.days() * 86_400) as u64);
|
||||
iso_date(secs)
|
||||
}
|
||||
|
||||
/// Brave's `freshness` code.
|
||||
pub fn brave_code(self) -> &'static str {
|
||||
match self {
|
||||
Self::Day => "pd",
|
||||
Self::Week => "pw",
|
||||
Self::Month => "pm",
|
||||
Self::Year => "py",
|
||||
}
|
||||
}
|
||||
|
||||
/// Tavily's `time_range`.
|
||||
pub fn tavily_range(self) -> &'static str {
|
||||
match self {
|
||||
Self::Day => "day",
|
||||
Self::Week => "week",
|
||||
Self::Month => "month",
|
||||
Self::Year => "year",
|
||||
}
|
||||
}
|
||||
|
||||
/// The Google `tbs` window Firecrawl passes upstream.
|
||||
pub fn tbs(self) -> &'static str {
|
||||
match self {
|
||||
Self::Day => "qdr:d",
|
||||
Self::Week => "qdr:w",
|
||||
Self::Month => "qdr:m",
|
||||
Self::Year => "qdr:y",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a caller can ask of a search, beyond the query itself.
|
||||
///
|
||||
/// Deliberately a small, provider-neutral set: the options that change *which* results come back
|
||||
/// and whether their content rides along. Exa's own schema has thirty knobs; a tool schema that
|
||||
/// exposed all of them would cost more context than the answers it fetches.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct SearchOptions {
|
||||
/// Extra query phrasings run alongside the main one, widening coverage in a single call.
|
||||
pub also: Vec<String>,
|
||||
/// Only these domains.
|
||||
pub include_domains: Vec<String>,
|
||||
/// Never these domains.
|
||||
pub exclude_domains: Vec<String>,
|
||||
/// Published no earlier than this window.
|
||||
pub recency: Option<Recency>,
|
||||
/// Carry extracted passages with each result instead of a bare snippet.
|
||||
pub include_content: bool,
|
||||
}
|
||||
|
||||
impl SearchOptions {
|
||||
/// `site:`/`-site:` operators for a backend whose API has no domain filter of its own.
|
||||
///
|
||||
/// Every general web index understands them, which is why a missing parameter is not a missing
|
||||
/// capability.
|
||||
pub fn site_operators(&self) -> String {
|
||||
let include = self.include_domains.iter().map(|domain| format!("site:{domain}"));
|
||||
let exclude = self.exclude_domains.iter().map(|domain| format!("-site:{domain}"));
|
||||
include.chain(exclude).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// `query` with those operators appended, which is how such a backend is asked.
|
||||
pub fn applied_to(&self, query: &str) -> String {
|
||||
let operators = self.site_operators();
|
||||
match operators.is_empty() {
|
||||
true => query.to_string(),
|
||||
false => format!("{query} {operators}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalized search result.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SearchHit {
|
||||
pub title: String,
|
||||
pub url: String,
|
||||
pub snippet: String,
|
||||
}
|
||||
|
||||
/// Create a search backend based on configuration.
|
||||
///
|
||||
/// No key means Exa's keyless MCP endpoint rather than an error — see [`WebConfig::from_env`].
|
||||
pub async fn create_backend(config: &WebConfig) -> Result<Box<dyn SearchBackend>, WebError> {
|
||||
let Some(api_key) = config.search_api_key.as_deref() else {
|
||||
return Ok(Box::new(crate::exa_mcp::ExaMcpBackend::new()));
|
||||
};
|
||||
match config.search_backend.as_deref().unwrap_or("exa_mcp") {
|
||||
"brave" => Ok(Box::new(crate::brave::BraveBackend::new(api_key.to_string()))),
|
||||
"tavily" => Ok(Box::new(crate::tavily::TavilyBackend::new(api_key.to_string()))),
|
||||
"exa" => Ok(Box::new(crate::exa::ExaBackend::new(api_key.to_string()))),
|
||||
"firecrawl" => Ok(Box::new(crate::firecrawl::FirecrawlBackend::new(api_key.to_string()))),
|
||||
"exa_mcp" => Ok(Box::new(crate::exa_mcp::ExaMcpBackend::new())),
|
||||
other => Err(WebError::Backend(format!("Unknown search backend: {other}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Run every phrasing the caller asked for and merge the results.
|
||||
///
|
||||
/// One call per query for a backend that takes one query, first-seen order preserved and duplicate
|
||||
/// URLs dropped — the same page found by two phrasings is one result, and the earlier phrasing is
|
||||
/// the one that ranked it. A phrasing that errors is skipped rather than sinking the whole search;
|
||||
/// the error only surfaces when *nothing* answered.
|
||||
pub(super) async fn run_search(
|
||||
backend: &dyn SearchBackend,
|
||||
queries: &[String],
|
||||
n: usize,
|
||||
options: &SearchOptions,
|
||||
) -> Result<Vec<SearchHit>, WebError> {
|
||||
let Some((query, also)) = queries.split_first() else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
if backend.batches_queries() || also.is_empty() {
|
||||
return backend.search(query, n, options).await;
|
||||
}
|
||||
|
||||
// The extras are already in `queries`; passing them again would double a backend that reads
|
||||
// both. One phrasing at a time, and the option set minus the fan-out it has already served.
|
||||
let single = SearchOptions { also: Vec::new(), ..options.clone() };
|
||||
let mut merged: Vec<SearchHit> = Vec::new();
|
||||
let mut last_error = None;
|
||||
for query in queries {
|
||||
match backend.search(query, n, &single).await {
|
||||
Ok(hits) => {
|
||||
for hit in hits {
|
||||
if !merged.iter().any(|seen| seen.url == hit.url) {
|
||||
merged.push(hit);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => last_error = Some(error),
|
||||
}
|
||||
}
|
||||
match (merged.is_empty(), last_error) {
|
||||
(true, Some(error)) => Err(error),
|
||||
_ => Ok(merged),
|
||||
}
|
||||
}
|
||||
|
||||
/// web_search tool — pluggable search backend.
|
||||
pub struct WebSearchTool {
|
||||
pub(super) config: Arc<RwLock<WebConfig>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for WebSearchTool {
|
||||
fn name(&self) -> &str {
|
||||
"web_search"
|
||||
}
|
||||
|
||||
/// A search backend that has stopped answering is not worth a two-minute wait.
|
||||
fn timeout(&self) -> Option<std::time::Duration> {
|
||||
Some(luxe_core::tool::NETWORK_TOOL_TIMEOUT)
|
||||
}
|
||||
|
||||
fn schema(&self) -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: "web_search".to_string(),
|
||||
description: "Search the web. Each result carries the passage the search engine \
|
||||
matched, which often answers the question outright — `web_fetch` a URL \
|
||||
only when you need more of the page than came back. Pass several \
|
||||
`queries` to cover a topic from different angles in one call (varied \
|
||||
phrasing beats repeating one query). Narrow with `domains` (prefix `-` \
|
||||
to exclude) and `recency` when currency matters; a reply that leads with \
|
||||
`Note:` is saying which of those the configured search vendor could not \
|
||||
apply."
|
||||
.to_string(),
|
||||
parameters: serde_json::json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {"type": "string", "description": "Search query"},
|
||||
"queries": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Two to four varied phrasings of the same question, searched together. Prefer this over one query for research."
|
||||
},
|
||||
"n": {"type": "integer", "description": "Results to return (default 5, max 20)"},
|
||||
"domains": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Limit to these domains, e.g. ['docs.rs']; prefix with '-' to exclude, e.g. '-pinterest.com'."
|
||||
},
|
||||
"recency": {
|
||||
"type": "string",
|
||||
"enum": ["day", "week", "month", "year"],
|
||||
"description": "Only pages published within this window."
|
||||
},
|
||||
"content": {
|
||||
"type": "boolean",
|
||||
"description": "Include the relevant passage from each result (default true). Set false for a bare link list."
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(&self, args: serde_json::Value, _cx: &ToolContext) -> ToolResultData {
|
||||
let queries = search_queries(&args);
|
||||
let Some((_, also)) = queries.split_first() else {
|
||||
return ToolResultData::error("Error: 'query' (or 'queries') is required");
|
||||
};
|
||||
|
||||
let n = (args.get("n").and_then(serde_json::Value::as_u64).unwrap_or(5) as usize)
|
||||
.clamp(1, MAX_RESULTS);
|
||||
let options = SearchOptions {
|
||||
also: also.to_vec(),
|
||||
include_content: args
|
||||
.get("content")
|
||||
.and_then(serde_json::Value::as_bool)
|
||||
.unwrap_or(true),
|
||||
recency: args
|
||||
.get("recency")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.and_then(Recency::parse),
|
||||
..domain_filters(&args)
|
||||
};
|
||||
|
||||
let config = self.config.read().await;
|
||||
let backend = match create_backend(&config).await {
|
||||
Ok(backend) => backend,
|
||||
Err(e) => return ToolResultData::error(format!("Backend error: {e}")),
|
||||
};
|
||||
match run_search(backend.as_ref(), &queries, n, &options).await {
|
||||
Ok(hits) => {
|
||||
ToolResultData::text(render_hits(&queries, &hits, &backend.honors(&options)))
|
||||
}
|
||||
Err(e) => ToolResultData::error(format!("Search failed: {e}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Most results any backend will return for one query. Brave refuses more than 20 outright, so the
|
||||
/// ceiling is the lowest that every vendor accepts rather than the highest one of them allows.
|
||||
pub(super) const MAX_RESULTS: usize = 20;
|
||||
|
||||
/// The queries to run: `queries` when given, else the single `query`, trimmed and de-duplicated.
|
||||
///
|
||||
/// Owned by `luxe_core` because the tool card lists the same set under the call's header, and a
|
||||
/// second implementation would let the card and the search disagree about what ran.
|
||||
pub(super) fn search_queries(args: &serde_json::Value) -> Vec<String> {
|
||||
luxe_core::web_search_queries(args)
|
||||
}
|
||||
|
||||
/// Split `domains` into include/exclude sets; a leading `-` excludes.
|
||||
pub(super) fn domain_filters(args: &serde_json::Value) -> SearchOptions {
|
||||
let mut options = SearchOptions::default();
|
||||
let Some(list) = args.get("domains").and_then(serde_json::Value::as_array) else {
|
||||
return options;
|
||||
};
|
||||
for entry in list.iter().filter_map(serde_json::Value::as_str) {
|
||||
let entry = entry.trim();
|
||||
// A bare `-` names no domain either way.
|
||||
if entry.is_empty() || entry == "-" {
|
||||
continue;
|
||||
}
|
||||
match entry.strip_prefix('-') {
|
||||
Some(excluded) => options.exclude_domains.push(excluded.to_string()),
|
||||
None => options.include_domains.push(entry.to_string()),
|
||||
}
|
||||
}
|
||||
options
|
||||
}
|
||||
433
crates/luxe-tools/src/web/tests.rs
Normal file
433
crates/luxe-tools/src/web/tests.rs
Normal file
@@ -0,0 +1,433 @@
|
||||
use super::fetch::{extract_readable, github_blob_raw, github_repo, page_of, FETCH_MAX_CHARS};
|
||||
use super::render::{iso_date, plain_text, render_hits, SNIPPET_CHARS};
|
||||
use super::search::{domain_filters, search_queries};
|
||||
use super::*;
|
||||
use luxe_core::ToolContext;
|
||||
use std::sync::Arc;
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
struct MockSearchBackend {
|
||||
hits: Vec<SearchHit>,
|
||||
}
|
||||
|
||||
impl MockSearchBackend {
|
||||
fn new(hits: Vec<SearchHit>) -> Self {
|
||||
Self { hits }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl SearchBackend for MockSearchBackend {
|
||||
async fn search(
|
||||
&self,
|
||||
_query: &str,
|
||||
n: usize,
|
||||
_options: &SearchOptions,
|
||||
) -> Result<Vec<SearchHit>, WebError> {
|
||||
let n = n.min(self.hits.len());
|
||||
Ok(self.hits[..n].to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
fn test_context(tmp_dir: &std::path::Path) -> ToolContext {
|
||||
let (event_tx, _event_rx) = mpsc::channel(64);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
ToolContext {
|
||||
cwd: tmp_dir.to_path_buf(),
|
||||
session_id: "test-session".to_string(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A silent host is the one failure a browser user-agent cannot fix, so `web_fetch` must not
|
||||
/// spend its budget twice on it. Two 30s attempts against a dead domain is the minute that looked
|
||||
/// like a hung agent.
|
||||
#[test]
|
||||
fn only_a_failure_a_browser_could_fix_earns_the_stealth_retry() {
|
||||
assert!(!WebError::Timeout("no answer".into()).worth_a_second_try());
|
||||
for error in [
|
||||
WebError::Http("HTTP 403 Forbidden".into()),
|
||||
WebError::Network("connection reset".into()),
|
||||
WebError::Parse("not html".into()),
|
||||
] {
|
||||
assert!(error.worth_a_second_try(), "{error} may well succeed as a browser");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_web_search_missing_query() {
|
||||
let tools = WebTools::new(WebConfig::default());
|
||||
let tool = tools.web_search();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({}), &ctx).await;
|
||||
assert!(result.is_error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_readable_pulls_main_content_as_markdown() {
|
||||
let html = r#"<html><head><title>Ignored</title></head><body>
|
||||
<nav>Home About Login Newsletter signup</nav>
|
||||
<article>
|
||||
<h1>Widget Guide</h1>
|
||||
<p>Install the widget with <code>cargo add widget</code> first.</p>
|
||||
<p>Then call <a href="https://example.com/api">the API</a> to render it.</p>
|
||||
</article>
|
||||
<footer>Copyright 2026</footer></body></html>"#;
|
||||
let md = extract_readable(html, "https://example.com/guide");
|
||||
assert!(md.contains("Widget Guide"), "heading kept: {md}");
|
||||
assert!(md.contains("cargo add widget"), "body kept: {md}");
|
||||
assert!(!md.contains("<article>") && !md.contains("<p>"), "tags stripped: {md}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_repo_matches_only_repo_roots() {
|
||||
let root = Url::parse("https://github.com/rust-lang/cargo").unwrap();
|
||||
assert_eq!(github_repo(&root), Some(("rust-lang".into(), "cargo".into())));
|
||||
let dotgit = Url::parse("https://github.com/rust-lang/cargo.git").unwrap();
|
||||
assert_eq!(github_repo(&dotgit), Some(("rust-lang".into(), "cargo".into())));
|
||||
assert!(github_repo(&Url::parse("https://github.com/rust-lang").unwrap()).is_none());
|
||||
assert!(github_repo(&Url::parse("https://github.com/o/r/blob/main/x").unwrap()).is_none());
|
||||
assert!(github_repo(&Url::parse("https://example.com/o/r").unwrap()).is_none());
|
||||
}
|
||||
|
||||
/// With cloning off the schema stops promising it, so the model reads a repository as a page
|
||||
/// rather than waiting on a path that never comes.
|
||||
#[test]
|
||||
fn the_description_mentions_cloning_only_when_it_is_on() {
|
||||
let on = WebTools::new(WebConfig::default()).web_fetch().schema().description;
|
||||
assert!(on.contains(".luxe/gh-cache/"), "{on}");
|
||||
let off = WebConfig { clone_repositories: false, ..WebConfig::default() };
|
||||
let off = WebTools::new(off).web_fetch().schema().description;
|
||||
assert!(!off.contains("clone"), "{off}");
|
||||
assert!(off.contains("GitHub blob URL"), "{off}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_blob_maps_to_raw() {
|
||||
assert_eq!(
|
||||
github_blob_raw("https://github.com/o/r/blob/main/src/lib.rs").as_deref(),
|
||||
Some("https://raw.githubusercontent.com/o/r/main/src/lib.rs")
|
||||
);
|
||||
assert!(github_blob_raw("https://github.com/o/r").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_web_fetch_missing_url() {
|
||||
let tools = WebTools::new(WebConfig::default());
|
||||
let tool = tools.web_fetch();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({}), &ctx).await;
|
||||
assert!(result.is_error);
|
||||
}
|
||||
|
||||
/// Search with no key is a working capability, not an error. Nothing here touches the network:
|
||||
/// the contract under test is which backend gets chosen.
|
||||
#[tokio::test]
|
||||
async fn no_api_key_falls_back_to_the_keyless_backend() {
|
||||
let config = WebConfig::default();
|
||||
assert!(!config.has_search_key());
|
||||
assert!(create_backend(&config).await.is_ok(), "an unconfigured user still gets search");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_configured_key_still_wins() {
|
||||
let config = WebConfig {
|
||||
search_backend: Some("brave".to_string()),
|
||||
search_api_key: Some("k".to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(create_backend(&config).await.is_ok());
|
||||
let unknown = WebConfig { search_backend: Some("nope".to_string()), ..config };
|
||||
assert!(create_backend(&unknown).await.is_err(), "a typo'd backend name is still an error");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_search_with_no_query_at_all_is_rejected() {
|
||||
let tools = WebTools::new(WebConfig::default());
|
||||
let tool = tools.web_search();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({}), &ctx).await;
|
||||
assert!(result.is_error);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queries_collapse_to_a_deduplicated_list() {
|
||||
let args = serde_json::json!({"queries": ["a", " a ", "b", ""], "query": "b"});
|
||||
assert_eq!(search_queries(&args), vec!["a".to_string(), "b".to_string()]);
|
||||
assert_eq!(search_queries(&serde_json::json!({"query": "solo"})), vec!["solo"]);
|
||||
assert!(search_queries(&serde_json::json!({})).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leading_dash_excludes_a_domain() {
|
||||
let filters =
|
||||
domain_filters(&serde_json::json!({"domains": ["docs.rs", "-pinterest.com", "-"]}));
|
||||
assert_eq!(filters.include_domains, vec!["docs.rs".to_string()]);
|
||||
assert_eq!(filters.exclude_domains, vec!["pinterest.com".to_string()]);
|
||||
}
|
||||
|
||||
/// One window, four vendor spellings. They are not interchangeable: Brave takes a code, Tavily
|
||||
/// a word, Firecrawl a Google `tbs` operator, and Exa an absolute date.
|
||||
#[test]
|
||||
fn a_recency_window_speaks_every_vendors_dialect() {
|
||||
let today = iso_date(
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.expect("clock")
|
||||
.as_secs(),
|
||||
);
|
||||
let week = Recency::parse("week").expect("a window the schema offers");
|
||||
assert_eq!(week.brave_code(), "pw");
|
||||
assert_eq!(week.tavily_range(), "week");
|
||||
assert_eq!(week.tbs(), "qdr:w");
|
||||
let since = week.since();
|
||||
assert_eq!(since.len(), 10, "YYYY-MM-DD: {since}");
|
||||
assert!(since < today, "{since} must precede {today}");
|
||||
assert!(Recency::parse("decade").is_none());
|
||||
assert!(Recency::Day.since() > Recency::Year.since(), "a shorter window starts later");
|
||||
// A known instant, so the civil-date arithmetic itself is pinned.
|
||||
assert_eq!(iso_date(1_767_225_600), "2026-01-01");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn results_render_as_compact_markdown_not_json() {
|
||||
let hits = vec![
|
||||
SearchHit {
|
||||
title: "Tokio select".into(),
|
||||
url: "https://docs.rs/tokio".into(),
|
||||
snippet: "Cancellation safety describes what happens…".into(),
|
||||
},
|
||||
SearchHit {
|
||||
title: "Bare".into(),
|
||||
url: "https://example.test".into(),
|
||||
snippet: String::new(),
|
||||
},
|
||||
];
|
||||
let rendered = render_hits(&["a".into(), "b".into()], &hits, &[]);
|
||||
|
||||
assert!(rendered.starts_with("Searched: a · b"), "{rendered}");
|
||||
assert!(rendered.contains("1. Tokio select"));
|
||||
assert!(rendered.contains("https://docs.rs/tokio"));
|
||||
assert!(rendered.contains("Cancellation safety"), "the passage rides along");
|
||||
assert!(!rendered.contains('{'), "no JSON punctuation tax: {rendered}");
|
||||
assert_eq!(render_hits(&["q".into()], &[], &[]), "No results for q.");
|
||||
}
|
||||
|
||||
/// Brave marks the matched words with `<strong>` and Firecrawl hands back the page's own
|
||||
/// markdown, newlines and fences included. Neither is information, and both are paid for by
|
||||
/// the token.
|
||||
#[test]
|
||||
fn a_snippet_is_reduced_to_one_line_of_readable_text() {
|
||||
let brave = "Cancellation safety <strong>describes what happens</strong> & why";
|
||||
assert_eq!(
|
||||
plain_text(brave, SNIPPET_CHARS),
|
||||
"Cancellation safety describes what happens & why"
|
||||
);
|
||||
|
||||
let firecrawl = "# Struct CancellationToken\n\n## Examples\n```\nuse tokio::select;\n```";
|
||||
assert_eq!(
|
||||
plain_text(firecrawl, SNIPPET_CHARS),
|
||||
"# Struct CancellationToken ## Examples ``` use tokio::select; ```"
|
||||
);
|
||||
|
||||
let long = "x".repeat(SNIPPET_CHARS + 500);
|
||||
let capped = plain_text(&long, SNIPPET_CHARS);
|
||||
assert_eq!(capped.chars().count(), SNIPPET_CHARS + 1, "capped, plus the ellipsis");
|
||||
assert!(capped.ends_with('…'));
|
||||
|
||||
// A double-escaped entity decodes once, not twice.
|
||||
assert_eq!(plain_text("a &lt; b", SNIPPET_CHARS), "a < b");
|
||||
assert!(plain_text(" \n \t ", SNIPPET_CHARS).is_empty());
|
||||
}
|
||||
|
||||
/// A docs.rs paragraph rendered to markdown spends more characters on link targets than on
|
||||
/// prose, and the result's own URL is already on the line above.
|
||||
#[test]
|
||||
fn inline_link_targets_are_dropped_and_their_text_kept() {
|
||||
assert_eq!(
|
||||
plain_text("see [Receiver::recv](https://docs.rs/x#method.recv) for details", 500),
|
||||
"see Receiver::recv for details"
|
||||
);
|
||||
assert_eq!(plain_text("jump to [§](#examples) now", 500), "jump to § now");
|
||||
// Not links, and each has to survive being mistaken for one.
|
||||
for kept in [
|
||||
"an array [0](1) index",
|
||||
"a [bracket] alone",
|
||||
"nested [a [b](c)] text",
|
||||
"[unclosed",
|
||||
"[text](not a url)",
|
||||
] {
|
||||
assert_eq!(plain_text(kept, 500), kept, "mangled a non-link");
|
||||
}
|
||||
}
|
||||
|
||||
/// A note about what the backend could not do has to arrive before the results it qualifies,
|
||||
/// and has to arrive even when there are none.
|
||||
#[test]
|
||||
fn a_backends_caveat_leads_the_reply() {
|
||||
let caveats = vec!["Brave returns a short search snippet".to_string()];
|
||||
let rendered = render_hits(&["q".into()], &[], &caveats);
|
||||
assert!(rendered.starts_with("Note: Brave returns"), "{rendered}");
|
||||
assert!(rendered.contains("No results for q."), "{rendered}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_web_search_with_api_key() {
|
||||
// Test with mock backend since we don't want to make real API calls
|
||||
let config = WebConfig {
|
||||
search_backend: Some("mock".to_string()),
|
||||
search_api_key: Some("test-key".to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
let tools = WebTools::new(config);
|
||||
let tool = tools.web_search();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({"query": "test", "n": 3}), &ctx).await;
|
||||
// Should fail because mock backend is not implemented in create_backend
|
||||
assert!(result.is_error);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_web_fetch_with_url() {
|
||||
let tools = WebTools::new(WebConfig::default());
|
||||
let tool = tools.web_fetch();
|
||||
let tmp_dir = TempDir::new().unwrap();
|
||||
let ctx = test_context(tmp_dir.path());
|
||||
|
||||
let result = tool.run(serde_json::json!({"url": "https://example.com"}), &ctx).await;
|
||||
assert!(!result.is_error);
|
||||
assert!(!result.content.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_mock_search_backend() {
|
||||
let hits = vec![
|
||||
SearchHit {
|
||||
title: "Test Result 1".to_string(),
|
||||
url: "https://example.com/1".to_string(),
|
||||
snippet: "Snippet 1".to_string(),
|
||||
},
|
||||
SearchHit {
|
||||
title: "Test Result 2".to_string(),
|
||||
url: "https://example.com/2".to_string(),
|
||||
snippet: "Snippet 2".to_string(),
|
||||
},
|
||||
];
|
||||
|
||||
let backend = MockSearchBackend::new(hits);
|
||||
let results = backend.search("test", 2, &SearchOptions::default()).await.unwrap();
|
||||
assert_eq!(results.len(), 2);
|
||||
assert_eq!(results[0].title, "Test Result 1");
|
||||
assert_eq!(results[1].title, "Test Result 2");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_mock_search_backend_limit() {
|
||||
let hits = vec![
|
||||
SearchHit {
|
||||
title: "Result 1".to_string(),
|
||||
url: "https://example.com/1".to_string(),
|
||||
snippet: "Snippet 1".to_string(),
|
||||
},
|
||||
SearchHit {
|
||||
title: "Result 2".to_string(),
|
||||
url: "https://example.com/2".to_string(),
|
||||
snippet: "Snippet 2".to_string(),
|
||||
},
|
||||
SearchHit {
|
||||
title: "Result 3".to_string(),
|
||||
url: "https://example.com/3".to_string(),
|
||||
snippet: "Snippet 3".to_string(),
|
||||
},
|
||||
];
|
||||
|
||||
let backend = MockSearchBackend::new(hits);
|
||||
let results = backend.search("test", 2, &SearchOptions::default()).await.unwrap();
|
||||
assert_eq!(results.len(), 2);
|
||||
}
|
||||
|
||||
/// A bound that cannot be walked past is a trap: pages with no anchors and no sub-pages would
|
||||
/// leave the remainder permanently unreachable. Every window must name the next offset.
|
||||
#[test]
|
||||
fn a_long_page_is_walkable_end_to_end() {
|
||||
let page: String = "abcdefghij".repeat(FETCH_MAX_CHARS / 10 * 3 + 137);
|
||||
let total = page.chars().count();
|
||||
|
||||
let mut offset = 0usize;
|
||||
let mut seen = 0usize;
|
||||
let mut windows = 0;
|
||||
loop {
|
||||
let out = page_of(&page, offset);
|
||||
windows += 1;
|
||||
assert!(windows < 20, "should terminate");
|
||||
let next = out
|
||||
.rsplit("offset: ")
|
||||
.next()
|
||||
.and_then(|s| s.trim().parse::<usize>().ok())
|
||||
.filter(|n| *n > offset);
|
||||
match next {
|
||||
Some(n) => {
|
||||
seen += n - offset;
|
||||
offset = n;
|
||||
}
|
||||
None => {
|
||||
assert!(out.contains("end of page"), "the last window says so: {}", &out[..80]);
|
||||
seen += total - offset;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(seen, total, "every character is reachable across {windows} windows");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_page_is_returned_untouched() {
|
||||
assert_eq!(page_of("just a little page", 0), "just a little page");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_window_of_a_long_page_reports_the_next_offset() {
|
||||
let page = "z".repeat(FETCH_MAX_CHARS * 2);
|
||||
let out = page_of(&page, 0);
|
||||
assert!(
|
||||
out.starts_with(&format!("[characters 0\u{2013}{FETCH_MAX_CHARS} of ")),
|
||||
"{}",
|
||||
&out[..60]
|
||||
);
|
||||
assert!(out.contains(&format!("offset: {FETCH_MAX_CHARS}")), "names the exact next offset");
|
||||
assert!(out.contains("characters remain"));
|
||||
}
|
||||
|
||||
/// Even the mistake is recoverable rather than a dead end.
|
||||
#[test]
|
||||
fn an_offset_past_the_end_says_how_to_recover() {
|
||||
let out = page_of("short", 9_000);
|
||||
assert!(out.contains("past the end"), "{out}");
|
||||
assert!(out.contains("offset 0"), "and how to start over: {out}");
|
||||
}
|
||||
|
||||
/// A page cut at the size cap says so after extraction, where readability cannot drop the note.
|
||||
#[test]
|
||||
fn a_cut_page_says_so_after_extraction() {
|
||||
let html =
|
||||
"<html><body><article><h1>Title</h1><p>Some long article text.</p></article></body></html>";
|
||||
let read = |truncated| {
|
||||
let fetched = crate::ssrf::Fetched { body: html.into(), truncated };
|
||||
fetched.reduced(|html| extract_readable(html, "https://x.test/"))
|
||||
};
|
||||
let cut = read(true);
|
||||
assert!(cut.trim_end().ends_with("and the rest was not read]"), "{cut}");
|
||||
assert!(!read(false).contains("truncated"));
|
||||
}
|
||||
203
crates/luxe-tools/src/write.rs
Normal file
203
crates/luxe-tools/src/write.rs
Normal file
@@ -0,0 +1,203 @@
|
||||
//! `write` tool — write content to a file, creating parents as needed.
|
||||
//!
|
||||
//! Supports:
|
||||
//! - Writing entire files (overwrite or create)
|
||||
//! - Creating parent directories automatically
|
||||
//! - Atomic writes (write to temp, then rename)
|
||||
|
||||
use async_trait::async_trait;
|
||||
use luxe_core::read_tracker::{ReadStatus, ReadTracker};
|
||||
use luxe_core::tool::guards::{CHANGED_ON_DISK, READ_BEFORE_WRITE};
|
||||
use luxe_core::{ContentBlock, Tool, ToolContext, ToolResultData, ToolSchema};
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use tracing::{debug, warn};
|
||||
|
||||
/// JSON-schema for the write tool arguments.
|
||||
fn write_schema() -> ToolSchema {
|
||||
ToolSchema {
|
||||
name: "write".to_string(),
|
||||
description: "Write a whole file, creating parent directories as needed. Best for NEW \
|
||||
files; for targeted changes to an existing file use `edit`. Overwriting an \
|
||||
existing file requires having `read` it in this Luxe run (and it not \
|
||||
having changed since) so you don't clobber content you never saw."
|
||||
.to_string(),
|
||||
parameters: json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Path to the file to write (relative to cwd)"
|
||||
},
|
||||
"content": {
|
||||
"type": "string",
|
||||
"description": "Content to write to the file"
|
||||
}
|
||||
},
|
||||
"required": ["path", "content"]
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `write` tool implementation.
|
||||
#[derive(Default)]
|
||||
pub struct WriteTool {
|
||||
/// Shared read tracker enforcing read-before-overwrite for existing files (skipped when absent).
|
||||
tracker: Option<Arc<ReadTracker>>,
|
||||
}
|
||||
|
||||
impl WriteTool {
|
||||
/// Create a new write tool instance.
|
||||
pub fn new() -> Self {
|
||||
Self { tracker: None }
|
||||
}
|
||||
|
||||
/// Attach the shared read tracker so overwriting an existing file requires a prior read.
|
||||
pub fn with_tracker(mut self, tracker: Arc<ReadTracker>) -> Self {
|
||||
self.tracker = Some(tracker);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl WriteTool {
|
||||
/// The blind-overwrite guard, when a tracker is wired.
|
||||
///
|
||||
/// Creating a NEW file is always fine, but overwriting an EXISTING file wholesale requires
|
||||
/// having read it first (and it not having changed since) so the model doesn't clobber content
|
||||
/// it never saw. `edit` is the right tool for targeted changes; this catches accidental
|
||||
/// full-file overwrites.
|
||||
fn check_blind_overwrite(
|
||||
&self,
|
||||
cx: &ToolContext,
|
||||
full_path: &Path,
|
||||
shown: &str,
|
||||
) -> Result<(), ToolResultData> {
|
||||
let Some(tracker) = &self.tracker else { return Ok(()) };
|
||||
if !full_path.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
match tracker.status(&cx.session_id, full_path) {
|
||||
ReadStatus::Unseen => Err(ToolResultData::error(format!(
|
||||
"Error: '{shown}' exists and has no read on record for this Luxe run \
|
||||
({READ_BEFORE_WRITE}), so overwriting it would be blind. \
|
||||
The record is per process, so a resumed session starts empty \
|
||||
even where the transcript shows an earlier read. Read it (or \
|
||||
use `edit` for a targeted change), then retry — nothing was \
|
||||
written."
|
||||
))),
|
||||
ReadStatus::Stale => Err(ToolResultData::error(format!(
|
||||
"Error: '{shown}' {CHANGED_ON_DISK} you last read it (a formatter, \
|
||||
another tool, or an external edit). Re-read it, then retry the \
|
||||
write — nothing was written."
|
||||
))),
|
||||
ReadStatus::Current => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// What happens once the bytes are down: format-on-save and diagnostics, the fingerprint, and
|
||||
/// the reply.
|
||||
async fn after_write(
|
||||
&self,
|
||||
cx: &ToolContext,
|
||||
full_path: &Path,
|
||||
content: &str,
|
||||
existed: bool,
|
||||
) -> ToolResultData {
|
||||
// format-on-save and diagnostics run here, before the fingerprint below
|
||||
let injected = cx.file_changed(full_path, "write").await;
|
||||
|
||||
// Format-on-save may have rewritten it; show what is there now
|
||||
let formatted = std::fs::read_to_string(full_path).ok().filter(|now| *now != *content);
|
||||
|
||||
// Record the freshly-written file so a subsequent edit/write isn't blocked.
|
||||
if let Some(tracker) = &self.tracker {
|
||||
tracker.record(&cx.session_id, full_path);
|
||||
}
|
||||
|
||||
// Show the written content as an all-additions block (the TUI colorizes it) so a
|
||||
// write reads like the edit diff rather than an opaque byte count.
|
||||
let verb = if existed { "Overwrote" } else { "Created" };
|
||||
let preview = crate::diff_preview::added_lines(formatted.as_deref().unwrap_or(content));
|
||||
let note = if formatted.is_some() {
|
||||
"\n Format-on-save then reformatted the file; the lines below are as it is now."
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let mut result = vec![ContentBlock::Text(format!(
|
||||
"{verb} '{}' ({} bytes){note}\n\n{preview}",
|
||||
luxe_core::paths::display(full_path.strip_prefix(&cx.cwd).unwrap_or(full_path)),
|
||||
content.len()
|
||||
))];
|
||||
if let Some(context) = injected {
|
||||
result.push(ContentBlock::Text(format!("\n--- Diagnostics ---\n{context}")));
|
||||
}
|
||||
ToolResultData { content: result, is_error: false }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for WriteTool {
|
||||
fn name(&self) -> &str {
|
||||
"write"
|
||||
}
|
||||
|
||||
fn schema(&self) -> ToolSchema {
|
||||
write_schema()
|
||||
}
|
||||
|
||||
async fn run(&self, args: serde_json::Value, cx: &ToolContext) -> ToolResultData {
|
||||
let path_str = match args.get("path").and_then(|v| v.as_str()) {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
return ToolResultData::error("Error: 'path' argument is required");
|
||||
}
|
||||
};
|
||||
|
||||
let content = match args.get("content").and_then(|v| v.as_str()) {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
return ToolResultData::error("Error: 'content' argument is required");
|
||||
}
|
||||
};
|
||||
|
||||
// Resolve path relative to cwd.
|
||||
let full_path = cx.cwd.join(path_str);
|
||||
|
||||
if let Err(refusal) = self.check_blind_overwrite(cx, &full_path, path_str) {
|
||||
return refusal;
|
||||
}
|
||||
|
||||
// Captured before the write so the result can say whether this created or replaced a file.
|
||||
let existed = full_path.exists();
|
||||
debug!(path = %full_path.display(), "writing file");
|
||||
|
||||
// Keep the file's own line endings. A Windows checkout is CRLF and the model writes LF, so
|
||||
// a straight overwrite would silently convert every line in the file.
|
||||
let content = match std::fs::read_to_string(&full_path) {
|
||||
Ok(previous) => std::borrow::Cow::Owned(crate::line_endings::normalize(
|
||||
content,
|
||||
crate::line_endings::detect(&previous),
|
||||
)),
|
||||
Err(_) => std::borrow::Cow::Borrowed(content),
|
||||
};
|
||||
|
||||
match luxe_core::fs_atomic::replace(&full_path, content.as_bytes()) {
|
||||
Ok(()) => {
|
||||
debug!(path = %full_path.display(), "file written successfully");
|
||||
self.after_write(cx, &full_path, &content, existed).await
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(path = %full_path.display(), error = %e, "failed to write file");
|
||||
ToolResultData::error(format!(
|
||||
"Error writing file '{}': {}",
|
||||
luxe_core::paths::display(&full_path),
|
||||
e
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
137
crates/luxe-tools/src/write/tests.rs
Normal file
137
crates/luxe-tools/src/write/tests.rs
Normal file
@@ -0,0 +1,137 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
fn test_context(tmp_dir: &std::path::Path) -> ToolContext {
|
||||
let (event_tx, _event_rx) = mpsc::channel(64);
|
||||
let (_cancel_tx, cancel_rx) = watch::channel(false);
|
||||
ToolContext {
|
||||
cwd: tmp_dir.to_path_buf(),
|
||||
session_id: "test-session".to_string(),
|
||||
cancelled: Arc::new(cancel_rx),
|
||||
event_tx,
|
||||
hook_ctx: None,
|
||||
question_broker: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A written file that format-on-save then rewrote is shown as it now is.
|
||||
#[tokio::test]
|
||||
async fn a_reformatted_write_shows_the_file_as_it_is_now() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cx = crate::edit::tests::formatting_context(dir.path());
|
||||
let args = serde_json::json!({"path": "lib.rs", "content": "fn sub(a:i32) {}\n"});
|
||||
let result = WriteTool::new().run(args, &cx).await;
|
||||
let ContentBlock::Text(text) = &result.content[0] else { panic!("expected text") };
|
||||
assert!(text.starts_with("Created 'lib.rs'"), "named from the project: {text}");
|
||||
assert!(text.contains("Format-on-save then reformatted the file"), "{text}");
|
||||
assert!(text.contains("+1 fn sub(a: i32) {}") && !text.contains("a:i32"), "{text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn write_tool_basic() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let tmp_dir = tmp_dir_guard.path().to_path_buf();
|
||||
|
||||
let tool = WriteTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({
|
||||
"path": "test.txt",
|
||||
"content": "Hello, World!"
|
||||
});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(!result.is_error);
|
||||
if let ContentBlock::Text(text) = &result.content[0] {
|
||||
assert!(text.contains("Created"));
|
||||
assert!(text.contains("test.txt"));
|
||||
assert!(text.contains("+1 Hello, World!"), "shows the numbered additions: {text}");
|
||||
} else {
|
||||
panic!("expected Text block");
|
||||
}
|
||||
|
||||
// Verify file was written.
|
||||
let content = std::fs::read_to_string(tmp_dir.join("test.txt")).unwrap();
|
||||
assert_eq!(content, "Hello, World!");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn write_tool_creates_parent_dirs() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let tmp_dir = tmp_dir_guard.path().to_path_buf();
|
||||
|
||||
let tool = WriteTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({
|
||||
"path": "subdir1/subdir2/test.txt",
|
||||
"content": "Nested content"
|
||||
});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(!result.is_error);
|
||||
|
||||
// Verify file was written.
|
||||
let content = std::fs::read_to_string(tmp_dir.join("subdir1/subdir2/test.txt")).unwrap();
|
||||
assert_eq!(content, "Nested content");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn write_tool_missing_path() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let tmp_dir = tmp_dir_guard.path().to_path_buf();
|
||||
|
||||
let tool = WriteTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({"content": "Hello"});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(result.is_error);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn write_tool_missing_content() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let tmp_dir = tmp_dir_guard.path().to_path_buf();
|
||||
|
||||
let tool = WriteTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
let args = json!({"path": "test.txt"});
|
||||
let result = tool.run(args, &cx).await;
|
||||
|
||||
assert!(result.is_error);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn write_tool_overwrite() {
|
||||
let tmp_dir_guard = tempfile::tempdir().expect("temp dir");
|
||||
let tmp_dir = tmp_dir_guard.path().to_path_buf();
|
||||
|
||||
let tool = WriteTool::new();
|
||||
let cx = test_context(&tmp_dir);
|
||||
|
||||
// Write initial content.
|
||||
let args1 = json!({
|
||||
"path": "test.txt",
|
||||
"content": "Initial content"
|
||||
});
|
||||
let result1 = tool.run(args1, &cx).await;
|
||||
assert!(!result1.is_error);
|
||||
|
||||
// Overwrite with new content.
|
||||
let args2 = json!({
|
||||
"path": "test.txt",
|
||||
"content": "Overwritten content"
|
||||
});
|
||||
let result2 = tool.run(args2, &cx).await;
|
||||
assert!(!result2.is_error);
|
||||
|
||||
// Verify file was overwritten.
|
||||
let content = std::fs::read_to_string(tmp_dir.join("test.txt")).unwrap();
|
||||
assert_eq!(content, "Overwritten content");
|
||||
}
|
||||
Reference in New Issue
Block a user