rpi-tools 0.35.0

Built-in agent tools (read/write/edit/bash/powershell) + ExecutionEnv, Rust port of pi harness tools
Documentation
//! Built-in `write` tool. Writes content to a file (creating parent directories),
//! serialized per canonical path. Cancellation keeps the queue held until the
//! write returns. A successful write can still skip the optional diff preview.

use std::sync::Arc;

use async_trait::async_trait;
use futures::future::BoxFuture;
use futures::FutureExt;
use rpi_agent::agent_tool::AgentTool;
use rpi_agent::error::AgentError;
use rpi_agent::types::{AgentToolResult, TextContentOrImage, ToolResultPartial};
use rpi_ai::types::{ConstrainedSamplingConfig, ConstrainedStrictness, Tool};
use schemars::JsonSchema;
use serde::Deserialize;
use tokio_util::sync::CancellationToken;

use crate::env::FileContent;
use crate::error::{FileError, FileErrorCode};
use crate::file_io::{
    resolve_client_path, with_tool_mutation_queue, FileIOOperation, FileIORouter,
};
use crate::file_mutation_queue::MutatingEnv;
use crate::path_utils::resolve_tool_path;
use crate::tools::edit_diff::{diff_skipped, mutation_diff_details, MAX_DIFF_INPUT_BYTES};
use crate::tools::tool_context::ExecutionToolContext;

// Input for the write tool. Mirrors TS `WriteToolInput`.
#[derive(Debug, Clone, JsonSchema, Deserialize)]
pub struct WriteInput {
    /// Path to the file to write (relative or absolute).
    pub path: String,
    /// Content to write to the file.
    pub content: String,
}

/// The built-in `write` tool. Holds the mutating env (for the queue + writes).
pub struct WriteTool {
    schema: Tool,
    env: Arc<dyn MutatingEnv>,
    file_io: Option<Arc<FileIORouter>>,
}

impl WriteTool {
    fn schema() -> Tool {
        let params = schemars::schema_for!(WriteInput);
        Tool {
            name: "write".to_string(),
            description: "Write content to a file. Creates the file if it doesn't exist, \
                          overwrites if it does. Automatically creates parent directories."
                .to_string(),
            parameters: rpi_ai::types::Schema::new(
                serde_json::to_value(params).unwrap_or_default(),
            ),
            constrained_sampling: Some(ConstrainedSamplingConfig::JsonSchema {
                strict: ConstrainedStrictness::Prefer,
            }),
        }
    }
}

/// Build the `write` tool from a context. Requires a mutation-capable env.
/// Mirrors TS `createWriteTool`.
pub fn create_write_tool(context: &ExecutionToolContext) -> Arc<dyn AgentTool> {
    let env = context
        .mutating_env()
        .expect("write tool requires a mutation-capable ExecutionToolContext")
        .clone();
    Arc::new(WriteTool {
        schema: WriteTool::schema(),
        env,
        file_io: context.file_io().cloned(),
    })
}

#[async_trait]
impl AgentTool for WriteTool {
    fn schema(&self) -> &Tool {
        &self.schema
    }
    fn label(&self) -> &str {
        "write"
    }

    async fn execute(
        &self,
        _tool_call_id: &str,
        params: serde_json::Value,
        signal: CancellationToken,
        _on_update: Arc<dyn Fn(ToolResultPartial) + Send + Sync>,
    ) -> Result<AgentToolResult, AgentError> {
        let input: WriteInput = serde_json::from_value(params)
            .map_err(|e| AgentError::Validation(format!("write input invalid: {e}")))?;
        let path_for_msg = input.path.clone();
        let content = input.content;

        // Freeze authority before any local path resolution or queue access.
        let client = match &self.file_io {
            Some(router) => router
                .select(FileIOOperation::Write)
                .await
                .map_err(|e| file_err_to_agent(e.into()))?,
            None => None,
        };
        let abs = if client.is_some() {
            resolve_client_path(self.env.as_env().cwd(), &path_for_msg)
                .map_err(|e| file_err_to_agent(e.into()))?
        } else {
            resolve_tool_path(self.env.as_env(), &path_for_msg, Some(&signal))
                .await
                .map_err(file_err_to_agent)?
        };
        let abs_str = abs;
        let client_selected = client.is_some();

        // The pre-image read and the write run in the *same* per-path mutation
        // queue: the diff must describe exactly the bytes this call replaced,
        // not a racing snapshot.
        let env = self.env.clone();
        let env_ref = env.clone();
        let abs_for_closure = abs_str.clone();
        let preview = with_tool_mutation_queue(
            if client_selected {
                self.file_io.as_deref()
            } else {
                None
            },
            &*env_ref,
            &abs_str,
            &signal,
            move |cancel: &CancellationToken| -> BoxFuture<'_, Result<PreviewInput, FileError>> {
                async move {
                    check_abort(cancel)?;
                    let previous = if client.is_some() {
                        Err("client_backend")
                    } else if content.len() > MAX_DIFF_INPUT_BYTES {
                        Err("content_too_large")
                    } else {
                        let max_old_bytes = MAX_DIFF_INPUT_BYTES - content.len();
                        match env
                            .as_env()
                            .read_text_file_bounded(&abs_for_closure, max_old_bytes, Some(cancel))
                            .await
                        {
                            Ok(Some(text)) => Ok(text),
                            Ok(None) => Err("content_too_large"),
                            Err(error) if error.code == FileErrorCode::NotFound => {
                                Ok(String::new())
                            }
                            Err(error) => Err(error.code.as_str()),
                        }
                    };
                    let preview = previous.map(|old| (old, content.clone()));
                    check_abort(cancel)?;
                    if let Some(client) = &client {
                        client
                            .write_text(&abs_for_closure, content, cancel)
                            .await
                            .map_err(FileError::from)?;
                    } else {
                        env.as_env()
                            .write_file(&abs_for_closure, FileContent::Text(content), Some(cancel))
                            .await?;
                    }
                    Ok(preview)
                }
                .boxed()
            },
        )
        .await;

        let preview = preview.map_err(file_err_to_agent)?;
        let message = format!("Successfully wrote to {path_for_msg}");
        let details = if signal.is_cancelled() {
            diff_skipped("cancelled")
        } else {
            match preview {
                Ok((old, new)) => mutation_diff_details(path_for_msg, old, new, &signal).await,
                Err(reason) => diff_skipped(reason),
            }
        };

        Ok(AgentToolResult {
            content: vec![TextContentOrImage::text(message)],
            details,
            ..Default::default()
        })
    }
}

/// Old and new text for a preview, or the reason it was skipped.
type PreviewInput = Result<(String, String), &'static str>;

/// Check the cancel token, returning `Err(FileError::aborted())` when set.
/// Mirrors the TS `if (signal?.aborted) throw new Error("Operation aborted")`.
fn check_abort(cancel: &CancellationToken) -> Result<(), FileError> {
    if cancel.is_cancelled() {
        return Err(FileError::new(FileErrorCode::Aborted, "Operation aborted"));
    }
    Ok(())
}

fn file_err_to_agent(e: FileError) -> AgentError {
    AgentError::Tool(e.to_string())
}