From 1e00854da33b873e1d696720c0f43a77c50813c6 Mon Sep 17 00:00:00 2001 From: Jhen-Jie Hong Date: Thu, 8 Oct 2026 18:38:24 +0800 Subject: [PATCH 1/6] =?UTF-8?q?Agent=20browser:=20agents=20drive=20?= =?UTF-8?q?=E2=8C=97=20tabs=20through=20mpx=20browser?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Host Settings ▸ Agent browser (per host, synced, default off) lets agents on that host open and operate web pages beside its terminal via `mpx browser` (mpx-cli PR). The app runs `mpx bridge` over its own SSH connection and serves requests against AGENT viewport tabs only. - Tabs: helpers in an isolated WKContentWorld (still no message handler — the page gets no bridge), the host's own data store, docked beside the agent's tmux session on a window that is on screen; focus taken only through AgentFocusGate (never mid-typing, once per 30 s per host). - Route: pages load THROUGH THE HOST — a loopback CONNECT proxy for the tabs' data store, every connection an SSH direct-tcpip from the host, so the device's LAN is never on the path. A real device never proxies loopback, so host localhost ports are forwarded on the device, admitted by an HttpOnly per-proxy cookie (`forward --open` opts a port out) and closed with the host's last agent tab; a loopback rule list blocks every other device port. WebRTC is removed from agent tabs. - Robustness: bounded wire integers and buffers, per-host quotas, stale requests dropped after suspension (bridge clock from trusted pongs), revocation cancels in-flight work and closes the host's tabs, the link redials on network change, backpressured tunnels. --- AGENTS.md | 3 +- Multiplex/App/AppRuntime.swift | 8 +- Multiplex/Localizable.xcstrings | 80 +++ .../AgentBrowserAddressPolicy.swift | 159 +++++ .../AgentBrowser/AgentBrowserScript.swift | 621 +++++++++++++++++ .../AgentBrowser/AgentBrowserWire.swift | 323 +++++++++ .../Models/AgentBrowser/AgentFocusGate.swift | 47 ++ .../Models/AgentBrowser/AgentProxyHead.swift | 135 ++++ Multiplex/Models/ConnectRetryBackoff.swift | 3 +- Multiplex/Models/Host.swift | 18 +- Multiplex/Models/TerminalRoute.swift | 11 +- Multiplex/Models/ViewportReach.swift | 14 +- Multiplex/Services/AgentBrowserDriver.swift | 204 ++++++ Multiplex/Services/AgentBrowserLink.swift | 373 +++++++++++ Multiplex/Services/AgentBrowserLog.swift | 7 + Multiplex/Services/AgentBrowserProxy.swift | 511 ++++++++++++++ Multiplex/Services/AgentBrowserService.swift | 623 ++++++++++++++++++ Multiplex/Services/HostStore.swift | 3 + Multiplex/Services/SSHConnection.swift | 60 ++ Multiplex/Services/TerminalWorkspace.swift | 57 +- Multiplex/Services/ViewportController.swift | 142 +++- Multiplex/Views/Deck/AddHostSheet.swift | 41 ++ .../Views/Terminal/TerminalWindowUIKit.swift | 14 +- MultiplexTests/AddHostUIKitTests.swift | 1 + MultiplexTests/AgentBrowserTests.swift | 413 ++++++++++++ MultiplexTests/AgentProxySpliceTests.swift | 62 ++ docs/agents/architecture.md | 10 + docs/agents/e2e-headless.md | 17 + docs/agents/links-and-viewers.md | 109 ++- fastlane/testflight-whats-new.txt | 1 + 30 files changed, 4038 insertions(+), 32 deletions(-) create mode 100644 Multiplex/Models/AgentBrowser/AgentBrowserAddressPolicy.swift create mode 100644 Multiplex/Models/AgentBrowser/AgentBrowserScript.swift create mode 100644 Multiplex/Models/AgentBrowser/AgentBrowserWire.swift create mode 100644 Multiplex/Models/AgentBrowser/AgentFocusGate.swift create mode 100644 Multiplex/Models/AgentBrowser/AgentProxyHead.swift create mode 100644 Multiplex/Services/AgentBrowserDriver.swift create mode 100644 Multiplex/Services/AgentBrowserLink.swift create mode 100644 Multiplex/Services/AgentBrowserLog.swift create mode 100644 Multiplex/Services/AgentBrowserProxy.swift create mode 100644 Multiplex/Services/AgentBrowserService.swift create mode 100644 MultiplexTests/AgentBrowserTests.swift create mode 100644 MultiplexTests/AgentProxySpliceTests.swift diff --git a/AGENTS.md b/AGENTS.md index fcc1f6a9..8e2c30c7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -87,7 +87,8 @@ approaches. Don't re-litigate a recorded decision without new facts. - `input-and-windows.md` — keyboard focus, key rail/ornament cluster, terminal window chrome, dictation, Copy Mode / Select Text, scene routing and tab moves, keyboard avoidance, secret fields, held-backspace filler. -- `links-and-viewers.md` — link/path confirmation, ⌗ viewport, ▤ file viewer. +- `links-and-viewers.md` — link/path confirmation, ⌗ viewport, agent + browser (`mpx browser` agent tabs), ▤ file viewer. - `backends-and-probe.md` — tmux invocation facts, mixed tmux+herdr hosts, the herdr adaptation, session creation (setup scripts, per-host tmux conf, systemd-run), file attach/drop. diff --git a/Multiplex/App/AppRuntime.swift b/Multiplex/App/AppRuntime.swift index ed2f0e6d..2670e8b7 100644 --- a/Multiplex/App/AppRuntime.swift +++ b/Multiplex/App/AppRuntime.swift @@ -13,7 +13,7 @@ final class AppRuntime { let entitlements: EntitlementStore let attention: AttentionCenter let localNetworkAccess = LocalNetworkAccessMonitor() - let networkChanges = NetworkChangeMonitor() + let networkChanges: NetworkChangeMonitor let appLock = AppLockStore() let externalActions = ExternalActionRouter.shared let bind = BindController.shared @@ -21,6 +21,8 @@ final class AppRuntime { /// `didFinishLaunchingWithOptions` (BGTaskScheduler rejects anything /// later) and re-scheduled whenever the app leaves. let backgroundRefresh: BackgroundRefresh + /// `mpx browser` for hosts that opted in (Host Settings ▸ Agent Browser). + let agentBrowser: AgentBrowserService init() { // Attention wiring: every probe's events funnel through one center, @@ -44,6 +46,9 @@ final class AppRuntime { hub: hub, attention: attention ) + let networkChanges = NetworkChangeMonitor() + self.networkChanges = networkChanges + agentBrowser = AgentBrowserService(store: store, workspace: workspace, networkChanges: networkChanges) // Background keep-alive: the assertion is taken only when a host the // user opted in has something for the extra time to do, so the @@ -75,6 +80,7 @@ final class AppRuntime { } BackgroundActivity.shared.start() backgroundRefresh.start() + agentBrowser.start() #if DEBUG backgroundRefresh.installDebugHook() #endif diff --git a/Multiplex/Localizable.xcstrings b/Multiplex/Localizable.xcstrings index 7cdae55a..094f2f1a 100644 --- a/Multiplex/Localizable.xcstrings +++ b/Multiplex/Localizable.xcstrings @@ -1648,6 +1648,86 @@ } } }, + "Agent browser" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "エージェントブラウザ" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Agent 瀏覽器" + } + } + } + }, + "Agents on this host can open and operate web pages in Multiplex" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このホストのエージェントが Multiplex で Web ページを開いて操作できます" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "這部主機上的 Agent 可以在 Multiplex 中開啟並操作網頁" + } + } + } + }, + "Let agents drive a browser" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "エージェントにブラウザを操作させる" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "讓 Agent 操作瀏覽器" + } + } + } + }, + "Off: agents on this host cannot open pages in Multiplex." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "オフ:このホストのエージェントは Multiplex でページを開けません。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "關閉:這部主機上的 Agent 無法在 Multiplex 中開啟網頁。" + } + } + } + }, + "While Multiplex is open, agents on this host can open web pages beside your terminal and read, click, and type in them with `mpx browser` (mpx 0.2 or later; `mpx skill install` teaches an agent how). Agent tabs load through this host over SSH, so they see the host's network and never your device's; they keep their own cookies and never see your own tabs." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Multiplex が開いている間、このホストのエージェントは `mpx browser` でターミナルの横に Web ページを開き、読み取り・クリック・入力ができます(mpx 0.2 以降が必要。`mpx skill install` でエージェントに使い方を教えられます)。エージェントのタブは SSH 経由でこのホストを通して読み込まれるため、見えるのはホストのネットワークだけで、あなたのデバイスのネットワークには届きません。独自の Cookie を持ち、あなた自身のタブは見えません。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Multiplex 開啟時,這部主機上的 Agent 可以用 `mpx browser` 在終端機旁開啟網頁,並讀取、點按與輸入內容(需要 mpx 0.2 以上;`mpx skill install` 會教 Agent 如何使用)。Agent 標籤頁經由 SSH 透過這部主機載入,只看得到主機的網路,碰不到你裝置所在的網路;它們有自己的 Cookie,也看不到你自己的標籤頁。" + } + } + } + }, "✳ AGENT HELPERS · PRO" : { "localizations" : { "ja" : { diff --git a/Multiplex/Models/AgentBrowser/AgentBrowserAddressPolicy.swift b/Multiplex/Models/AgentBrowser/AgentBrowserAddressPolicy.swift new file mode 100644 index 00000000..6707aa7f --- /dev/null +++ b/Multiplex/Models/AgentBrowser/AgentBrowserAddressPolicy.swift @@ -0,0 +1,159 @@ +import Foundation + +/// Where an agent may point a browser that runs on the user's device. Pure. +/// +/// Shipping (host route): pages load through the host, so `admitViaHost` +/// only gates the scheme and keeps `localhost` as the host's; what stays +/// on the device is loopback, which `loopbackPort` names for forwarding and +/// `loopbackRuleListJSON` guards. +/// +/// DEBUG device route (`admit`, `admits`, `contentRuleListJSON`): the page +/// loads from the device's network, so a tab reaches the internet and THIS +/// host and no other private address — judged per main-frame navigation and +/// per subresource by content rules. Neither sees DNS: a public name that +/// resolves to a private address still loads, which is why the host route +/// ships. +enum AgentBrowserAddressPolicy { + /// An agent-typed address → the URL the device will load, or why not. + static func admit(_ input: String, host: Host) -> Result { + guard let offer = ViewportOffer.fromTypedInput(input, host: host) else { + return .failure(.badRequest("'\(input)' is not an http(s) address.")) + } + guard admits(offer.url, host: host) else { + return .failure(blockedError(offer.url)) + } + return .success(offer) + } + + /// The host route's admission: the page loads from the host's network, + /// so every web address is the host's view — `localhost` stays the + /// host's loopback (spelled `localhost`, no rewrite) and the device's + /// LAN is unreachable by construction. Only the scheme gate applies. + static func admitViaHost(_ input: String, host: Host) -> Result { + // The typed-address path rewrites loopback to the host record's + // address; a record whose address IS loopback keeps it as such. + var asSeenByHost = host + asSeenByHost.hostname = "localhost" + guard let offer = ViewportOffer.fromTypedInput(input, host: asSeenByHost) else { + return .failure(.badRequest("'\(input)' is not an http(s) address.")) + } + return .success(offer) + } + + /// The port a loopback web URL names (default 80/443), or nil when the + /// URL is not loopback — the host route forwards exactly these. + static func loopbackPort(_ url: URL) -> Int? { + guard ViewportReach.classify(url) == .remoteLoopback, + let scheme = url.scheme?.lowercased() + else { return nil } + return url.port ?? (scheme == "https" ? 443 : 80) + } + + /// The per-navigation verdict for a URL already formed (link clicks, + /// redirects, `location =`). Non-web schemes are the viewport gate's + /// business and pass through here. + static func admits(_ url: URL, host: Host) -> Bool { + guard let reach = ViewportReach.classify(url) else { return true } + switch reach { + case .internet: + return true + case .lan, .remoteLoopback: + // Loopback here is the DEVICE's own — admission already + // rewrote the host's loopback to its address. + return isThisHost(url, host: host) + } + } + + static func blockedError(_ url: URL) -> AgentBrowserError { + .blocked( + "\(url.host() ?? url.absoluteString) is a private address that is not this host — " + + "agent tabs reach the internet and this machine only." + ) + } + + private static func isThisHost(_ url: URL, host: Host) -> Bool { + guard let target = url.host()?.lowercased() else { return false } + let own = host.hostname.trimmingCharacters(in: .whitespaces).lowercased() + return !own.isEmpty && (target == own || "[\(target)]" == own || target == "[\(own)]") + } + + /// WebKit content-blocker rules: block private and loopback authorities + /// for every resource type, then let this host back in. WebKit's + /// url-filter has no alternation, hence one rule per range. + static func contentRuleListJSON(host: Host) -> String { + let authority = "^[a-z][a-z0-9+.-]*://" + let privateAuthorities = [ + #"10\."#, + #"192\.168\."#, + #"172\.1[6-9]\."#, + #"172\.2[0-9]\."#, + #"172\.3[01]\."#, + #"169\.254\."#, + #"127\."#, + #"0\.0\.0\.0"#, + #"localhost\.?[:/]"#, + #"[^/:]*\.localhost\.?[:/]"#, + #"[^/:]*\.local\.?[:/]"#, + // IPv6 literals: the ranges that matter (ULA, link-local, + // loopback, mapped) cannot be told apart without alternation; + // an agent has no need for a bracketed literal on the internet. + #"\["#, + // A single-label name resolves through the LAN's search domains. + #"[^/:.]+\.?[:/]"#, + ] + var rules: [[String: Any]] = privateAuthorities.map { pattern in + ["trigger": ["url-filter": authority + pattern], "action": ["type": "block"]] + } + var own = host.hostname.trimmingCharacters(in: .whitespaces).lowercased() + // URLs bracket an IPv6 literal; a host record may not. + if own.contains(":"), !own.hasPrefix("[") { own = "[\(own)]" } + if !own.isEmpty { + rules.append([ + "trigger": ["url-filter": authority + escapeRegex(own) + "[:/]"], + "action": ["type": "ignore-previous-rules"], + ]) + } + let options: JSONSerialization.WritingOptions = [.sortedKeys, .withoutEscapingSlashes] + let data = (try? JSONSerialization.data(withJSONObject: rules, options: options)) ?? Data("[]".utf8) + return String(decoding: data, as: UTF8.self) + } + + /// The host route's content rules. Pages load through the host, but a + /// device never proxies loopback — so `localhost` reaches the PHONE, + /// where other apps may listen. Every loopback authority is blocked + /// except the ports forwarded to the host. Recompiled as forwards + /// change; WebKit's url-filter has no alternation, hence one rule per + /// spelling and scheme. + static func loopbackRuleListJSON(forwardedPorts: [Int]) -> String { + let anyScheme = "^[a-z][a-z0-9+.-]*://" + let loopbackHosts = [ + #"localhost"#, #"127\.[0-9.]+"#, #"\[::1\]"#, #"[^/:]*\.localhost"#, #"0\.0\.0\.0"#, + ] + var rules: [[String: Any]] = loopbackHosts.map { + ["trigger": ["url-filter": anyScheme + $0 + "\\.?[:/]"], "action": ["type": "block"]] + } + // Only the spellings a forward listens on (127.0.0.1 and ::1, which + // `localhost` and `*.localhost` resolve to). + let forwardedHosts = [#"localhost"#, #"127\.0\.0\.1"#, #"\[::1\]"#, #"[^/:]*\.localhost"#] + for port in Set(forwardedPorts).sorted() { + var prefixes = forwardedHosts.map { anyScheme + $0 + ":\(port)/" } + let defaults: [Int: [String]] = [80: ["http", "ws"], 443: ["https", "wss"]] + for scheme in defaults[port] ?? [] { + prefixes += forwardedHosts.map { "^\(scheme)://" + $0 + "/" } + } + rules += prefixes.map { ["trigger": ["url-filter": $0], "action": ["type": "ignore-previous-rules"]] } + } + let options: JSONSerialization.WritingOptions = [.sortedKeys, .withoutEscapingSlashes] + let data = (try? JSONSerialization.data(withJSONObject: rules, options: options)) ?? Data("[]".utf8) + return String(decoding: data, as: UTF8.self) + } + + static func escapeRegex(_ text: String) -> String { + var out = "" + for character in text { + if "\\^$.|?*+()[]{}".contains(character) { out.append("\\") } + out.append(character) + } + return out + } +} diff --git a/Multiplex/Models/AgentBrowser/AgentBrowserScript.swift b/Multiplex/Models/AgentBrowser/AgentBrowserScript.swift new file mode 100644 index 00000000..dacc80ba --- /dev/null +++ b/Multiplex/Models/AgentBrowser/AgentBrowserScript.swift @@ -0,0 +1,621 @@ +import Foundation + +/// The JavaScript an agent tab carries. Pure strings. +/// +/// Two scripts, two worlds: +/// - `helper` runs in an isolated `WKContentWorld`: it shares the DOM with +/// the page but none of its globals, so the page can neither see nor call +/// it, and no message handler exists in any world — the viewport's "no +/// bridge into the app" rule holds for the page. Every agent action +/// (`snapshot`, `click`, `fill`, …) is a call into `__mpx.call`. +/// - `consoleHook` runs in the page world, because console calls happen +/// there. It only re-dispatches each message as a DOM event the helper +/// buffers; it gives the page nothing it did not already have. +/// +/// Answers are JSON strings (`{"ok":…}` or `{"error":{"code","message"}}`) +/// so the driver never depends on WebKit's JS→ObjC value bridging and +/// exceptions keep their code. +enum AgentBrowserScript { + /// The isolated world every agent helper call runs in. + static let worldName = "multiplex-agent" + + static func helper(consoleEvent: String) -> String { + helperSource.replacingOccurrences(of: "__MPX_EVENT__", with: consoleEvent) + } + + static func consoleHook(consoleEvent: String) -> String { + consoleHookSource.replacingOccurrences(of: "__MPX_EVENT__", with: consoleEvent) + } + + /// The body `callAsyncJavaScript` runs in the helper world; `name` and + /// `argsJSON` arrive as arguments. + static let callBody = """ + if (!window.__mpx) { return null; } + const out = JSON.stringify(window.__mpx.call(name, JSON.parse(argsJSON))); + if (out.length > \(maxAnswerChars)) { + return JSON.stringify({ error: { code: "too_large", message: `The answer was ${out.length} characters.` } }); + } + return out; + """ + + /// Answers longer than this never leave the page: a page can make any + /// value huge, and the app would hold it whole. + static let maxAnswerChars = 4_000_000 + + /// Bodies for the agent's own `eval`, in the PAGE world (where the app's + /// globals live). Tried as an expression first, then as statements, so + /// both `document.title` and `const a = 1; return a + 1` work. + static func evalBodies(_ source: String) -> [String] { + let finish = """ + if (__v === undefined) { return JSON.stringify({ undefined: true }); } + let __s; + try { __s = JSON.stringify({ value: __v }); } catch (e) { __s = JSON.stringify({ value: String(__v) }); } + if (__s.length > \(maxAnswerChars)) { return JSON.stringify({ tooLarge: __s.length }); } + return __s; + """ + return [ + "const __v = await (\n\(source)\n);\n\(finish)", + "const __v = await (async () => {\n\(source)\n})();\n\(finish)", + ] + } + + /// Removes the WebRTC constructors from the page world: peer + /// connections send UDP from the device to any address the page names. + static let noWebRTC = #""" + (() => { + for (const name of ["RTCPeerConnection", "webkitRTCPeerConnection", "RTCDataChannel"]) { + try { Object.defineProperty(window, name, { value: undefined, writable: false, configurable: false }); } + catch (_) { try { delete window[name]; } catch (_) {} } + } + })(); + """# + + private static let consoleHookSource = #""" + (() => { + const EVENT = "__MPX_EVENT__"; + for (const level of ["log", "info", "warn", "error", "debug"]) { + const original = console[level]; + if (typeof original !== "function") continue; + console[level] = function (...args) { + try { + const text = args.map((a) => { + if (typeof a === "string") return a; + if (a instanceof Error) return a.stack || String(a); + try { return JSON.stringify(a); } catch (_) { return String(a); } + }).join(" "); + document.dispatchEvent(new CustomEvent(EVENT, { + detail: JSON.stringify({ level, text: text.slice(0, 4000) }), + })); + } catch (_) {} + return original.apply(this, args); + }; + } + })(); + """# + + private static let helperSource = #""" + (() => { + if (window.__mpx) return; + const EVENT = "__MPX_EVENT__"; + // The page can forge these events (the name is not a secret), so + // everything recorded is page-authored: levels are allowlisted, + // text is cut, and the buffer has a character budget. + const MAX_CONSOLE = 500; + const MAX_CONSOLE_CHARS = 400000; + const LEVELS = new Set(["log", "info", "warn", "error", "debug"]); + const consoleBuffer = []; + let consoleChars = 0; + let refs = new Map(); + + function record(level, text) { + const entry = { + level: LEVELS.has(level) ? level : "log", + text: String(text).slice(0, 4000), + ts: Date.now(), + }; + consoleBuffer.push(entry); + consoleChars += entry.text.length; + while (consoleBuffer.length > MAX_CONSOLE || consoleChars > MAX_CONSOLE_CHARS) { + consoleChars -= consoleBuffer.shift().text.length; + } + } + document.addEventListener(EVENT, (e) => { + if (typeof e.detail !== "string" || e.detail.length > 8192) return; + try { + const d = JSON.parse(e.detail); + if (d && typeof d.level === "string" && typeof d.text === "string") record(d.level, d.text); + } catch (_) {} + }, true); + window.addEventListener("error", (e) => { + const t = e.target; + if (t && t !== window && (t.src || t.href)) { + record("error", `Failed to load ${t.tagName.toLowerCase()} ${t.src || t.href}`); + } else { + record("error", (e.message || "Uncaught error") + (e.filename ? ` (${e.filename}:${e.lineno})` : "")); + } + }, true); + window.addEventListener("unhandledrejection", (e) => { + const r = e.reason; + record("error", "Unhandled rejection: " + (r && r.stack ? r.stack : String(r))); + }); + + function fail(code, message) { const e = new Error(message); e.mpxCode = code; return e; } + function clean(s, max = 100) { + s = String(s == null ? "" : s).replace(/\s+/g, " ").trim(); + return s.length > max ? s.slice(0, max - 1) + "…" : s; + } + const q = (s) => JSON.stringify(s); + + function isHidden(el) { + if (el.hidden || el.getAttribute("aria-hidden") === "true") return true; + if (typeof el.checkVisibility === "function") { + return !el.checkVisibility({ visibilityProperty: true }); + } + const s = getComputedStyle(el); + return s.display === "none" || s.visibility === "hidden"; + } + + function roleOf(el) { + const explicit = el.getAttribute("role"); + if (explicit) return explicit.trim().split(/\s+/)[0]; + switch (el.tagName) { + case "A": return el.hasAttribute("href") ? "link" : null; + case "BUTTON": case "SUMMARY": return "button"; + case "SELECT": return el.multiple || el.size > 1 ? "listbox" : "combobox"; + case "TEXTAREA": return "textbox"; + case "INPUT": { + const t = (el.type || "text").toLowerCase(); + if (t === "hidden") return null; + if (["button", "submit", "reset", "image"].includes(t)) return "button"; + if (t === "checkbox" || t === "radio") return t; + if (t === "range") return "slider"; + if (t === "file") return "file"; + if (t === "search") return "searchbox"; + return "textbox"; + } + case "H1": case "H2": case "H3": case "H4": case "H5": case "H6": return "heading"; + case "IMG": return el.getAttribute("alt") ? "img" : null; + case "NAV": return "navigation"; + case "MAIN": return "main"; + case "ASIDE": return "complementary"; + case "FORM": return "form"; + case "DIALOG": return "dialog"; + case "UL": case "OL": return "list"; + case "TABLE": return "table"; + case "FIELDSET": return "group"; + case "IFRAME": return "iframe"; + } + if (el.isContentEditable && el.hasAttribute("contenteditable")) return "textbox"; + return null; + } + + const INTERACTIVE = new Set([ + "link", "button", "combobox", "listbox", "textbox", "searchbox", "checkbox", "radio", + "slider", "file", "switch", "tab", "menuitem", "menuitemcheckbox", "menuitemradio", + "option", "treeitem", "spinbutton", + ]); + const CONTAINERS = new Set([ + "navigation", "main", "complementary", "form", "dialog", "alertdialog", "list", "table", + "group", "menu", "menubar", "tablist", "tree", "region", "banner", "contentinfo", "toolbar", + ]); + const DESCEND = "a[href],button,input,select,textarea,summary,img[alt],iframe,nav,main,aside," + + "form,dialog,ul,ol,table,fieldset,h1,h2,h3,h4,h5,h6,[role],[contenteditable],[tabindex],[onclick]"; + const SKIP = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "HEAD", "META", "LINK"]); + + function nameOf(el) { + const aria = el.getAttribute("aria-label"); + if (aria && aria.trim()) return clean(aria); + const by = el.getAttribute("aria-labelledby"); + if (by) { + const t = by.split(/\s+/).map((id) => document.getElementById(id)).filter(Boolean) + .map((n) => n.innerText || n.textContent).join(" "); + if (t.trim()) return clean(t); + } + const tag = el.tagName; + if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") { + if (el.labels && el.labels.length) { + const t = Array.from(el.labels).map((l) => l.innerText).join(" "); + if (t.trim()) return clean(t); + } + if (["button", "submit", "reset"].includes(el.type)) return clean(el.value || el.type); + if (el.type === "image") return clean(el.alt); + return clean(el.getAttribute("placeholder") || el.getAttribute("title") || el.getAttribute("name")); + } + if (tag === "IMG") return clean(el.getAttribute("alt")); + const text = el.innerText; + if (text && text.trim()) return clean(text); + const img = el.querySelector("img[alt]"); + if (img) return clean(img.alt); + const svgTitle = el.querySelector("svg title"); + if (svgTitle) return clean(svgTitle.textContent); + return clean(el.getAttribute("title")); + } + + function describe(el) { + const role = roleOf(el) || el.tagName.toLowerCase(); + const name = nameOf(el); + return name ? `${role} ${q(name)}` : role; + } + + function isPointer(el) { + if (getComputedStyle(el).cursor !== "pointer") return false; + const parent = el.parentElement; + return !parent || getComputedStyle(parent).cursor !== "pointer"; + } + + function states(el, role) { + const out = []; + if (el.disabled || el.getAttribute("aria-disabled") === "true") out.push("disabled"); + if (el.checked || el.getAttribute("aria-checked") === "true") out.push("checked"); + if (el.getAttribute("aria-selected") === "true") out.push("selected"); + const expanded = el.getAttribute("aria-expanded"); + if (expanded) out.push(expanded === "true" ? "expanded" : "collapsed"); + if (el.required) out.push("required"); + if (document.activeElement === el) out.push("focused"); + return out; + } + + function valueOf(el, role) { + if (el.tagName === "SELECT") { + const o = el.options[el.selectedIndex]; + return o ? clean(o.text, 60) : ""; + } + if (role === "textbox" || role === "searchbox" || role === "spinbutton" || role === "slider") { + if (el.isContentEditable) return clean(el.innerText, 80); + if (el.type === "password") return el.value ? "••••" : ""; + return "value" in el ? clean(el.value, 80) : null; + } + return null; + } + + function hrefOf(el) { + const raw = el.getAttribute("href"); + if (!raw || raw.startsWith("javascript:")) return null; + try { + const u = new URL(raw, location.href); + const s = u.origin === location.origin ? u.pathname + u.search + u.hash : u.href; + return clean(s, 80); + } catch (_) { return null; } + } + + function snapshot(full) { + refs = new Map(); + let next = 1; + const lines = []; + const limit = full ? 20000 : 600; + let truncated = false; + const emit = (depth, text) => { + if (lines.length >= limit) { truncated = true; return; } + lines.push(" ".repeat(depth) + "- " + text); + }; + const ref = (el) => { const id = "e" + next++; refs.set(id, el); return id; }; + + function interactive(el, role, depth) { + const name = nameOf(el); + let line = role + (name ? " " + q(name) : "") + ` [ref=${ref(el)}]`; + const st = states(el, role); + if (st.length) line += " [" + st.join(", ") + "]"; + const value = valueOf(el, role); + if (value) line += " = " + q(value); + if (role === "link") { const h = hrefOf(el); if (h) line += " → " + h; } + emit(depth, line); + } + + function visitNodes(nodes, depth) { + for (const node of nodes) { + if (truncated) return; + if (node.nodeType === 3) { + const t = clean(node.textContent, 300); + if (t) emit(depth, "text: " + t); + } else if (node.nodeType === 1) { + visit(node, depth); + } + } + } + + function children(el) { + return el.shadowRoot ? el.shadowRoot.childNodes : el.childNodes; + } + + function visit(el, depth) { + if (SKIP.has(el.tagName)) return; + if (el.tagName === "SLOT") { visitNodes(el.assignedNodes({ flatten: true }), depth); return; } + if (isHidden(el)) return; + const role = roleOf(el); + if (role && INTERACTIVE.has(role)) { interactive(el, role, depth); return; } + if (role === "heading") { + const level = Number(el.getAttribute("aria-level") || el.tagName.slice(1)) || 2; + emit(depth, `heading ${q(nameOf(el))} [level=${level}]`); + return; + } + if (role === "img") { emit(depth, "img " + q(nameOf(el))); return; } + if (role === "iframe") { emit(depth, "iframe " + q(clean(el.title || el.src, 80))); return; } + if (role && CONTAINERS.has(role)) { + const label = clean(el.getAttribute("aria-label")); + emit(depth, role + (label ? " " + q(label) : "") + ":"); + visitNodes(children(el), depth + 1); + return; + } + if (!el.shadowRoot && !el.querySelector(DESCEND)) { + if (isPointer(el)) { interactive(el, "clickable", depth); return; } + const t = clean(el.innerText, 300); + if (t) emit(depth, "text: " + t); + return; + } + if (role === null && isPointer(el) && !el.querySelector("a[href],button,input,select,textarea")) { + interactive(el, "clickable", depth); + return; + } + visitNodes(children(el), depth); + } + + if (document.body) visit(document.body, 0); + return { text: lines.join("\n"), truncated, refs: next - 1 }; + } + + function findByText(text) { + const needle = text.toLowerCase(); + const candidates = document.querySelectorAll( + "a[href],button,input,select,textarea,summary,label,[role],[tabindex],[onclick]"); + for (const el of candidates) { + if (!isHidden(el) && nameOf(el).toLowerCase().includes(needle)) return el; + } + if (!document.body) return null; + const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT); + while (walker.nextNode()) { + const parent = walker.currentNode.parentElement; + if (parent && walker.currentNode.textContent.toLowerCase().includes(needle) && !isHidden(parent)) { + return parent; + } + } + return null; + } + + function resolve(target) { + target = String(target || "").trim(); + if (/^e\d+$/.test(target)) { + const el = refs.get(target); + if (!el) throw fail("stale_ref", `No ${target} in the last snapshot — take a new snapshot.`); + if (!el.isConnected) throw fail("stale_ref", `${target} is gone from the page — take a new snapshot.`); + return el; + } + if (target.startsWith("text=")) { + const el = findByText(target.slice(5)); + if (!el) throw fail("not_found", `No visible element with text ${q(target.slice(5))}.`); + return el; + } + let el; + try { el = document.querySelector(target); } catch (_) { + throw fail("bad_request", `${q(target)} is not a ref (e12), text=…, or a CSS selector.`); + } + if (!el) throw fail("not_found", `Nothing matches ${q(target)}.`); + return el; + } + + function center(el) { + el.scrollIntoView({ block: "center", inline: "center", behavior: "instant" }); + const r = el.getBoundingClientRect(); + return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; + } + + function click(target) { + const el = resolve(target); + const { x, y } = center(el); + const top = document.elementFromPoint(x, y); + const opts = { + bubbles: true, cancelable: true, composed: true, clientX: x, clientY: y, view: window, button: 0, + }; + const pointer = (type) => { + const init = { ...opts, pointerId: 1, pointerType: "mouse", isPrimary: true }; + try { el.dispatchEvent(new PointerEvent(type, init)); } catch (_) {} + }; + pointer("pointerover"); + el.dispatchEvent(new MouseEvent("mouseover", opts)); + pointer("pointerdown"); + el.dispatchEvent(new MouseEvent("mousedown", opts)); + if (typeof el.focus === "function") el.focus({ preventScroll: true }); + pointer("pointerup"); + el.dispatchEvent(new MouseEvent("mouseup", opts)); + el.click(); + const out = { clicked: describe(el) }; + if (top && top !== el && !el.contains(top) && !top.contains(el)) out.coveredBy = describe(top); + return out; + } + + function inputEvent(text) { + return new InputEvent("input", { bubbles: true, composed: true, inputType: "insertText", data: text }); + } + + function isEditable(el) { + return el && (el.isContentEditable || el.tagName === "TEXTAREA" + || (el.tagName === "INPUT" && roleOf(el) !== null && ["textbox", "searchbox"].includes(roleOf(el)))); + } + + function insert(el, text) { + let ok = false; + try { + ok = text === "" ? document.execCommand("delete") : document.execCommand("insertText", false, text); + } catch (_) {} + return ok; + } + + function selectOption(el, value) { + if (el.tagName !== "SELECT") { + throw fail("bad_request", `${describe(el)} is not a