use super::actions::{self, Done};
use super::inputs::{Request, TabsRequest};
use super::schema::Action;
use super::tabs::{execution, show_loading, Held, SessionTabs, Tabs};
use super::text::{self, Destination, READ_LIMIT};
use super::{reads, view};
use crate::browser::config::BrowserConfig;
use crate::browser::view::{acted_on, Placed};
use crate::browser::{connect, navigation};
use rho_browser::manager::Context;
use rho_browser::tab::{LoadError, Step};
use rho_sdk::model::{ImageContent, ToolSpec};
use rho_sdk::tool::{
OperationKind, Tool, ToolAsset, ToolContext, ToolError, ToolFuture, ToolInvocation,
ToolMetadata, ToolOutput, ToolSecurity,
};
use rho_sdk::{CapabilityKind, CapabilityRequest, CapabilitySource, NetworkTarget};
use serde_json::Value;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
pub(super) struct BrowserTool {
pub(super) tabs: Arc<SessionTabs>,
pub(super) action: Action,
pub(super) max_output_bytes: usize,
pub(super) offer: Arc<Offer>,
}
#[derive(Debug)]
pub(super) struct Offer {
pub(super) actions: Vec<Action>,
pub(super) upload_dir: Option<PathBuf>,
}
impl Offer {
pub(super) fn new(config: &BrowserConfig) -> Self {
Self {
actions: Action::offered(config),
upload_dir: config.upload_dir.clone(),
}
}
}
impl Default for Offer {
fn default() -> Self {
Self::new(&BrowserConfig::default())
}
}
impl Tool for BrowserTool {
fn spec(&self) -> ToolSpec {
ToolSpec {
name: self.action.name().into(),
description: self.action.description(&self.offer.actions),
input_schema: self.action.input_schema(),
}
}
fn security(&self) -> ToolSecurity {
match self.action {
Action::Wait => ToolSecurity::built_in([]),
_ => ToolSecurity::built_in([CapabilityKind::Network]),
}
}
fn start_metadata(&self, _arguments: &Value) -> ToolMetadata {
match self.action {
Action::Wait => ToolMetadata::new(),
_ => ToolMetadata::new().operation(OperationKind::Network),
}
}
fn call<'a>(&'a self, invocation: ToolInvocation, context: ToolContext) -> ToolFuture<'a> {
Box::pin(async move {
let arguments = invocation.into_arguments();
let upload_dir = self.offer.upload_dir.as_deref();
let request = match Request::parse(self.action, arguments, upload_dir)? {
Request::Wait { seconds } => {
return wait(seconds, &context).await.map(Reply::into_output)
}
Request::Tabs(request) => request,
};
if let TabsRequest::Navigate {
destination: Destination::Url(url),
..
} = &request
{
navigation::allowed(url.as_str())
.await
.map_err(|reason| execution(format!("Navigation refused: {reason}.")))?;
let target = NetworkTarget::Url(url.to_string());
authorize(&context, target, Action::Navigate).await?;
}
let card_tab = request.card_tab();
let mut held = self.tabs.hold().await?;
let before = held.tabs.current().map(str::to_owned);
let reply = self.run(&mut held, request, &context).await;
let placed = reply.as_ref().ok().and_then(|reply| reply.placed.clone());
let tabs = &held.tabs;
let card_tab = card_tab.linked(before.as_deref(), tabs.current(), |id| tabs.has(id));
held.show_tabs().await;
after_notices(reply, held.person_drove, held.lost_tabs).map(|output| match card_tab {
Some(tab) => {
let metadata = acted_on(output.presentation().clone(), &tab, placed.as_ref());
output.metadata(metadata)
}
None => output,
})
})
}
}
impl BrowserTool {
async fn run(
&self,
held: &mut Held<'_>,
request: TabsRequest,
context: &ToolContext,
) -> Result<Reply, ToolError> {
let tabs = &mut held.tabs;
let limit = READ_LIMIT.min(self.max_output_bytes);
match request {
TabsRequest::Navigate {
destination,
tab_id,
} => navigate(held, &destination, tab_id.as_deref()).await,
TabsRequest::ReadPage {
filter,
depth,
element,
tab_id,
} => {
let open = tabs.get(tab_id.as_deref())?;
reads::read_page(open, filter, depth, element.as_deref(), limit).await
}
TabsRequest::Find { query, tab_id } => {
let open = tabs.get(tab_id.as_deref())?;
reads::find(open, &query, limit).await
}
TabsRequest::GetPageText { tab_id } => {
let open = tabs.get(tab_id.as_deref())?;
reads::page_text(open, limit).await
}
TabsRequest::Screenshot { tab_id } => {
view::screenshot(tabs.get(tab_id.as_deref())?).await
}
TabsRequest::Zoom { region, tab_id } => {
view::zoom(tabs.get(tab_id.as_deref())?, region).await
}
TabsRequest::Scroll {
x,
y,
direction,
notches,
tab_id,
} => view::scroll(tabs.get(tab_id.as_deref())?, x, y, direction, notches).await,
TabsRequest::ScrollTo { element, tab_id } => {
view::scroll_to(tabs.get(tab_id.as_deref())?, &element).await
}
TabsRequest::Act { act, tab_id } => {
let open = tabs.get(tab_id.as_deref())?;
let target = NetworkTarget::PageAction(open.url().await);
authorize(context, target, self.action).await?;
let done = actions::run(tabs.get(tab_id.as_deref())?, &act).await;
acted(tabs, &held.context, tab_id.as_deref(), done).await
}
TabsRequest::NewTab => {
let id = tabs.open(&held.context).await?.id.clone();
let lines = tabs.lines().await;
tabs.note_shown(&lines);
Ok(Reply::text(format!(
"Created new tab with tab_id: {id}, URL: about:blank. It is now the current tab."
)))
}
TabsRequest::ListTabs => {
let opened = text::page_tabs(&tabs.take_in(&held.context).await);
let lines = tabs.lines().await;
tabs.note_shown(&lines);
let list = text::tab_list(&lines, tabs.current());
Ok(Reply::text(match opened {
Some(opened) => format!("{opened}\n\n{list}"),
None => list,
}))
}
TabsRequest::SwitchTab { tab_id } => {
tabs.switch(&tab_id)?;
Ok(Reply::text(format!("Switched to tab {tab_id}")))
}
TabsRequest::CloseTab { tab_id } => {
tabs.close(&tab_id).await?;
let mut text = format!("Closed tab {tab_id}");
if let Some(current) = tabs.current().map(str::to_owned) {
with_tab_context(tabs, &held.context, ¤t, &mut text).await;
}
Ok(Reply::text(text))
}
}
}
}
pub(super) struct Reply {
pub(super) text: String,
pub(super) image: Option<Image>,
pub(super) placed: Option<Placed>,
}
pub(super) struct Image {
pub(super) data: String,
pub(super) bytes: Vec<u8>,
}
impl Reply {
pub(super) fn text(text: impl Into<String>) -> Self {
Self {
text: text.into(),
image: None,
placed: None,
}
}
fn into_output(self) -> ToolOutput {
let output = ToolOutput::text(self.text);
match self.image {
None => output,
Some(Image { data, bytes }) => output
.metadata(ToolMetadata::new().asset(ToolAsset::new("image/jpeg", bytes)))
.with_images(vec![ImageContent {
data,
mime_type: "image/jpeg".to_owned(),
}]),
}
}
}
fn after_notices(
reply: Result<Reply, ToolError>,
person_drove: bool,
lost_tabs: bool,
) -> Result<ToolOutput, ToolError> {
const PERSON_DROVE: &str = "A person drove the browser since this session's last browser call, so its pages may have changed: refs from earlier reads may be stale.";
const LOST_TABS: &str = "The browser closed since this session's last browser call (it closes after going unused for a while, and when it crashes), so the session's earlier tabs and refs are gone.";
let notices: Vec<&str> = [
person_drove.then_some(PERSON_DROVE),
lost_tabs.then_some(LOST_TABS),
]
.into_iter()
.flatten()
.collect();
if notices.is_empty() {
return reply.map(Reply::into_output);
}
let notices = notices.join("\n\n");
match reply {
Ok(mut reply) => {
reply.text = format!("{notices}\n\n{}", reply.text);
Ok(reply.into_output())
}
Err(error) => Err(ToolError::new(
error.kind(),
format!("{notices}\n\n{}", error.message()),
)),
}
}
async fn navigate(
held: &mut Held<'_>,
destination: &Destination,
tab_id: Option<&str>,
) -> Result<Reply, ToolError> {
let browser = held.browser;
let tabs = &mut held.tabs;
let open = match (tab_id, tabs.current()) {
(None, None) => tabs.open(&held.context).await?,
(tab_id, _) => tabs.get(tab_id)?,
};
let new_url = match destination {
Destination::Url(url) => Some(url.as_str()),
Destination::Back | Destination::Forward | Destination::Reload => None,
};
let loading = show_loading(browser, held.context.id(), open, new_url);
let (loaded, target) = match destination {
Destination::Url(url) => (open.load(url.as_str()).await, url.to_string()),
Destination::Back => (open.go(Step::Back).await, "the previous page".to_owned()),
Destination::Forward => (open.go(Step::Forward).await, "the next page".to_owned()),
Destination::Reload => (open.go(Step::Reload).await, "the reloaded page".to_owned()),
};
drop(loading);
let dialogs = text::dialogs(&open.take_dialogs());
let unconnected = match (&loaded, destination) {
(Err(LoadError::Failed(reason)), Destination::Url(url)) if reason == UNCONNECTED => {
match (url.host_str(), url.port_or_known_default()) {
(Some(host), Some(port)) => Some(connect::explain(host, port).await),
_ => None,
}
}
_ => None,
};
loaded.map_err(|error| navigation_failed(&target, error, unconnected, dialogs.as_deref()))?;
let id = open.id.clone();
let url = match open.url().await {
url if url.is_empty() => target,
url => url,
};
let mut text = format!("Navigated to {}", text::url(&url));
if let Some(dialogs) = dialogs {
text.push_str("\n\n");
text.push_str(&dialogs);
}
with_tab_context(tabs, &held.context, &id, &mut text).await;
Ok(Reply::text(text))
}
async fn acted(
tabs: &mut Tabs,
context: &Context,
tab_id: Option<&str>,
done: Result<Done, ToolError>,
) -> Result<Reply, ToolError> {
let Ok(open) = tabs.get(tab_id) else {
return done.map(|done| Reply::text(done.text));
};
let id = open.id.clone();
let dialogs = text::dialogs(&open.take_dialogs());
let (mut text, placed) = match (done, dialogs) {
(Ok(done), None) => (done.text, done.placed),
(Ok(done), Some(dialogs)) => (format!("{}\n\n{dialogs}", done.text), done.placed),
(Err(error), None) => return Err(error),
(Err(error), Some(dialogs)) => {
let message = format!("{}\n\n{dialogs}", error.message());
return Err(ToolError::new(error.kind(), message));
}
};
with_tab_context(tabs, context, &id, &mut text).await;
Ok(Reply {
placed,
..Reply::text(text)
})
}
async fn with_tab_context(tabs: &mut Tabs, context: &Context, id: &str, text: &mut String) {
if let Some(opened) = text::page_tabs(&tabs.take_in(context).await) {
text.push_str("\n\n");
text.push_str(&opened);
}
let lines = tabs.lines().await;
if tabs.note_shown(&lines) {
text.push_str("\n\n");
text.push_str(&text::tab_context(&lines, id));
}
}
const UNCONNECTED: &str = "net::ERR_SOCKS_CONNECTION_FAILED";
fn navigation_failed(
target: &str,
error: LoadError,
unconnected: Option<String>,
dialogs: Option<&str>,
) -> ToolError {
let mut message = match error {
LoadError::TimedOut(limit) => format!(
"Navigation to {target} timed out after {} s, and its loading was stopped. Use screenshot or read_page to see what loaded.",
limit.as_secs()
),
LoadError::Failed(reason) if reason == "net::ERR_BLOCKED_BY_CLIENT" => format!(
"Navigation to {target} was refused: it led to a link-local or cloud-metadata address, which the browser does not load."
),
LoadError::Failed(reason) if reason == UNCONNECTED => match unconnected {
Some(why) => format!("Navigation to {target} failed: {why}."),
None => format!("Navigation to {target} failed: the browser could not connect."),
},
LoadError::Failed(reason) => format!("Navigation to {target} failed: {reason}."),
LoadError::NoHistory(_) | LoadError::Closed | LoadError::Cdp(_) => {
format!("Navigation to {target} failed: {error}.")
}
};
if let Some(dialogs) = dialogs {
message.push_str("\n\n");
message.push_str(dialogs);
}
execution(message)
}
async fn wait(seconds: f64, context: &ToolContext) -> Result<Reply, ToolError> {
tokio::select! {
() = tokio::time::sleep(Duration::from_secs_f64(seconds)) => {}
() = context.cancellation().cancelled() => return Err(ToolError::cancelled()),
}
Ok(Reply::text(format!("Waited {seconds} s.")))
}
async fn authorize(
context: &ToolContext,
target: NetworkTarget,
action: Action,
) -> Result<(), ToolError> {
context
.authorize(CapabilityRequest::network(
target,
CapabilitySource::built_in_tool(action.name()),
))
.await
.map(|_| ())
.map_err(|error| {
if error.kind() == rho_sdk::AuthorizationDenialKind::Cancelled {
ToolError::cancelled()
} else {
ToolError::policy_denied(&error)
}
})
}
#[cfg(test)]
#[path = "calls_live_tests.rs"]
mod live_tests;