use super::text::READ_LIMIT;
use crate::browser::config::BrowserConfig;
use crate::browser::VIEWPORT;
use serde_json::{json, Value};
use std::ops::RangeInclusive;
use std::time::Duration;
pub(super) const NAVIGATION_LIMIT: Duration = Duration::from_secs(30);
pub(super) const SCRIPT_LIMIT: Duration = super::tabs::CALL_LIMIT;
pub(super) const WAIT_SECONDS: f64 = 30.0;
pub(super) const NOTCH: u32 = 100;
pub(super) const SCROLL_NOTCHES: RangeInclusive<u8> = 1..=10;
pub(super) const DEFAULT_NOTCHES: u8 = 3;
pub(super) const FIND_LIMIT: usize = 20;
pub(super) const DEFAULT_DEPTH: usize = 15;
pub(super) const KEY_REPEAT: RangeInclusive<u8> = 1..=100;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Action {
Navigate,
ReadPage,
Find,
GetPageText,
Screenshot,
Zoom,
Scroll,
ScrollTo,
LeftClick,
RightClick,
MiddleClick,
DoubleClick,
TripleClick,
Hover,
Type,
Key,
FormInput,
Wait,
NewTab,
ListTabs,
SwitchTab,
CloseTab,
JavascriptExec,
FileUpload,
}
impl Action {
pub(super) const ALL: [Self; 24] = [
Self::Navigate,
Self::ReadPage,
Self::Find,
Self::GetPageText,
Self::Screenshot,
Self::Zoom,
Self::Scroll,
Self::ScrollTo,
Self::LeftClick,
Self::RightClick,
Self::MiddleClick,
Self::DoubleClick,
Self::TripleClick,
Self::Hover,
Self::Type,
Self::Key,
Self::FormInput,
Self::Wait,
Self::NewTab,
Self::ListTabs,
Self::SwitchTab,
Self::CloseTab,
Self::JavascriptExec,
Self::FileUpload,
];
pub(super) fn offered(config: &BrowserConfig) -> Vec<Self> {
Self::ALL
.into_iter()
.filter(|action| match action {
Self::JavascriptExec => config.javascript_exec,
Self::FileUpload => config.upload_dir.is_some(),
_ => true,
})
.collect()
}
pub(super) fn name(self) -> &'static str {
match self {
Self::Navigate => "navigate",
Self::ReadPage => "read_page",
Self::Find => "find",
Self::GetPageText => "get_page_text",
Self::Screenshot => "screenshot",
Self::Zoom => "zoom",
Self::Scroll => "scroll",
Self::ScrollTo => "scroll_to",
Self::LeftClick => "left_click",
Self::RightClick => "right_click",
Self::MiddleClick => "middle_click",
Self::DoubleClick => "double_click",
Self::TripleClick => "triple_click",
Self::Hover => "hover",
Self::Type => "type",
Self::Key => "key",
Self::FormInput => "form_input",
Self::Wait => "wait",
Self::NewTab => "new_tab",
Self::ListTabs => "list_tabs",
Self::SwitchTab => "switch_tab",
Self::CloseTab => "close_tab",
Self::JavascriptExec => "javascript_exec",
Self::FileUpload => "file_upload",
}
}
pub(super) fn description(self, offered: &[Self]) -> String {
let (min_notches, max_notches) = (SCROLL_NOTCHES.start(), SCROLL_NOTCHES.end());
let others: Vec<&str> = offered
.iter()
.copied()
.filter(|action| *action != Self::Navigate)
.map(Self::name)
.collect();
match self {
Self::Navigate => format!(
"Load an http or https URL in the browser, or move through history with \"back\", \"forward\" or \"reload\". A URL without a scheme is https. Opens a tab when none is open. Returns once the page loads or its network goes quiet, at most {} s. The other browser tools ({}) load through tool_search.",
NAVIGATION_LIMIT.as_secs(),
others.join(", ")
),
Self::ReadPage => format!(
"Return the page's accessibility tree as text, each element tagged with a reference such as [ref_2]. With filter omitted, every element in the viewport; \"interactive\", only the viewport's controls; \"all\", also elements outside the viewport. depth caps the tree depth (default {DEFAULT_DEPTH}) and ref reads that element's subtree. Output is capped at {READ_LIMIT} bytes; narrow with depth, ref or filter."
),
Self::Find => format!(
"Find elements matching a description such as \"search field\" or \"add to cart button\", matched against their roles, names and values, and return up to {FIND_LIMIT} in read_page's format."
),
Self::GetPageText => "Return the page's visible text as plain text: the main or article element's when the page has one, else the whole page's. Suited to articles and documentation.".to_owned(),
Self::Screenshot => format!(
"Capture the viewport ({}x{}) as an image.",
VIEWPORT.width, VIEWPORT.height
),
Self::Zoom => "Return a cropped, upscaled image of region [x0, y0, x1, y1], in viewport pixels, to read small text or controls.".to_owned(),
Self::Scroll => format!(
"Scroll at a viewport position, which scrolls the element under it. scroll_amount is in wheel notches of {NOTCH} px, {min_notches} to {max_notches}, default {DEFAULT_NOTCHES}."
),
Self::ScrollTo => "Scroll a referenced element into view.".to_owned(),
Self::LeftClick => format!(
"Left-click a viewport coordinate or a referenced element. A referenced element is scrolled into view and clicked at its center, and the click fails if another element covers it there. modifiers is a chord held during the click, such as \"shift\" or \"ctrl+shift\". Returns once the page has acted on the click, or when it starts a navigation, once the next page loads, at most {} s.",
NAVIGATION_LIMIT.as_secs()
),
Self::RightClick => "Right-click a coordinate or element, as left_click does.".to_owned(),
Self::MiddleClick => "Middle-click a coordinate or element, as left_click does.".to_owned(),
Self::DoubleClick => "Double left-click a coordinate or element, as left_click does.".to_owned(),
Self::TripleClick => "Triple left-click a coordinate or element, as left_click does, which typically selects a line or paragraph.".to_owned(),
Self::Hover => "Move the pointer over a coordinate or element without clicking.".to_owned(),
Self::Type => "Type a literal string at the current focus. A line break presses Enter.".to_owned(),
Self::Key => format!(
"Press a key or chord: a single key (\"Enter\"), a chord joined with + (\"ctrl+a\"), or a space-separated sequence (\"Backspace Backspace\"). repeat is {} to {}, default 1.",
KEY_REPEAT.start(),
KEY_REPEAT.end()
),
Self::FormInput => "Set a form element's value directly: true or false for a checkbox or radio button, an option's value or visible text for a select, and text for other fields.".to_owned(),
Self::Wait => format!(
"Wait duration seconds, 0 to {WAIT_SECONDS}, such as for a page to update."
),
Self::NewTab => "Open a blank tab and make it the current tab.".to_owned(),
Self::ListTabs => "List the open tabs, including any a page opened.".to_owned(),
Self::SwitchTab => "Make tab_id the current tab.".to_owned(),
Self::CloseTab => "Close tab_id.".to_owned(),
Self::JavascriptExec => format!(
"Run text as JavaScript in the page, with the page's own privileges, and return the value of its last expression as text. Write an expression, not a return statement; a promise it returns is awaited, at most {} s.",
SCRIPT_LIMIT.as_secs()
),
Self::FileUpload => "Set the files of a file input (<input type=\"file\">) a ref names to paths in the upload directory, absolute or relative to it. Only files inside that directory can be uploaded.".to_owned(),
}
}
pub(super) fn input_schema(self) -> Value {
let tab_id = json!({
"type": "string",
"description": "The tab to use, such as \"tab-2\"; the current tab when omitted."
});
let (properties, required): (Value, &[&str]) = match self {
Self::Navigate => (
json!({
"url": {
"type": "string",
"description": "An http(s) URL, or \"back\", \"forward\" or \"reload\"."
},
"tab_id": tab_id,
}),
&["url"],
),
Self::ReadPage => (
json!({
"filter": { "type": "string", "enum": ["interactive", "all"] },
"depth": { "type": "integer", "minimum": 1, "default": DEFAULT_DEPTH },
"ref": { "type": "string", "description": "An element reference such as \"ref_2\"." },
"tab_id": tab_id,
}),
&[],
),
Self::Find => (
json!({
"query": { "type": "string", "description": "What to find, in plain words." },
"tab_id": tab_id,
}),
&["query"],
),
Self::GetPageText | Self::Screenshot => (json!({ "tab_id": tab_id }), &[]),
Self::Zoom => (
json!({
"region": {
"type": "array",
"items": { "type": "integer" },
"minItems": 4,
"maxItems": 4,
"description": "[x0, y0, x1, y1] in viewport pixels."
},
"tab_id": tab_id,
}),
&["region"],
),
Self::Scroll => (
json!({
"target": coordinate_target(),
"scroll_direction": { "type": "string", "enum": ["up", "down", "left", "right"] },
"scroll_amount": {
"type": "integer",
"minimum": SCROLL_NOTCHES.start(),
"maximum": SCROLL_NOTCHES.end(),
"default": DEFAULT_NOTCHES
},
"tab_id": tab_id,
}),
&["target", "scroll_direction"],
),
Self::ScrollTo => (
json!({ "target": ref_target(), "tab_id": tab_id }),
&["target"],
),
Self::LeftClick
| Self::RightClick
| Self::MiddleClick
| Self::DoubleClick
| Self::TripleClick => (
json!({
"target": target(),
"modifiers": {
"type": "string",
"description": "Keys held during the click, such as \"shift\" or \"ctrl+shift\"."
},
"tab_id": tab_id,
}),
&["target"],
),
Self::Hover => (json!({ "target": target(), "tab_id": tab_id }), &["target"]),
Self::Type => (
json!({ "text": { "type": "string" }, "tab_id": tab_id }),
&["text"],
),
Self::Key => (
json!({
"text": {
"type": "string",
"description": "A key (\"Enter\"), a chord (\"ctrl+a\") or keys separated by spaces (\"Backspace Backspace\")."
},
"repeat": {
"type": "integer",
"minimum": KEY_REPEAT.start(),
"maximum": KEY_REPEAT.end(),
"default": 1
},
"tab_id": tab_id,
}),
&["text"],
),
Self::FormInput => (
json!({
"target": ref_target(),
"value": { "type": ["string", "number", "boolean"] },
"tab_id": tab_id,
}),
&["target", "value"],
),
Self::Wait => (
json!({
"duration": { "type": "number", "minimum": 0, "maximum": WAIT_SECONDS },
"tab_id": tab_id,
}),
&["duration"],
),
Self::JavascriptExec => (
json!({
"text": { "type": "string", "description": "JavaScript whose last expression's value is returned." },
"tab_id": tab_id,
}),
&["text"],
),
Self::FileUpload => (
json!({
"target": ref_target(),
"paths": {
"type": "array",
"items": { "type": "string" },
"minItems": 1,
"description": "Files in the upload directory, absolute or relative to it."
},
"tab_id": tab_id,
}),
&["target", "paths"],
),
Self::NewTab | Self::ListTabs => (json!({}), &[]),
Self::SwitchTab | Self::CloseTab => (
json!({ "tab_id": { "type": "string", "description": "Such as \"tab-2\"." } }),
&["tab_id"],
),
};
json!({
"type": "object",
"properties": properties,
"required": required,
"additionalProperties": false,
})
}
}
fn coordinate_target() -> Value {
json!({
"type": "object",
"properties": {
"type": { "const": "coordinate" },
"x": { "type": "integer" },
"y": { "type": "integer" },
},
"required": ["type", "x", "y"],
"additionalProperties": false,
})
}
fn target() -> Value {
json!({ "oneOf": [coordinate_target(), ref_target()] })
}
fn ref_target() -> Value {
json!({
"type": "object",
"properties": {
"type": { "const": "ref" },
"ref": { "type": "string", "description": "An element reference such as \"ref_2\"." },
},
"required": ["type", "ref"],
"additionalProperties": false,
})
}
#[cfg(test)]
#[path = "schema_tests.rs"]
mod tests;