rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The two tools config has to turn on, as they widen what a page that
//! manipulates the model could make it do: `javascript_exec`, which runs
//! the model's JavaScript with the page's privileges, and `file_upload`,
//! which hands the page files from the upload directory and nowhere else.

use super::schema::SCRIPT_LIMIT;
use super::tabs::{execution, Node, OpenTab};
use super::text::{self, READ_LIMIT};
use rho_browser::cdp::dom::SetFileInputFiles;
use rho_browser::cdp::runtime::{
    CallArgument, CallFunctionOn, Evaluate, Evaluated, ReleaseObject, RemoteObject,
};
use rho_sdk::tool::ToolError;
use serde::Deserialize;
use serde_json::Value;
use std::path::{Path, PathBuf};

/// Files `file_upload` may hand a page: each inside the upload directory,
/// links and `..` followed. Only [`uploads`] makes them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Uploads(Vec<PathBuf>);

/// `paths`, absolute or relative to the upload directory `dir`, as files
/// inside `dir`, or why one is not.
pub(super) fn uploads(dir: &Path, paths: &[PathBuf]) -> Result<Uploads, String> {
    if paths.is_empty() {
        return Err("paths must name at least one file".to_owned());
    }
    let root = dir.canonicalize().map_err(|error| {
        format!(
            "the upload directory {} (browser.upload_dir) is unusable: {error}",
            dir.display()
        )
    })?;
    let files = paths
        .iter()
        .map(|path| {
            let file = root
                .join(path)
                .canonicalize()
                .map_err(|error| format!("could not upload {}: {error}", path.display()))?;
            if !file.starts_with(&root) {
                return Err(format!(
                    "could not upload {}: only files in the upload directory {} can be uploaded",
                    path.display(),
                    root.display()
                ));
            }
            if !file.is_file() {
                return Err(format!("could not upload {}: not a file", path.display()));
            }
            Ok(file)
        })
        .collect::<Result<_, _>>()?;
    Ok(Uploads(files))
}

/// What an element is, as `file_upload` needs to know it.
const FILE_INPUT: &str = r##"function () {
  const file = this.localName === "input" && this.type === "file";
  return { file, multiple: file && this.multiple };
}"##;

#[derive(Deserialize)]
struct FileInput {
    file: bool,
    multiple: bool,
}

/// Sets the files of the file input `node` to `files`.
pub(super) async fn upload(
    open: &mut OpenTab,
    node: &Node<'_>,
    files: &Uploads,
) -> Result<String, ToolError> {
    let element = node.name;
    let input: FileInput = serde_json::from_value(open.call_on(node, FILE_INPUT, vec![]).await?)
        .map_err(|error| execution(format!("the browser answered oddly: {error}")))?;
    if !input.file {
        return Err(execution(format!(
            "{element} is not a file input (<input type=\"file\">), so it takes no files."
        )));
    }
    let Uploads(files) = files;
    if files.len() > 1 && !input.multiple {
        return Err(execution(format!(
            "{element} takes one file, not {}.",
            files.len()
        )));
    }
    let set = SetFileInputFiles {
        files: files
            .iter()
            .map(|file| file.display().to_string())
            .collect(),
        backend_node_id: node.id,
    };
    open.on_node(&set).await?.ok_or_else(|| node.stale())?;
    let names: Vec<String> = files
        .iter()
        .map(|file| {
            file.file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .into_owned()
        })
        .collect();
    Ok(format!(
        "Set the files of {element} to {}.",
        names.join(", ")
    ))
}

/// Runs `script` in the page's own world and returns its value as text,
/// framed as the page's.
pub(super) async fn run_script(open: &mut OpenTab, script: &str) -> Result<String, ToolError> {
    let evaluate = Evaluate {
        expression: script.to_owned(),
        context_id: None,
        // A handle, so a value JSON cannot hold, such as a DOM node, still
        // has a description.
        return_by_value: false,
        await_promise: true,
        timeout: Some(SCRIPT_LIMIT.as_millis() as u64),
    };
    let evaluated = open.call(&evaluate).await.map_err(|error| {
        execution(format!(
            "{} A script, or a promise it returns, has {} s.",
            error.message(),
            SCRIPT_LIMIT.as_secs()
        ))
    })?;
    let text = match script_value(&evaluated) {
        Ok(Shown::Text(text)) => text,
        Ok(Shown::Object(object)) => object_text(open, &object).await,
        Err(thrown) => {
            release_thrown(open, evaluated).await;
            return Err(execution(format!("The script threw: {thrown}")));
        }
    };
    let url = open.url().await;
    let narrower = "Return less, such as one property or a slice.";
    Ok(text::framed(&url, &text::fit(text, READ_LIMIT, narrower)))
}

/// How a script's value is shown.
#[derive(Debug, PartialEq)]
enum Shown {
    /// As this text.
    Text(String),
    /// As the object it is, which the page has to describe.
    Object(RemoteObject),
}

/// What `evaluated` shows, or what the script threw.
fn script_value(evaluated: &Evaluated) -> Result<Shown, String> {
    if let Some(details) = &evaluated.exception_details {
        return Err(details
            .exception
            .as_ref()
            .and_then(|thrown| thrown.description.clone().or_else(|| primitive(thrown)))
            .unwrap_or_else(|| details.text.clone()));
    }
    let result = &evaluated.result;
    Ok(match primitive(result) {
        Some(text) => Shown::Text(text),
        None if result.object_id.is_some() => Shown::Object(result.clone()),
        None => Shown::Text(result.description.clone().unwrap_or_default()),
    })
}

/// A value that is not an object, as text: a string as itself, anything
/// else as JavaScript writes it.
fn primitive(value: &RemoteObject) -> Option<String> {
    match (value.kind.as_str(), &value.value) {
        ("undefined", _) => Some("undefined".to_owned()),
        // JSON's `null` reads as no value; an object without a handle is
        // `null` all the same.
        ("object", None) if value.object_id.is_none() => Some("null".to_owned()),
        ("string", Some(Value::String(text))) => Some(text.clone()),
        (_, Some(value)) if !value.is_object() && !value.is_array() => Some(value.to_string()),
        _ => value.unserializable_value.clone(),
    }
}

/// An object as JSON, when it is plain data, or else as the console would
/// describe it: an element or a function says what it is rather than `{}`.
const OBJECT_TEXT: &str = r##"function () {
  if (typeof this === "function" || this instanceof Node || this instanceof Window) return null;
  try {
    const json = JSON.stringify(this);
    return json === undefined ? null : json;
  } catch (error) {
    return null;
  }
}"##;

/// `object` as text, letting go of the page's handle to it.
async fn object_text(open: &OpenTab, object: &RemoteObject) -> String {
    let Some(object_id) = object.object_id.clone() else {
        return object.description.clone().unwrap_or_default();
    };
    let json = open
        .call(&CallFunctionOn {
            function_declaration: OBJECT_TEXT.to_owned(),
            object_id: object_id.clone(),
            arguments: Vec::<CallArgument>::new(),
            return_by_value: true,
            await_promise: false,
        })
        .await
        .ok()
        .and_then(|called| called.result.value)
        .and_then(|value| value.as_str().map(str::to_owned));
    // A handle the page keeps holds its object until the page goes.
    let _ = open.call(&ReleaseObject { object_id }).await;
    json.or_else(|| object.description.clone())
        .unwrap_or_else(|| "null".to_owned())
}

/// Lets go of the handles to what a script threw, which the page keeps
/// until then.
async fn release_thrown(open: &OpenTab, evaluated: Evaluated) {
    let thrown = evaluated
        .exception_details
        .and_then(|details| details.exception);
    let mut handles: Vec<_> = [
        evaluated.result.object_id,
        thrown.and_then(|thrown| thrown.object_id),
    ]
    .into_iter()
    .flatten()
    .collect();
    handles.dedup();
    for object_id in handles {
        let _ = open.call(&ReleaseObject { object_id }).await;
    }
}

#[cfg(test)]
#[path = "opt_in_tests.rs"]
mod tests;