diff --git a/AGENTS.md b/AGENTS.md index 934aae63..b351335d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -90,7 +90,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, the Rex adaptation (probe, attach, panes, mint), 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 17995492..ce072180 100644 --- a/Multiplex/Localizable.xcstrings +++ b/Multiplex/Localizable.xcstrings @@ -464,6 +464,22 @@ } } }, + "%@ closed the shell before mpx answered. Try again, or run `mpx skill install` there yourself." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "mpxが応答する前に%@がシェルを閉じました。もう一度試すか、そのホストで`mpx skill install`を自分で実行してください。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "%@ 在 mpx 回應前就關閉了 shell。請再試一次,或自行在該主機上執行 `mpx skill install`。" + } + } + } + }, "%@ connected" : { "localizations" : { "ja" : { @@ -1670,6 +1686,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). INSTALL SKILL teaches them how: it runs `mpx skill install` on this host. 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" : "needs_review", + "value" : "Multiplexが開いている間、このホストのエージェントは`mpx browser`でターミナルの横にWebページを開き、読み取り・クリック・入力ができます(mpx 0.2以降が必要)。INSTALL SKILLを押すと、このホストで`mpx skill install`が実行され、エージェントに使い方を教えられます。エージェントのタブはSSH経由でこのホストを通して読み込まれるため、見えるのはホストのネットワークだけで、あなたのデバイスのネットワークには届きません。独自のCookieを持ち、あなた自身のタブは見えません。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "Multiplex 開啟時,這部主機上的 Agent 可以用 `mpx browser` 在終端機旁開啟網頁,並讀取、點按與輸入內容(需要 mpx 0.2 以上)。INSTALL SKILL 會教它們如何使用:它會在這部主機上執行 `mpx skill install`。Agent 標籤頁經由 SSH 透過這部主機載入,只看得到主機的網路,碰不到你裝置所在的網路;它們有自己的 Cookie,也看不到你自己的標籤頁。" + } + } + } + }, "A Rex tile opens the window its session is showing, with its panes. New Rex sessions need Rex already running on the host, so Rex is never the default." : { "localizations" : { "ja" : { @@ -7908,6 +8004,22 @@ } } }, + "Install the agent skill on this host" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "このホストにエージェントスキルをインストール" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "在這部主機上安裝 Agent 技能" + } + } + } + }, "Install guide" : { "localizations" : { "ja" : { @@ -8680,6 +8792,82 @@ } } }, + "mpx couldn't write the skill into %@: %@" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "mpx couldn't write the skill into %1$@: %2$@" + } + }, + "ja" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "mpxはスキルを%1$@に書き込めませんでした:%2$@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "mpx 無法將技能寫入 %1$@:%2$@" + } + } + } + }, + "mpx wasn't found on %@. Install it there (brew install multiplex-term/tap/mpx), then try again." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "%@にmpxが見つかりません。そのホストにインストールして(brew install multiplex-term/tap/mpx)から、もう一度お試しください。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "在 %@ 上找不到 mpx。請在該主機上安裝(brew install multiplex-term/tap/mpx),然後再試一次。" + } + } + } + }, + "mpx on %@ couldn't install the skill: %@" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "mpx on %1$@ couldn't install the skill: %2$@" + } + }, + "ja" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "%1$@のmpxはスキルをインストールできませんでした:%2$@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "%1$@ 上的 mpx 無法安裝技能:%2$@" + } + } + } + }, + "mpx on %@ reported nothing installed. Try again." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "%@のmpxは何もインストールしなかったと報告しました。もう一度お試しください。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "%@ 上的 mpx 回報沒有安裝任何項目。請再試一次。" + } + } + } + }, "Magenta" : { "localizations" : { "ja" : { @@ -9996,6 +10184,28 @@ } } }, + "No answer from mpx on %@ after %lld seconds. Try again, or run `mpx skill install` there yourself." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "No answer from mpx on %1$@ after %2$lld seconds. Try again, or run `mpx skill install` there yourself." + } + }, + "ja" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "%1$@のmpxから%2$lld秒経っても応答がありません。もう一度試すか、そのホストで`mpx skill install`を自分で実行してください。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "%1$@ 上的 mpx 在 %2$lld 秒內沒有回應。請再試一次,或自行在該主機上執行 `mpx skill install`。" + } + } + } + }, "NO COMMANDS" : { "localizations" : { "ja" : { @@ -16065,6 +16275,38 @@ } } }, + "The multiplex skill is on %@. Agents started from now on can use it." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "multiplexスキルを%@にインストールしました。これ以降に起動するエージェントが利用できます。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "multiplex 技能已安裝到 %@。之後啟動的 Agent 都能使用。" + } + } + } + }, + "The mpx on %@ is too old to install the skill. Update it to 0.2 or later, then try again." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "%@のmpxは古すぎて、スキルをインストールできません。0.2以降に更新してから、もう一度お試しください。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "needs_review", + "value" : "%@ 上的 mpx 版本太舊,無法安裝技能。請更新到 0.2 以上,然後再試一次。" + } + } + } + }, "The machine declined the bind." : { "localizations" : { "ja" : { diff --git a/Multiplex/Models/AgentBrowser/AgentBrowserAddressPolicy.swift b/Multiplex/Models/AgentBrowser/AgentBrowserAddressPolicy.swift new file mode 100644 index 00000000..1ba68f4d --- /dev/null +++ b/Multiplex/Models/AgentBrowser/AgentBrowserAddressPolicy.swift @@ -0,0 +1,168 @@ +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"#, + // The unspecified address connects to loopback, and an + // IPv4-mapped literal names its IPv4 payload (the URL parser + // spells `[::ffff:127.0.0.1]` as `[::ffff:7f00:1]`). + #"\[::\]"#, #"\[::ffff:[0-9a-f:.]+\]"#, + ] + // Twice: bare, and behind userinfo (`http://x@127.0.0.1:9000/`), + // which puts text between the scheme and the host. No forward's + // allow rule below matches the userinfo form, so it stays blocked. + var rules: [[String: Any]] = ["", "[^/]*@"].flatMap { userinfo in + loopbackHosts.map { + ["trigger": ["url-filter": anyScheme + userinfo + $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..6aff185f --- /dev/null +++ b/Multiplex/Models/AgentBrowser/AgentBrowserScript.swift @@ -0,0 +1,636 @@ +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. + /// + /// Each body catches what the code throws and answers `{ thrown }`, so + /// the only exception WebKit reports is a body that did not compile — + /// the one case where nothing ran and the next body may be tried. A + /// `SyntaxError` thrown at RUN time (`JSON.parse` of an HTML error page) + /// used to look the same and ran the code, side effects included, twice. + 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; + """ + let thrown = "catch (__e) { return JSON.stringify({ thrown: String(__e) }); }" + return [ + "let __v;\ntry { __v = await (\n\(source)\n); } \(thrown)\n\(finish)", + "let __v;\ntry { __v = await (async () => {\n\(source)\n})(); } \(thrown)\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; + } + + // Only HTML elements have `click()`; an icon button does not. + function activate(el) { + if (typeof el.click === "function") { el.click(); return; } + const init = { bubbles: true, cancelable: true, composed: true, view: window }; + el.dispatchEvent(new MouseEvent("click", init)); + } + + 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)); + if (typeof el.click === "function") el.click(); + else el.dispatchEvent(new MouseEvent("click", opts)); + 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