rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Each browser tool as an SDK tool: its input parsed before the browser
//! starts, then one function per tool on the session's tabs.

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>,
}

/// What `[browser]` offers a session: which tools, and where
/// `file_upload` takes files from.
#[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,
            };
            // Checked before the browser starts, so a refusal costs
            // nothing. The browser checks every later load itself.
            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())?;
                // Asked of each action, so a mode that only reads, such as
                // plan mode, can refuse it.
                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, &current, &mut text).await;
                }
                Ok(Reply::text(text))
            }
        }
    }
}

/// What a browser tool answers.
pub(super) struct Reply {
    pub(super) text: String,
    pub(super) image: Option<Image>,
    /// Where the element a click or hover by ref acted on was.
    pub(super) placed: Option<Placed>,
}

/// A captured image, base64 for the model and decoded for the transcript.
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(),
                }]),
        }
    }
}

/// `reply` as the tool's output, telling the model first what happened to
/// the session's browser while it was not looking: since its last call, a
/// person drove it, or the browser closed, taking the session's earlier
/// tabs.
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))
}

/// `done`, what an action did on tab `tab_id` or why it failed, followed
/// by the dialogs the page opened meanwhile and, when it did, the tab list
/// if it changed, such as when the action navigated.
async fn acted(
    tabs: &mut Tabs,
    context: &Context,
    tab_id: Option<&str>,
    done: Result<Done, ToolError>,
) -> Result<Reply, ToolError> {
    // A tab that closed has no dialogs left to tell of.
    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)
    })
}

/// Appends to `text` the tabs pages in `context` opened since the last
/// look, and the tab list, as seen from tab `id`, when the model has not
/// seen it as it is now.
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));
    }
}

/// What Chrome reports for a page whose connection rho's proxy did not
/// make, whatever the reason.
const UNCONNECTED: &str = "net::ERR_SOCKS_CONNECTION_FAILED";

/// Why navigating to `target` failed. `unconnected` says why the browser
/// could not connect, when that is why.
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()
        ),
        // Only the browser's check on each load refuses one this way.
        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."
        ),
        // rho's proxy did not make a connection the page needed.
        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.")))
}

/// Asks the session's permission policy whether `action` may reach
/// `target`: load a URL, as `fetch_content` does for one it fetches, or act
/// on the page there.
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;