rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The tools that read a page as text: `read_page`, `find` and
//! `get_page_text`.

use super::calls::Reply;
use super::refs::StaleRef;
use super::schema::FIND_LIMIT;
use super::snapshot::{self, Filter, Read, View};
use super::tabs::{execution, OpenTab};
use super::text;
use crate::browser::VIEWPORT;
use rho_browser::cdp::accessibility::GetFullAxTree;
use rho_browser::cdp::dom_snapshot::CaptureSnapshot;
use rho_sdk::tool::ToolError;

/// The visible text of the page's main content, or of the whole page.
const PAGE_TEXT: &str =
    "(document.querySelector('main, [role=\"main\"], article') ?? document.body)?.innerText ?? ''";

/// The page's accessibility tree from `element`, or from the top, cut at
/// `limit` bytes.
pub(super) async fn read_page(
    open: &mut OpenTab,
    filter: Filter,
    depth: usize,
    element: Option<&str>,
    limit: usize,
) -> Result<Reply, ToolError> {
    let loader = open.document().await?;
    let start = element
        .map(|element| open.refs.node(element, &loader))
        .transpose()
        .map_err(stale)?;
    let tree = open.call(&GetFullAxTree { depth: None }).await?;
    let view = match filter {
        Filter::All => None,
        Filter::Visible | Filter::Interactive => open
            .call(&CaptureSnapshot::default())
            .await?
            .documents
            .first()
            .map(|document| View::of(document, VIEWPORT.width, VIEWPORT.height)),
    };
    let read = Read {
        filter,
        depth,
        start,
    };
    let rendered = snapshot::render(&tree.nodes, view.as_ref(), &read, &mut open.refs)
        .ok_or_else(|| stale(StaleRef(element.unwrap_or_default().to_owned())))?;
    let mut body = rendered.text;
    if body.is_empty() {
        body.push_str(match filter {
            Filter::Interactive => "No controls in the viewport.\n",
            Filter::Visible | Filter::All => "No elements.\n",
        });
    }
    match filter {
        Filter::Visible | Filter::Interactive => {
            body.push_str("[Viewport only; filter \"all\" reads the whole page.]\n")
        }
        Filter::All => {}
    }
    if rendered.cut_at_depth {
        body.push_str(&format!(
            "[Elements deeper than depth {depth} are left out; read one with its ref.]\n"
        ));
    }
    let url = open.url().await;
    Ok(Reply::text(text::fit(
        text::framed(&url, body.trim_end()),
        limit,
        "Read less with a smaller depth, a ref, or filter \"interactive\".",
    )))
}

/// The elements matching `query`, at most [`FIND_LIMIT`].
pub(super) async fn find(
    open: &mut OpenTab,
    query: &str,
    limit: usize,
) -> Result<Reply, ToolError> {
    open.document().await?;
    let tree = open.call(&GetFullAxTree { depth: None }).await?;
    let lines = snapshot::find(&tree.nodes, query, FIND_LIMIT, &mut open.refs);
    let body = if lines.is_empty() {
        format!("No elements match {query:?}.")
    } else {
        lines.join("\n")
    };
    let url = open.url().await;
    Ok(Reply::text(text::fit(text::framed(&url, &body), limit, "")))
}

/// The page's visible text, from its main content when it marks one.
pub(super) async fn page_text(open: &mut OpenTab, limit: usize) -> Result<Reply, ToolError> {
    let value = open.evaluate(PAGE_TEXT).await?;
    let body = value.as_str().unwrap_or_default().trim();
    let url = open.url().await;
    Ok(Reply::text(text::fit(
        text::framed(&url, body),
        limit,
        "Use read_page with a ref to read one part.",
    )))
}

fn stale(error: StaleRef) -> ToolError {
    execution(error.to_string())
}