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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! Each browser tool's input, parsed and checked before the browser starts,
//! so a bad call costs nothing.

use super::actions::{Act, Pointer, Target};
use super::keys;
use super::opt_in;
use super::schema::{Action, DEFAULT_NOTCHES, KEY_REPEAT, SCROLL_NOTCHES, WAIT_SECONDS};
use super::snapshot::Filter;
use super::text::{self, Destination};
use crate::browser::VIEWPORT;
use rho_browser::cdp::input::Modifiers;
use rho_sdk::tool::{ToolError, ToolErrorKind};
use serde::Deserialize;
use serde_json::Value;
use std::path::{Path, PathBuf};

/// A browser tool call's input.
pub(super) enum Request {
    /// `wait`, which needs no browser.
    Wait { seconds: f64 },
    /// Every other tool, which runs on the session's tabs.
    Tabs(TabsRequest),
}

pub(super) enum TabsRequest {
    Navigate {
        destination: Destination,
        tab_id: Option<String>,
    },
    ReadPage {
        filter: Filter,
        depth: usize,
        element: Option<String>,
        tab_id: Option<String>,
    },
    Find {
        query: String,
        tab_id: Option<String>,
    },
    GetPageText {
        tab_id: Option<String>,
    },
    Screenshot {
        tab_id: Option<String>,
    },
    Zoom {
        region: Region,
        tab_id: Option<String>,
    },
    Scroll {
        x: u32,
        y: u32,
        direction: Direction,
        notches: u8,
        tab_id: Option<String>,
    },
    ScrollTo {
        element: String,
        tab_id: Option<String>,
    },
    /// An action on the page: a click, typing, a key or a form field.
    Act {
        act: Act,
        tab_id: Option<String>,
    },
    NewTab,
    ListTabs,
    SwitchTab {
        tab_id: String,
    },
    CloseTab {
        tab_id: String,
    },
}

/// The tab a call's card links to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum CardTab {
    /// The tab the call names.
    Named(String),
    /// The tab that was current as the call started, which it acted on, or
    /// the one it opened when there was none.
    ActedOn,
    /// The current tab once the call ran: the one it opened or switched to.
    Current,
    /// None, for a call about the tab list or one that closes a tab.
    Nothing,
}

impl CardTab {
    /// The tab to link, given the current tab `before` the call ran and
    /// `after` it, as long as the session still `has` it: a call whose tab
    /// closed, as a popup that closed itself on a click, links none.
    pub(super) fn linked(
        self,
        before: Option<&str>,
        after: Option<&str>,
        has: impl Fn(&str) -> bool,
    ) -> Option<String> {
        match self {
            Self::Named(id) => Some(id),
            Self::ActedOn => before.or(after).map(str::to_owned),
            Self::Current => after.map(str::to_owned),
            Self::Nothing => None,
        }
        .filter(|id| has(id))
    }
}

impl TabsRequest {
    /// The tab the call's card links to.
    pub(super) fn card_tab(&self) -> CardTab {
        match self {
            Self::Navigate { tab_id, .. }
            | Self::ReadPage { tab_id, .. }
            | Self::Find { tab_id, .. }
            | Self::GetPageText { tab_id }
            | Self::Screenshot { tab_id }
            | Self::Zoom { tab_id, .. }
            | Self::Scroll { tab_id, .. }
            | Self::ScrollTo { tab_id, .. }
            | Self::Act { tab_id, .. } => tab_id.clone().map_or(CardTab::ActedOn, CardTab::Named),
            Self::NewTab | Self::SwitchTab { .. } => CardTab::Current,
            Self::ListTabs | Self::CloseTab { .. } => CardTab::Nothing,
        }
    }
}

/// A rectangle within the viewport, in viewport pixels.
#[derive(Debug, Clone, Copy)]
pub(super) struct Region {
    pub(super) x0: u32,
    pub(super) y0: u32,
    pub(super) x1: u32,
    pub(super) y1: u32,
}

#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(super) enum Direction {
    Up,
    Down,
    Left,
    Right,
}

impl Direction {
    pub(super) fn name(self) -> &'static str {
        match self {
            Self::Up => "up",
            Self::Down => "down",
            Self::Left => "left",
            Self::Right => "right",
        }
    }
}

/// `read_page`'s `filter` as the model writes it; omitted reads the
/// viewport.
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum ReadFilter {
    Interactive,
    All,
}

#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
enum CoordinateTarget {
    Coordinate { x: i64, y: i64 },
}

#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
enum AnyTarget {
    Coordinate {
        x: i64,
        y: i64,
    },
    Ref {
        #[serde(rename = "ref")]
        element: String,
    },
}

impl AnyTarget {
    fn parse(self) -> Result<Target, ToolError> {
        match self {
            Self::Coordinate { x, y } => {
                let (x, y) = point(x, y)?;
                Ok(Target::Point { x, y })
            }
            Self::Ref { element } => Ok(Target::Ref(element)),
        }
    }
}

/// A click of `pointer`'s kind: a target and the keys held during it.
fn pointing(pointer: Pointer, arguments: Value) -> Result<TabsRequest, ToolError> {
    #[derive(Deserialize)]
    #[serde(deny_unknown_fields)]
    struct Input {
        target: AnyTarget,
        modifiers: Option<String>,
        tab_id: Option<String>,
    }
    let input: Input = parse(arguments)?;
    let modifiers = match input.modifiers.as_deref() {
        None | Some("") => Modifiers::NONE,
        Some(text) => keys::modifiers(text).map_err(invalid)?,
    };
    let act = Act::Point {
        pointer,
        target: input.target.parse()?,
        modifiers,
    };
    Ok(TabsRequest::Act {
        act,
        tab_id: input.tab_id,
    })
}

#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
enum RefTarget {
    Ref {
        #[serde(rename = "ref")]
        element: String,
    },
}

impl Request {
    /// The input of a call to `action`. `upload_dir` is where
    /// `file_upload` takes files from.
    pub(super) fn parse(
        action: Action,
        arguments: Value,
        upload_dir: Option<&Path>,
    ) -> Result<Self, ToolError> {
        let tabs = match action {
            Action::Wait => {
                #[derive(Deserialize)]
                #[serde(deny_unknown_fields)]
                struct Input {
                    duration: f64,
                    #[allow(dead_code)]
                    tab_id: Option<String>,
                }
                let input: Input = parse(arguments)?;
                if !(0.0..=WAIT_SECONDS).contains(&input.duration) {
                    return Err(invalid(format!(
                        "duration must be 0 to {WAIT_SECONDS} seconds; got {}",
                        input.duration
                    )));
                }
                return Ok(Self::Wait {
                    seconds: input.duration,
                });
            }
            Action::Navigate => {
                #[derive(Deserialize)]
                #[serde(deny_unknown_fields)]
                struct Input {
                    url: String,
                    tab_id: Option<String>,
                }
                let input: Input = parse(arguments)?;
                TabsRequest::Navigate {
                    destination: text::destination(&input.url).map_err(invalid)?,
                    tab_id: input.tab_id,
                }
            }
            Action::ReadPage => {
                #[derive(Deserialize)]
                #[serde(deny_unknown_fields)]
                struct Input {
                    filter: Option<ReadFilter>,
                    depth: Option<usize>,
                    #[serde(rename = "ref")]
                    element: Option<String>,
                    tab_id: Option<String>,
                }
                let input: Input = parse(arguments)?;
                TabsRequest::ReadPage {
                    filter: match input.filter {
                        None => Filter::Visible,
                        Some(ReadFilter::Interactive) => Filter::Interactive,
                        Some(ReadFilter::All) => Filter::All,
                    },
                    depth: input.depth.unwrap_or(super::schema::DEFAULT_DEPTH).max(1),
                    element: input.element,
                    tab_id: input.tab_id,
                }
            }
            Action::Find => {
                #[derive(Deserialize)]
                #[serde(deny_unknown_fields)]
                struct Input {
                    query: String,
                    tab_id: Option<String>,
                }
                let input: Input = parse(arguments)?;
                TabsRequest::Find {
                    query: input.query,
                    tab_id: input.tab_id,
                }
            }
            Action::GetPageText => TabsRequest::GetPageText {
                tab_id: parse::<TabOnly>(arguments)?.tab_id,
            },
            Action::Screenshot => TabsRequest::Screenshot {
                tab_id: parse::<TabOnly>(arguments)?.tab_id,
            },
            Action::Zoom => {
                #[derive(Deserialize)]
                #[serde(deny_unknown_fields)]
                struct Input {
                    region: [i64; 4],
                    tab_id: Option<String>,
                }
                let input: Input = parse(arguments)?;
                TabsRequest::Zoom {
                    region: region(input.region)?,
                    tab_id: input.tab_id,
                }
            }
            Action::Scroll => {
                #[derive(Deserialize)]
                #[serde(deny_unknown_fields)]
                struct Input {
                    target: CoordinateTarget,
                    scroll_direction: Direction,
                    scroll_amount: Option<u8>,
                    tab_id: Option<String>,
                }
                let input: Input = parse(arguments)?;
                let CoordinateTarget::Coordinate { x, y } = input.target;
                let notches = input.scroll_amount.unwrap_or(DEFAULT_NOTCHES);
                if !SCROLL_NOTCHES.contains(&notches) {
                    return Err(invalid(format!(
                        "scroll_amount must be {} to {}; got {notches}",
                        SCROLL_NOTCHES.start(),
                        SCROLL_NOTCHES.end()
                    )));
                }
                let (x, y) = point(x, y)?;
                TabsRequest::Scroll {
                    x,
                    y,
                    direction: input.scroll_direction,
                    notches,
                    tab_id: input.tab_id,
                }
            }
            Action::ScrollTo => {
                #[derive(Deserialize)]
                #[serde(deny_unknown_fields)]
                struct Input {
                    target: RefTarget,
                    tab_id: Option<String>,
                }
                let input: Input = parse(arguments)?;
                let RefTarget::Ref { element } = input.target;
                TabsRequest::ScrollTo {
                    element,
                    tab_id: input.tab_id,
                }
            }
            Action::LeftClick => pointing(Pointer::Left, arguments)?,
            Action::RightClick => pointing(Pointer::Right, arguments)?,
            Action::MiddleClick => pointing(Pointer::Middle, arguments)?,
            Action::DoubleClick => pointing(Pointer::Double, arguments)?,
            Action::TripleClick => pointing(Pointer::Triple, arguments)?,
            Action::Hover => {
                #[derive(Deserialize)]
                #[serde(deny_unknown_fields)]
                struct Input {
                    target: AnyTarget,
                    tab_id: Option<String>,
                }
                let input: Input = parse(arguments)?;
                let act = Act::Point {
                    pointer: Pointer::Hover,
                    target: input.target.parse()?,
                    modifiers: Modifiers::NONE,
                };
                TabsRequest::Act {
                    act,
                    tab_id: input.tab_id,
                }
            }
            Action::Type => {
                #[derive(Deserialize)]
                #[serde(deny_unknown_fields)]
                struct Input {
                    text: String,
                    tab_id: Option<String>,
                }
                let input: Input = parse(arguments)?;
                TabsRequest::Act {
                    act: Act::Type(input.text),
                    tab_id: input.tab_id,
                }
            }
            Action::Key => {
                #[derive(Deserialize)]
                #[serde(deny_unknown_fields)]
                struct Input {
                    text: String,
                    repeat: Option<u8>,
                    tab_id: Option<String>,
                }
                let input: Input = parse(arguments)?;
                let repeat = input.repeat.unwrap_or(1);
                if !KEY_REPEAT.contains(&repeat) {
                    return Err(invalid(format!(
                        "repeat must be {} to {}; got {repeat}",
                        KEY_REPEAT.start(),
                        KEY_REPEAT.end()
                    )));
                }
                let act = Act::Key {
                    chords: keys::sequence(&input.text).map_err(invalid)?,
                    text: input.text,
                    repeat,
                };
                TabsRequest::Act {
                    act,
                    tab_id: input.tab_id,
                }
            }
            Action::FormInput => {
                #[derive(Deserialize)]
                #[serde(deny_unknown_fields)]
                struct Input {
                    target: RefTarget,
                    value: Value,
                    tab_id: Option<String>,
                }
                let input: Input = parse(arguments)?;
                if !matches!(
                    input.value,
                    Value::String(_) | Value::Number(_) | Value::Bool(_)
                ) {
                    return Err(invalid(format!(
                        "value must be a string, number or boolean; got {}",
                        input.value
                    )));
                }
                let RefTarget::Ref { element } = input.target;
                TabsRequest::Act {
                    act: Act::FormInput {
                        element,
                        value: input.value,
                    },
                    tab_id: input.tab_id,
                }
            }
            Action::JavascriptExec => {
                #[derive(Deserialize)]
                #[serde(deny_unknown_fields)]
                struct Input {
                    text: String,
                    tab_id: Option<String>,
                }
                let input: Input = parse(arguments)?;
                TabsRequest::Act {
                    act: Act::Script(input.text),
                    tab_id: input.tab_id,
                }
            }
            Action::FileUpload => {
                #[derive(Deserialize)]
                #[serde(deny_unknown_fields)]
                struct Input {
                    target: RefTarget,
                    paths: Vec<PathBuf>,
                    tab_id: Option<String>,
                }
                let input: Input = parse(arguments)?;
                // Offered only with an upload directory.
                let dir = upload_dir.ok_or_else(|| {
                    invalid("file_upload is not enabled: set browser.upload_dir in config")
                })?;
                let files = opt_in::uploads(dir, &input.paths).map_err(invalid)?;
                let RefTarget::Ref { element } = input.target;
                TabsRequest::Act {
                    act: Act::Upload { element, files },
                    tab_id: input.tab_id,
                }
            }
            Action::NewTab => {
                parse::<NoInput>(arguments)?;
                TabsRequest::NewTab
            }
            Action::ListTabs => {
                parse::<NoInput>(arguments)?;
                TabsRequest::ListTabs
            }
            Action::SwitchTab => TabsRequest::SwitchTab {
                tab_id: parse::<TabInput>(arguments)?.tab_id,
            },
            Action::CloseTab => TabsRequest::CloseTab {
                tab_id: parse::<TabInput>(arguments)?.tab_id,
            },
        };
        Ok(Self::Tabs(tabs))
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct NoInput {}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TabOnly {
    tab_id: Option<String>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TabInput {
    tab_id: String,
}

fn parse<T: serde::de::DeserializeOwned>(arguments: Value) -> Result<T, ToolError> {
    serde_json::from_value(arguments).map_err(|error| invalid(error.to_string()))
}

fn invalid(message: impl Into<String>) -> ToolError {
    ToolError::new(ToolErrorKind::InvalidArguments, message)
}

/// `[x0, y0, x1, y1]`, if it is a non-empty rectangle within the viewport.
fn region([x0, y0, x1, y1]: [i64; 4]) -> Result<Region, ToolError> {
    let (width, height) = (i64::from(VIEWPORT.width), i64::from(VIEWPORT.height));
    if !(0 <= x0 && x0 < x1 && x1 <= width && 0 <= y0 && y0 < y1 && y1 <= height) {
        return Err(invalid(format!(
            "region must be [x0, y0, x1, y1] with 0 <= x0 < x1 <= {width} and 0 <= y0 < y1 <= {height}; got [{x0}, {y0}, {x1}, {y1}]"
        )));
    }
    let pixels = |value: i64| u32::try_from(value).expect("checked against the viewport");
    Ok(Region {
        x0: pixels(x0),
        y0: pixels(y0),
        x1: pixels(x1),
        y1: pixels(y1),
    })
}

/// `(x, y)`, if it is within the viewport.
fn point(x: i64, y: i64) -> Result<(u32, u32), ToolError> {
    let (width, height) = (i64::from(VIEWPORT.width), i64::from(VIEWPORT.height));
    if (0..width).contains(&x) && (0..height).contains(&y) {
        let pixels = |value: i64| u32::try_from(value).expect("checked against the viewport");
        Ok((pixels(x), pixels(y)))
    } else {
        Err(invalid(format!(
            "({x}, {y}) is outside the {width}x{height} viewport"
        )))
    }
}

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