mahbot 0.10.1

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
//! Safe chrome-use argv forms shared by the interactive `chrome` tool and the
//! `mahbot chrome` CLI: the numeric `wait <ms>` sleep form has no [`WaitTarget`]
//! variant, and expect conditions are a validated allowlist.

use crate::chrome::escape_js_single_quoted;
use serde_json::Value;

/// A leading-dash `fill`/`type` text is shielded with the `--` end-of-options
/// marker, which chrome-use's arg preprocessor drops and forwards verbatim
/// (otherwise a known flag of the same name could swallow it).
pub(crate) fn text_value_argv(text: &str) -> Vec<String> {
    if text.starts_with('-') {
        vec!["--".to_string(), text.to_string()]
    } else {
        vec![text.to_string()]
    }
}

/// The numeric sleep form (`wait 5000`) has no variant — [`wait_target`] rejects
/// it before one can be built.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum WaitTarget {
    Selector(String),
    Url(String),
    Text(String),
}

impl WaitTarget {
    pub(crate) fn describe(&self) -> String {
        match self {
            Self::Selector(s) => format!("selector '{s}'"),
            Self::Url(p) => format!("url pattern '{p}'"),
            Self::Text(t) => format!("text '{t}'"),
        }
    }
}

/// `--timeout <ms>` IS forwarded — chrome-use's wait forms honor it (verified
/// against 1.5.101); callers additionally bound the spawned step mahbot-side.
pub(crate) fn wait_args(target: &WaitTarget, timeout_ms: u128) -> Vec<String> {
    let mut args = match target {
        WaitTarget::Selector(s) => vec!["wait".to_string(), s.clone()],
        WaitTarget::Url(p) => vec!["wait".to_string(), "--url".to_string(), p.clone()],
        WaitTarget::Text(t) => vec!["wait".to_string(), "--text".to_string(), t.clone()],
    };
    args.push("--timeout".to_string());
    args.push(timeout_ms.to_string());
    args
}

/// The safe allowlist subset of chrome-use's grammar (gone/request/no-errors and
/// the --not/--regex/--no-wait flags are not exposed).
pub(crate) enum ExpectCond {
    State {
        selector: String,
        state: &'static str,
    }, // visible | hidden | present
    Count {
        selector: String,
        op: String,
        n: u64,
    },
    Text {
        selector: String,
        predicate: &'static str,
        value: String,
    },
    Value {
        selector: String,
        predicate: &'static str,
        value: String,
    },
    Attr {
        selector: String,
        name: String,
        predicate: &'static str,
        value: String,
    },
    Url {
        predicate: &'static str,
        pattern: String,
    },
}

pub(crate) fn parse_state(s: &str) -> Option<&'static str> {
    match s {
        "visible" => Some("visible"),
        "hidden" => Some("hidden"),
        "present" => Some("present"),
        _ => None,
    }
}

pub(crate) fn parse_predicate(s: &str) -> Option<&'static str> {
    match s {
        "equals" => Some("equals"),
        "contains" => Some("contains"),
        "matches" => Some("matches"),
        _ => None,
    }
}

/// Accepts symbols or word forms; the word is forwarded verbatim to chrome-use.
pub(crate) fn parse_count_op(s: &str) -> Option<String> {
    let valid = [
        "==", "!=", ">", "<", ">=", "<=", "eq", "ne", "gt", "lt", "ge", "le",
    ];
    valid.contains(&s).then(|| s.to_string())
}

/// Selector-first, chrome-use 1.5.101 grammar, plus the forwarded `--timeout <ms>`.
pub(crate) fn expect_args(cond: &ExpectCond, timeout_ms: u128) -> Vec<String> {
    let mut args = match cond {
        ExpectCond::State { selector, state } => {
            vec!["expect".to_string(), selector.clone(), (*state).to_string()]
        }
        ExpectCond::Count { selector, op, n } => vec![
            "expect".to_string(),
            "count".to_string(),
            selector.clone(),
            op.clone(),
            n.to_string(),
        ],
        ExpectCond::Text {
            selector,
            predicate,
            value,
        } => vec![
            "expect".to_string(),
            "text".to_string(),
            selector.clone(),
            (*predicate).to_string(),
            value.clone(),
        ],
        ExpectCond::Value {
            selector,
            predicate,
            value,
        } => vec![
            "expect".to_string(),
            "value".to_string(),
            selector.clone(),
            (*predicate).to_string(),
            value.clone(),
        ],
        ExpectCond::Attr {
            selector,
            name,
            predicate,
            value,
        } => vec![
            "expect".to_string(),
            "attr".to_string(),
            selector.clone(),
            name.clone(),
            (*predicate).to_string(),
            value.clone(),
        ],
        ExpectCond::Url { predicate, pattern } => vec![
            "expect".to_string(),
            "url".to_string(),
            (*predicate).to_string(),
            pattern.clone(),
        ],
    };
    args.push("--timeout".to_string());
    args.push(timeout_ms.to_string());
    args
}

pub(crate) fn describe(cond: &ExpectCond) -> String {
    match cond {
        ExpectCond::State { selector, state } => format!("'{selector}' is {state}"),
        ExpectCond::Count { selector, op, n } => format!("count('{selector}') {op} {n}"),
        ExpectCond::Text {
            selector,
            predicate,
            value,
        } => format!("text of '{selector}' {predicate} \"{value}\""),
        ExpectCond::Value {
            selector,
            predicate,
            value,
        } => format!("value of '{selector}' {predicate} \"{value}\""),
        ExpectCond::Attr {
            selector,
            name,
            predicate,
            value,
        } => format!("attr '{name}' of '{selector}' {predicate} \"{value}\""),
        ExpectCond::Url { predicate, pattern } => format!("url {predicate} \"{pattern}\""),
    }
}

/// Exactly one of selector/url/text, with one policy and one error text for both
/// frontends. A numeric selector is chrome-use's silent-sleep form (rc 0 without
/// waiting): rejected here, never forwarded.
pub(crate) fn wait_target(
    selector: Option<&str>,
    url: Option<&str>,
    text: Option<&str>,
) -> Result<WaitTarget, String> {
    match (selector, url, text) {
        (Some(s), None, None) if s.parse::<u64>().is_err() => {
            Ok(WaitTarget::Selector(s.to_string()))
        }
        (Some(_), None, None) => Err(
            "numeric wait is a silent sleep — not supported; wait for a selector, a URL pattern, or page text"
                .to_string(),
        ),
        (None, Some(u), None) => Ok(WaitTarget::Url(u.to_string())),
        (None, None, Some(t)) => Ok(WaitTarget::Text(t.to_string())),
        _ => Err(
            "give exactly one wait target — a selector, a URL pattern, or page text".to_string(),
        ),
    }
}

/// Eval JS counting elements matching `selector` — chrome-use has no standalone
/// count verb in the grammar we use. Top-document scope, which diverges from
/// chrome-use's frame-aware extract on iframed rows: an accepted heuristic, since
/// the gate exists to keep phantom rows out.
pub(crate) fn count_eval_js(selector: &str) -> String {
    format!(
        "document.querySelectorAll('{}').length",
        escape_js_single_quoted(selector)
    )
}

pub(crate) enum ExtractGate<E> {
    /// 0 matches — report the empty region WITHOUT invoking extract: chrome-use's
    /// rows-mode extract returns phantom rows on a 0-match, and its invalid-CSS
    /// auto-detect fallback manufactures rows too.
    Empty,
    Proceed,
    /// The count eval failed (e.g. an invalid CSS rows selector threw) — an explicit
    /// error, never a fallback to extract. Carries the caller's own classified
    /// failure so each frontend renders it in its native channel.
    Fail(E),
}

/// Shared by both frontends: count the rows selector ([`count_eval_js`]) and let
/// [`ExtractGate`] decide.
pub(crate) fn extract_gate<E>(count: Result<u64, E>) -> ExtractGate<E> {
    match count {
        Ok(0) => ExtractGate::Empty,
        Ok(_) => ExtractGate::Proceed,
        Err(e) => ExtractGate::Fail(e),
    }
}

/// The corrective suffix shared by every getter-validation error.
const GETTER_GRAMMAR: &str = "valid getters are \"text\" (default), \"html\", \"value\", or \
     \"@<attribute>\" (e.g. \"@href\"); attributes require the \"@\" prefix — a bare \
     attribute name is not a getter";

/// `get` must be "text" (default) | "@<attribute>" | "html" | "value", "@" alone is
/// invalid. chrome-use silently falls back to textContent for unknown getters, which
/// produced plausible-but-wrong `ok:true` extractions (rc 0, no signal) — mahbot
/// rejects them loudly instead. The allowlist is pinned to the documented grammar
/// (stable across 1.5.10x); extend it if a release documents new getters.
pub(crate) fn validate_extract_getters(schema: &Value) -> Result<(), String> {
    let Some(fields) = schema.get("fields").and_then(Value::as_object) else {
        // Missing or non-object "fields" is shape-checked elsewhere.
        return Ok(());
    };
    for (name, field) in fields {
        let Some(obj) = field.as_object() else {
            continue; // plain CSS-selector string fields need no getter check.
        };
        let Some(get) = obj.get("get") else {
            continue;
        };
        let Some(getter) = get.as_str() else {
            return Err(format!(
                "extract field '{name}' has a non-string getter {get} — {GETTER_GRAMMAR}"
            ));
        };
        if let Some(attr) = getter.strip_prefix('@') {
            if attr.is_empty() {
                return Err(format!(
                    "extract field '{name}' has an empty getter \"@\" — {GETTER_GRAMMAR}"
                ));
            }
            continue;
        }
        if !matches!(getter, "text" | "html" | "value") {
            return Err(format!(
                "extract field '{name}' has an invalid getter \"{getter}\" — {GETTER_GRAMMAR}"
            ));
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn argv(args: &[String]) -> Vec<&str> {
        args.iter().map(String::as_str).collect()
    }

    #[test]
    fn wait_and_expect_args_carry_every_target() {
        {
            let case = "wait args forwards timeout for every target";
            let wait_cases = [
                (
                    "selector",
                    WaitTarget::Selector("#main".into()),
                    vec!["wait", "#main"],
                ),
                (
                    "url",
                    WaitTarget::Url("https://example.com".into()),
                    vec!["wait", "--url", "https://example.com"],
                ),
                (
                    "text",
                    WaitTarget::Text("Loaded".into()),
                    vec!["wait", "--text", "Loaded"],
                ),
            ];
            for (name, target, mut expected) in wait_cases {
                expected.extend(["--timeout", "8000"]);
                assert_eq!(
                    argv(&wait_args(&target, 8000)),
                    expected,
                    "case {case}: {name}"
                );
            }
        }

        {
            let case = "expect args covers every variant";
            let expect_cases = [
                (
                    "state",
                    ExpectCond::State {
                        selector: "#main".into(),
                        state: "visible",
                    },
                    vec!["expect", "#main", "visible"],
                ),
                (
                    "count",
                    ExpectCond::Count {
                        selector: ".card".into(),
                        op: "==".into(),
                        n: 3,
                    },
                    vec!["expect", "count", ".card", "==", "3"],
                ),
                (
                    "text",
                    ExpectCond::Text {
                        selector: "#main".into(),
                        predicate: "contains",
                        value: "hello".into(),
                    },
                    vec!["expect", "text", "#main", "contains", "hello"],
                ),
                (
                    "value",
                    ExpectCond::Value {
                        selector: "input".into(),
                        predicate: "equals",
                        value: "abc".into(),
                    },
                    vec!["expect", "value", "input", "equals", "abc"],
                ),
                (
                    "attr",
                    ExpectCond::Attr {
                        selector: "a".into(),
                        name: "href".into(),
                        predicate: "matches",
                        value: "example.com".into(),
                    },
                    vec!["expect", "attr", "a", "href", "matches", "example.com"],
                ),
                (
                    "url",
                    ExpectCond::Url {
                        predicate: "contains",
                        pattern: "dashboard".into(),
                    },
                    vec!["expect", "url", "contains", "dashboard"],
                ),
            ];
            for (name, cond, mut expected) in expect_cases {
                expected.extend(["--timeout", "8000"]);
                assert_eq!(
                    argv(&expect_args(&cond, 8000)),
                    expected,
                    "case {case}: {name}"
                );
            }
        }
    }

    #[test]
    fn parse_each_wait_predicate_part_accepts_and_rejects() {
        {
            let case = "parse state accepts and rejects";
            for state in ["visible", "hidden", "present"] {
                assert_eq!(
                    parse_state(state),
                    Some(state),
                    "case {case}: {state:?} is a documented state"
                );
            }
            for state in ["gone", "VISIBLE", ""] {
                assert_eq!(
                    parse_state(state),
                    None,
                    "case {case}: {state:?} is not a state"
                );
            }
        }

        {
            let case = "parse predicate accepts and rejects";
            for predicate in ["equals", "contains", "matches"] {
                assert_eq!(
                    parse_predicate(predicate),
                    Some(predicate),
                    "case {case}: {predicate:?} is a documented predicate"
                );
            }
            for predicate in ["regex", "EQUALS", ""] {
                assert_eq!(
                    parse_predicate(predicate),
                    None,
                    "case {case}: {predicate:?} is not a predicate"
                );
            }
        }

        {
            let case = "parse count op accepts symbols and words";
            for op in [
                "==", "!=", ">", "<", ">=", "<=", "eq", "ne", "gt", "lt", "ge", "le",
            ] {
                assert_eq!(
                    parse_count_op(op).as_deref(),
                    Some(op),
                    "case {case}: op {op:?} should parse"
                );
            }
        }

        {
            let case = "parse count op rejects unknowns";
            for op in [">>", "=", "like", " between ", ""] {
                assert_eq!(
                    parse_count_op(op),
                    None,
                    "case {case}: op {op:?} should be rejected"
                );
            }
        }
    }

    /// The count verb's JS wrapper escapes the selector, so a quote or a backslash
    /// in it can neither end nor alter the single-quoted literal.
    #[test]
    fn count_eval_js_escapes_single_quotes_and_backslashes() {
        for (name, selector, js) in [
            ("quote", "a'b", "document.querySelectorAll('a\\'b').length"),
            (
                "backslash",
                "a\\b",
                "document.querySelectorAll('a\\\\b').length",
            ),
            (
                "plain",
                "div.c",
                "document.querySelectorAll('div.c').length",
            ),
        ] {
            assert_eq!(count_eval_js(selector), js, "{name}");
        }
    }

    #[test]
    fn wait_target_rejects_numeric_and_multiple_targets() {
        assert_eq!(
            wait_target(Some("#x"), None, None),
            Ok(WaitTarget::Selector("#x".into()))
        );
        assert_eq!(
            wait_target(None, Some("dash"), None),
            Ok(WaitTarget::Url("dash".into()))
        );
        assert_eq!(
            wait_target(None, None, Some("hi")),
            Ok(WaitTarget::Text("hi".into()))
        );
        // The numeric silent-sleep form is rejected, never forwarded.
        let err = wait_target(Some("5000"), None, None).unwrap_err();
        assert!(err.contains("silent sleep"), "err: {err}");
        assert!(wait_target(Some("#x"), Some("dash"), None).is_err());
        assert!(wait_target(None, None, None).is_err());
        assert!(wait_target(Some("#x"), Some("d"), Some("t")).is_err());
    }

    /// `text`/`html`/`value` and `@<attribute>` pass, everything else is refused.
    #[test]
    fn validate_extract_getters_accepts_the_grammar_and_rejects_the_rest() {
        struct Case {
            name: &'static str,
            schema: Value,
            /// Substrings the refusal must name; `None` means the schema is valid.
            refused: Option<&'static [&'static str]>,
        }

        let cases = [
            Case {
                name: "accepts_documented_grammar",
                schema: serde_json::json!({
                    "rows": ".card",
                    "fields": {
                        "t": {"sel": ".a", "get": "text"},
                        "h": {"sel": ".b", "get": "html"},
                        "v": {"sel": ".c", "get": "value"},
                        "u": {"sel": "a", "get": "@href"},
                        "plain": ".title",
                    },
                }),
                refused: None,
            },
            Case {
                name: "field_object_without_get",
                schema: serde_json::json!({"fields": {"title": {"sel": ".title"}}}),
                refused: None,
            },
            Case {
                name: "plain_string_fields",
                schema: serde_json::json!({"fields": {"title": ".title", "url": "a"}}),
                refused: None,
            },
            Case {
                name: "missing_fields",
                schema: serde_json::json!({"rows": ".card"}),
                refused: None,
            },
            Case {
                name: "non_object_fields",
                schema: serde_json::json!({"fields": ".title"}),
                refused: None,
            },
            Case {
                name: "bare_attribute_name",
                schema: serde_json::json!({"fields": {"link": {"sel": "a", "get": "href"}}}),
                refused: Some(&["@", "getter", "href"]),
            },
            Case {
                name: "empty_getter",
                schema: serde_json::json!({"fields": {"u": {"sel": "a", "get": "@"}}}),
                refused: Some(&["empty getter"]),
            },
            Case {
                name: "non_string_getter",
                schema: serde_json::json!({"fields": {"u": {"sel": "a", "get": 42}}}),
                refused: Some(&["non-string getter"]),
            },
        ];

        for case in cases {
            match case.refused {
                None => assert!(
                    validate_extract_getters(&case.schema).is_ok(),
                    "{}: must pass",
                    case.name
                ),
                Some(substrings) => {
                    let err = validate_extract_getters(&case.schema)
                        .expect_err("the getter must be refused");
                    for needle in substrings {
                        assert!(err.contains(needle), "{}: {err}", case.name);
                    }
                }
            }
        }
    }
}