rpi-tools 0.34.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 write_content = content.clone();
        let pre_image: Result<PreImage, FileError> = with_tool_mutation_queue(
            if client_selected {
                self.file_io.as_deref()
            } else {
                None
            },
            &*env_ref,
            &abs_str,
            &signal,
            move |cancel: &CancellationToken| -> BoxFuture<'_, Result<PreImage, FileError>> {
                let abs_str = abs_for_closure;
                let content = write_content;
                async move {
                    check_abort(cancel)?;
                    // Absent file = empty pre-image (a real "create" diff).
                    // A read that fails for any other reason is surfaced as
                    // `diff_skipped` in details; the write itself proceeds
                    // (the pre-image is metadata, not part of the operation).
                    let pre = if client.is_some() {
                        // Client-owned files: the write transport has no
                        // read-pre-image contract yet, so report the diff as
                        // unavailable instead of paying an extra round-trip
                        // or fabricating one from the new content.
                        PreImage {
                            text: None,
                            read_error: Some("client_backend".to_string()),
                        }
                    } else if content.len() > MAX_DIFF_INPUT_BYTES {
                        PreImage {
                            text: None,
                            read_error: Some("content_too_large".to_string()),
                        }
                    } else {
                        let max_old_size = (MAX_DIFF_INPUT_BYTES - content.len()) as u64;
                        match env.as_env().file_info(&abs_str, Some(cancel)).await {
                            Ok(info) if info.size <= max_old_size => {
                                match env.as_env().read_text_file(&abs_str, Some(cancel)).await {
                                    Ok(text) => PreImage {
                                        text: Some(text),
                                        read_error: None,
                                    },
                                    Err(e) => PreImage {
                                        text: None,
                                        read_error: Some(e.code.as_str().to_string()),
                                    },
                                }
                            }
                            Ok(_) => PreImage {
                                text: None,
                                read_error: Some("content_too_large".to_string()),
                            },
                            Err(e) if e.code == FileErrorCode::NotFound => PreImage {
                                text: None,
                                read_error: None,
                            },
                            Err(e) => PreImage {
                                text: None,
                                read_error: Some(e.code.as_str().to_string()),
                            },
                        }
                    };
                    check_abort(cancel)?;
                    if let Some(client) = &client {
                        client
                            .write_text(&abs_str, content, cancel)
                            .await
                            .map_err(FileError::from)?;
                    } else {
                        env.as_env()
                            .write_file(&abs_str, FileContent::Text(content), Some(cancel))
                            .await?;
                    }
                    Ok(pre)
                }
                .boxed()
            },
        )
        .await;

        let pre = pre_image.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 if let Some(reason) = pre.read_error {
            diff_skipped(&reason)
        } else {
            mutation_diff_details(path_for_msg, pre.text.unwrap_or_default(), content, &signal)
                .await
        };

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

/// Pre-write snapshot used to build a real diff for the host.
struct PreImage {
    /// `None` = the file did not exist (a genuine create diff from "").
    text: Option<String>,
    /// Why the pre-image could not be read (non-NotFound). Hosts receive
    /// `diff_skipped` instead of a fabricated diff.
    read_error: Option<String>,
}

/// 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())
}