SPB Git

Repository Public License

BrowserAgentHost.swift 13.1 KB 284 lines swift

1import Foundation2import NavigatorCore34/// Called by the host for the destination of every redirect **before it commits**. `false` means the navigation5/// must be cancelled. The closure is synchronous and immutable for the duration of one call.6public typealias AgentNavigationGuard = @Sendable (URL) -> Bool78public struct AgentPageInfo: Sendable, Hashable {9    public var url: URL10    public var title: String11    public var isLoading: Bool1213    public init(url: URL, title: String, isLoading: Bool = false) {14        self.url = url; self.title = title; self.isLoading = isLoading15    }16}1718/// Why a piece of text was not visible to a person looking at the page.19public enum AgentHiddenReason: String, Sendable, Hashable, Codable, CaseIterable {20    case hiddenElement, ariaHidden, tinyText, transparent, sameColorAsBackground, offScreen, clipped, comment21}2223public struct AgentTextSegment: Sendable, Hashable {24    public var text: String25    /// `nil` when the text was visible.26    public var hiddenReason: AgentHiddenReason?2728    public init(_ text: String, hiddenReason: AgentHiddenReason? = nil) { self.text = text; self.hiddenReason = hiddenReason }29}3031public enum AgentReadMode: String, Sendable, Hashable, Codable { case page, reader }3233public struct AgentPageText: Sendable, Hashable {34    public var info: AgentPageInfo35    /// The text in document order. The host must mark every segment a person could not see.36    public var segments: [AgentTextSegment]3738    public init(info: AgentPageInfo, segments: [AgentTextSegment]) { self.info = info; self.segments = segments }39}4041public struct AgentElement: Sendable, Hashable {42    public enum Role: String, Sendable, Hashable, Codable { case link, button, submit, other }4344    /// Stable for the lifetime of the document; the host must fail an action whose ref no longer matches.45    public var ref: String46    public var role: Role47    /// Visible text and accessible name.48    public var text: String49    public var href: URL?50    /// The form this control belongs to, when it is a submit control.51    public var formRef: String?52    public var isHidden: Bool53    /// The host knows this action cannot be undone (for example a `data-confirm` control, a POST link).54    public var isIrreversible: Bool55    /// Activating it starts a download (`download` attribute, attachment link).56    public var isDownload: Bool5758    public init(ref: String, role: Role, text: String, href: URL? = nil, formRef: String? = nil, isHidden: Bool = false,59                isIrreversible: Bool = false, isDownload: Bool = false) {60        self.ref = ref; self.role = role; self.text = text; self.href = href; self.formRef = formRef61        self.isHidden = isHidden; self.isIrreversible = isIrreversible; self.isDownload = isDownload62    }63}6465public enum AgentFieldKind: String, Sendable, Hashable, Codable, CaseIterable {66    case text, email, search, telephone, url, number, date, textArea, checkbox, radio, select, file, hidden67    case password, creditCardNumber, creditCardSecurityCode, creditCardExpiry, oneTimeCode68    case other6970    /// Kinds the agent may never type into and whose values never reach the model.71    public var isSecret: Bool {72        switch self {73        case .password, .creditCardNumber, .creditCardSecurityCode, .creditCardExpiry, .oneTimeCode: true74        default: false75        }76    }77}7879public struct AgentFormField: Sendable, Hashable {80    public var ref: String81    public var name: String82    public var label: String83    public var kind: AgentFieldKind84    /// The HTML `type` and `autocomplete` attributes as written, for the runtime's own secret-field check.85    public var htmlType: String86    public var autocomplete: String87    public var value: String?88    public var isHidden: Bool8990    public init(ref: String, name: String, label: String = "", kind: AgentFieldKind = .text, htmlType: String = "text",91                autocomplete: String = "", value: String? = nil, isHidden: Bool = false) {92        self.ref = ref; self.name = name; self.label = label; self.kind = kind; self.htmlType = htmlType93        self.autocomplete = autocomplete; self.value = value; self.isHidden = isHidden94    }95}9697public struct AgentForm: Sendable, Hashable {98    public var ref: String99    /// Where the form posts. `nil` means the page's own URL.100    public var action: URL?101    public var method: String102    public var fields: [AgentFormField]103    public var submitLabel: String104    public var isIrreversible: Bool105106    public init(ref: String, action: URL? = nil, method: String = "GET", fields: [AgentFormField] = [], submitLabel: String = "",107                isIrreversible: Bool = false) {108        self.ref = ref; self.action = action; self.method = method; self.fields = fields109        self.submitLabel = submitLabel; self.isIrreversible = isIrreversible110    }111}112113public struct AgentHeading: Sendable, Hashable {114    public var level: Int115    public var text: String116    public init(level: Int, text: String) { self.level = level; self.text = text }117}118119/// Something only a person may get past.120public enum AgentChallengeKind: String, Sendable, Hashable, Codable { case captcha, authentication }121122public struct AgentChallenge: Sendable, Hashable {123    public var kind: AgentChallengeKind124    public var evidence: String125    public init(kind: AgentChallengeKind, evidence: String) { self.kind = kind; self.evidence = evidence }126}127128public struct AgentPageOutline: Sendable, Hashable {129    public var info: AgentPageInfo130    public var headings: [AgentHeading]131    public var links: [AgentElement]132    public var buttons: [AgentElement]133    public var forms: [AgentForm]134    /// Challenges the host itself recognised (a known CAPTCHA frame, an HTTP 401). The runtime adds its own heuristics.135    public var challenges: [AgentChallenge]136137    public init(info: AgentPageInfo, headings: [AgentHeading] = [], links: [AgentElement] = [], buttons: [AgentElement] = [],138                forms: [AgentForm] = [], challenges: [AgentChallenge] = []) {139        self.info = info; self.headings = headings; self.links = links; self.buttons = buttons140        self.forms = forms; self.challenges = challenges141    }142}143144public struct AgentActionOutcome: Sendable, Hashable {145    public var page: AgentPageInfo146    public var didNavigate: Bool147    /// The action tried to start a download. The host never starts one from a click or a navigation: it reports148    /// the address here and the agent has to ask for `browser.download`.149    public var blockedDownload: URL?150151    public init(page: AgentPageInfo, didNavigate: Bool = false, blockedDownload: URL? = nil) {152        self.page = page; self.didNavigate = didNavigate; self.blockedDownload = blockedDownload153    }154}155156public enum AgentScrollDirection: String, Sendable, Hashable, Codable { case up, down, top, bottom }157158public struct AgentScrollState: Sendable, Hashable {159    /// 0 at the top, 1 at the bottom.160    public var position: Double161    public var atTop: Bool162    public var atBottom: Bool163    public init(position: Double, atTop: Bool, atBottom: Bool) { self.position = position; self.atTop = atTop; self.atBottom = atBottom }164}165166public struct AgentFieldRequest: Sendable, Hashable {167    public var name: String168    public var description: String169    public init(name: String, description: String = "") { self.name = name; self.description = description }170}171172public enum AgentExtractionQuery: Sendable, Hashable {173    case selector(String, maxItems: Int)174    case element(ref: String)175    /// The host's own extraction (microdata, JSON-LD, tables, labelled values) fills the described fields.176    case fields([AgentFieldRequest], maxItems: Int)177}178179public struct AgentExtraction: Sendable, Hashable {180    public var info: AgentPageInfo181    /// Visible values only: the host applies the same visibility rule as `readText`.182    public var records: [[String: String]]183    public init(info: AgentPageInfo, records: [[String: String]]) { self.info = info; self.records = records }184}185186public struct AgentScreenshot: Sendable, Hashable {187    public var info: AgentPageInfo188    public var data: Data189    public var mimeType: String190    public init(info: AgentPageInfo, data: Data, mimeType: String = "image/png") { self.info = info; self.data = data; self.mimeType = mimeType }191}192193public struct AgentDownloadProbe: Sendable, Hashable {194    /// The address after redirects.195    public var url: URL196    public var filename: String197    public var mimeType: String?198    public var expectedBytes: Int64?199    /// The host's own risk classification (DownloadEngine's `DownloadRisk`).200    public var isExecutable: Bool201202    public init(url: URL, filename: String, mimeType: String? = nil, expectedBytes: Int64? = nil, isExecutable: Bool = false) {203        self.url = url; self.filename = filename; self.mimeType = mimeType; self.expectedBytes = expectedBytes; self.isExecutable = isExecutable204    }205}206207public struct AgentDownloadResult: Sendable, Hashable {208    public var filename: String209    public var byteCount: Int64210    public init(filename: String, byteCount: Int64) { self.filename = filename; self.byteCount = byteCount }211}212213public struct AgentCreatedTab: Sendable, Hashable {214    public var id: TabID215    public var info: AgentPageInfo?216    public init(id: TabID, info: AgentPageInfo? = nil) { self.id = id; self.info = info }217}218219public enum AgentTabOperation: Sendable, Hashable {220    case group(tabs: [TabID], name: String)221    case move(tab: TabID, index: Int)222    case close(tab: TabID)223}224225public enum BrowserAgentHostError: Error, Sendable, Hashable, LocalizedError {226    case tabUnavailable227    case elementNotFound(ref: String)228    /// The navigation guard refused a destination.229    case navigationBlocked(URL)230    case navigationFailed(String)231    case downloadTooLarge232    case timeout233    case unsupported(String)234    case failed(String)235236    public var errorDescription: String? {237        switch self {238        case .tabUnavailable: "The tab is no longer available."239        case .elementNotFound(let ref): "No element matches ref “\(ref)” any more. Inspect the page again."240        case .navigationBlocked(let url): "A redirect to \(url.host() ?? "another site") is outside the sites allowed for this run and was stopped."241        case .navigationFailed(let detail): "The page could not be loaded: \(detail)"242        case .downloadTooLarge: "The file is larger than the size allowed for this run."243        case .timeout: "The page took too long."244        case .unsupported(let detail): detail245        case .failed(let detail): detail246        }247    }248}249250/// Everything the agent can do to the browser. The UI layer implements it over `WebEngine`.251///252/// The surface is the security boundary: there is deliberately **no** method to list tabs, read cookies, website253/// storage, passwords, the Keychain, history, bookmarks, downloads already on disk, local files or another profile.254/// Every method names one tab, and the runtime only ever passes tabs the user shared or the agent created.255///256/// Contract for implementers:257/// - Evaluate scripts in the agent content world, never in the page world.258/// - `redirectGuard` must be called for the destination of every server and client redirect before it commits, and259///   the navigation cancelled (throwing `navigationBlocked`) when it returns `false`.260/// - Never start a download as a side effect of `navigate`, `click` or `submitForm`; report `blockedDownload`.261/// - Mark every text segment and element a person could not see (`hiddenReason`, `isHidden`).262/// - Use `NavigationEntry.Transition.agent` for history, and the profile of the tab for cookies and permissions.263/// - Honour task cancellation: a cancelled call must stop loading and return promptly.264/// - `download` must stop and delete the partial file when more than `maxBytes` arrive.265public protocol BrowserAgentHost: Sendable {266    func pageInfo(tab: TabID) async throws -> AgentPageInfo267    /// The results URL of the user's search engine for `query`.268    func searchURL(for query: String) async throws -> URL269    func navigate(tab: TabID, to url: URL, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentPageInfo270    func readText(tab: TabID, mode: AgentReadMode) async throws -> AgentPageText271    func outline(tab: TabID) async throws -> AgentPageOutline272    func click(tab: TabID, ref: String, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentActionOutcome273    func type(tab: TabID, ref: String, text: String) async throws274    func submitForm(tab: TabID, ref: String, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentActionOutcome275    func scroll(tab: TabID, direction: AgentScrollDirection, pages: Double) async throws -> AgentScrollState276    func extract(tab: TabID, query: AgentExtractionQuery) async throws -> AgentExtraction277    func screenshot(tab: TabID) async throws -> AgentScreenshot278    /// Resolves redirects and reads the response head without saving anything.279    func probeDownload(url: URL, fromTab: TabID?, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentDownloadProbe280    func download(url: URL, fromTab: TabID?, maxBytes: Int64, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentDownloadResult281    func createTab(url: URL?, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentCreatedTab282    func organize(_ operation: AgentTabOperation) async throws283}284
Files main
Menu

Theme