SPB Git

Repository Public License

AGENT.md 20.8 KB 319 lines markdown

1# The browsing agent (AgentRuntime)23ORIX Navigator works fully without AI. `AgentRuntime` is used only after the user has configured a provider4(`docs/AI_PROVIDERS.md`), opened the agent panel, chosen what to share and pressed Start.56Module: `Packages/NavigatorKit/Sources/AgentRuntime` (imports Foundation, `NavigatorCore`, `ProviderKit`,7`Persistence`, `Diagnostics`; never WebKit, `WebRuntime` or SwiftUI). Security design: `docs/AGENT_SECURITY.md`.89> **Not verified with a real model.** No API key was available. Every test drives the runtime with a scripted10> provider and a scripted fake browser; no request was sent to any model, and no real page was driven. How a real11> model behaves with these tools, prompts and error messages is unknown.1213## Architecture1415```16 UI (NavigatorUI)                         AgentRuntime                               ProviderKit17 ─────────────────                        ─────────────                              ───────────18 agent panel  ── AgentSessionConfiguration ─▶ AgentSession (actor) ── ChatRequest ─▶ ChatProvider.stream19      ▲                                        │  loop: model → tool calls → results20      │ AsyncStream<AgentEvent>                │  budget · permissions · confirmations21      │◀───────────────────────────────────────┤  envelope · redaction · citations22 AgentConfirmationDelegate ◀── confirm / handOff23 BrowserAgentHost (over WebEngine) ◀── navigate / read / click …                    Persistence24                                               └── AgentRun after every step ─────▶ database.agentRuns25```2627One actor, `AgentSession`, owns a run. There are no sub-agents: the roles are phases of the one loop.2829| Phase (`AgentPhase`) | When | What the orchestrator does |30|---|---|---|31| `research` | navigate, search, read, inspect, click, scroll, type, submit, tabs | executes tool calls |32| `extraction` | extract, compare, screenshot, download | executes tool calls |33| `synthesis` | the model calls `finish`, or one step is left | with one step left only `finish` is offered, with a runtime notice |34| `verification` | inside `finish` | checks the answer against the sources of the run, deterministically |3536A step is one tool call (executed, refused or rejected) or one model turn that called no tool.3738### Files3940| File | Content |41|---|---|42| `JSONSchema.swift` | `SchemaValidator`: strict JSON Schema subset |43| `AgentTools.swift` | `AgentToolCatalog`: the 15 tools and their declared properties |44| `BrowserAgentHost.swift` | the host protocol and its value types |45| `AgentPolicy.swift` | `AgentLimits`, `AgentPermissionPolicy`, `DomainPolicy`, `AgentURL`, `AgentClock` |46| `AgentClassifiers.swift` | `SensitiveActionClassifier`, `SecretFieldClassifier`, `WallDetector`, `InjectionScanner` |47| `ExfiltrationGuard.swift` | outbound URL / text checks |48| `DataEnvelope.swift` | `DataEnvelope` (nonce delimiters), `ResultSanitizer` (redaction, bounds) |49| `Citations.swift` | source registry, `AnswerVerifier`, `VerifiedAnswer` |50| `TextDiff.swift` | line diff for `browser.compare` |51| `AgentEvents.swift` | `AgentEvent`, `ConfirmationRequest`, `AgentConfirmationDelegate`, hand-off types |52| `AgentSession.swift`, `AgentSession+Tools.swift` | the orchestrator and one function per tool |53| `AgentRunHistory.swift` | stored runs; interrupted runs at relaunch |54| `AssistantHelpers.swift` | tool-less helpers with a consent step |5556## Tools5758Names shown to the user and stored in `AgentStep.tool` use a dot (`browser.navigate`). On the wire the dot is an59underscore (`browser_navigate`), because Anthropic and OpenAI accept only `[A-Za-z0-9_-]` in tool names. The model60refers to tabs by small integer handles (`tab: 1`), never by identifier; a handle exists only for a tab the user61shared or the agent opened.6263| Tool | Capability | Risk | Asks the user | What leaves the device |64|---|---|---|---|---|65| `browser.navigate` | navigate | medium | if the site is off the allowed list (when the user chose "ask"), or the URL appears to carry copied data | the URL, to that site, with the profile's cookies for it |66| `browser.search` | search | medium | if the query appears to carry copied text | the query, to the user's search engine |67| `browser.read` | read | low | no | page text (redacted, hidden text excluded), to the AI provider |68| `browser.inspect` | inspect | low | no | headings, link texts and addresses, button labels, field names, to the AI provider |69| `browser.click` | interact | medium | sensitive label, submit control, or irreversible flag | whatever the page sends when clicked |70| `browser.scroll` | interact | low | no | nothing beyond what the page loads |71| `browser.type` | interact | medium | if the text appears copied; **secret fields are always refused** | the text, into the page (its scripts can read it) |72| `browser.submit_form` | submitForms | high | **always** | every field of the form, to the form's destination |73| `browser.extract` | extract | low | no | extracted values (redacted), to the AI provider |74| `browser.screenshot` | screenshot | medium | no | an image of the visible page, to the AI provider |75| `browser.compare` | read | low | no | a summary of added and removed lines, to the AI provider |76| `browser.download` | download | high | **always**; executables refused unless the user enabled them | the URL, to its site; the file stays on the device |77| `browser.create_tab` | manageTabs | medium | as `navigate` | the URL, if any |78| `browser.organize` | manageTabs | medium | when a tab shared by the user would be closed | nothing |79| `finish` | — | low | no | nothing |8081The same information is in code: `AgentToolCatalog.all` (`capability`, `risk`, `confirmation`,82`dataLeavingDevice`, `parameters`). Arguments are validated by `SchemaValidator` against `parameters` before83anything runs. The validator supports `type` (object, string, integer, number, boolean, array), `description`,84`properties`, `required`, `additionalProperties` (must be `false`), `enum`, `minimum`, `maximum`, `minLength`,85`maxLength`, `items`, `minItems`, `maxItems`. A schema using any other keyword is invalid and nothing validates86against it.8788Behaviour worth knowing:8990- `browser.read` returns at most `maxToolResultCharacters` per call with `next_cursor`; all pages of one address91  share one `source_id`.92- `browser.extract` takes exactly one of `selector`, `ref`, `fields`. Described-field extraction is done by the93  host (microdata, JSON-LD, tables, labelled values), not by a model.94- `browser.compare` takes a tab or a `source_id` on each side; the diff (longest common subsequence over lines,95  or sentences for prose, first 1 500 units per side) is computed by the runtime.96- `browser.click` looks the element up in a fresh outline at click time, so the label that is classified is the97  one on the page now. A click on a submit control is handled as `browser.submit_form`.98- `finish` may be handed back once (`maxAnswerRevisions`) with the verifier's findings; the second answer is99  checked the same way and then repaired by the runtime.100101## Events102103`AgentSession.events` is a single-consumer `AsyncStream<AgentEvent>` that ends after `.finished`.104105| Event | Meaning |106|---|---|107| `started(AgentRun)` | first event |108| `phaseChanged(AgentPhase)` | |109| `stepStarted / stepUpdated / stepFinished(AgentStep)` | steps of kind `toolCall` exist only for calls the runtime executed, refused or rejected; `thought` is model commentary; `confirmation`, `answer`, `error` are written by the runtime |110| `textDelta(String)` | model text as it streams. Commentary, never a record of something done |111| `citationAdded(Citation)` | a source was read for the first time |112| `confirmationRequested(ConfirmationRequest)` / `confirmationResolved(id:decision:)` | |113| `handoffRequested(AgentHandoffRequest)` / `handoffResolved(id:decision:)` | CAPTCHA or sign-in: the tab is the user's |114| `warning(AgentWarning)` | `injectionSuspected`, `hiddenTextOmitted`, `usageEstimated`, `costUnknown`, `contextCompacted`, `answerNotFullyVerified`, `persistenceFailed` |115| `usage(AgentUsageReport)` | after every model call |116| `finished(AgentRunResult)` | always last: final `AgentRun`, the reason in one sentence, the `VerifiedAnswer` if completed |117118Run status: `running`, `awaitingConfirmation` (also during a hand-off), then `completed`, `failed`, `cancelled`119or `budgetExhausted`. The reason is also stored as the last step of the run (`AgentRunHistory.endReason`).120121## What the UI implements122123### `BrowserAgentHost`124125```swift126public protocol BrowserAgentHost: Sendable {127    func pageInfo(tab: TabID) async throws -> AgentPageInfo128    func searchURL(for query: String) async throws -> URL129    func navigate(tab: TabID, to url: URL, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentPageInfo130    func readText(tab: TabID, mode: AgentReadMode) async throws -> AgentPageText131    func outline(tab: TabID) async throws -> AgentPageOutline132    func click(tab: TabID, ref: String, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentActionOutcome133    func type(tab: TabID, ref: String, text: String) async throws134    func submitForm(tab: TabID, ref: String, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentActionOutcome135    func scroll(tab: TabID, direction: AgentScrollDirection, pages: Double) async throws -> AgentScrollState136    func extract(tab: TabID, query: AgentExtractionQuery) async throws -> AgentExtraction137    func screenshot(tab: TabID) async throws -> AgentScreenshot138    func probeDownload(url: URL, fromTab: TabID?, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentDownloadProbe139    func download(url: URL, fromTab: TabID?, maxBytes: Int64, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentDownloadResult140    func createTab(url: URL?, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentCreatedTab141    func organize(_ operation: AgentTabOperation) async throws142}143```144145The implementation is part of the safety of the whole. It must:1461471. evaluate scripts in the agent content world (`ScriptBridge`), never in the page world;1482. call `redirectGuard` with the destination of **every** server and client redirect before it commits, and149   cancel the navigation (throw `BrowserAgentHostError.navigationBlocked`) when it returns `false`;1503. never start a download from `navigate`, `click` or `submitForm` — report `AgentActionOutcome.blockedDownload`;1514. mark every text segment and element a person could not see (`AgentTextSegment.hiddenReason`,152   `AgentElement.isHidden`, `AgentFormField.isHidden`): `display:none`, `visibility:hidden`, `aria-hidden`,153   font size under a few pixels, opacity near zero, text the colour of its background, off-screen or clipped154   boxes, comments;1555. report field kinds truthfully (`AgentFieldKind`) and pass `type` / `autocomplete` as written;1566. give elements refs that are stable for the document and fail an action whose ref no longer matches;1577. honour task cancellation promptly; stop a download above `maxBytes` and delete the partial file;1588. record history with `NavigationEntry.Transition.agent`, and use the tab's own profile.159160It must **not** grow methods to list tabs or read cookies, storage, passwords, history, files or other profiles.161162### `AgentConfirmationDelegate`163164```swift165public protocol AgentConfirmationDelegate: Sendable {166    func confirm(_ request: ConfirmationRequest) async -> ConfirmationDecision      // .approved / .denied167    func handOff(_ request: AgentHandoffRequest) async -> AgentHandoffDecision      // .userCompleted / .declined168}169```170171Both suspend until the user answers. The UI must show `ConfirmationRequest.action`, `destination`, every172`data` item (name and value; `isMasked` values are already masked) and `reasons`. If the run stops meanwhile the173call's task is cancelled and `confirmationResolved(…, .cancelled)` tells the UI to dismiss the sheet. A session174created without a delegate refuses every action that needs confirmation.175176## Starting a run177178```swift179let provider = try await registry.provider(for: providerID, space: spaceID)180let price = await registry.price(family: provider.family, model: provider.configuration.model)181let session = AgentSession(182    goal: goal, provider: provider, price: price, isGhost: profile.isGhost,183    limits: AgentLimits(budget: AgentBudget(maxSteps: 20, allowedDomains: ["example.com"])),184    policy: AgentPermissionPolicy(sharedTabs: [currentTab], capabilities: AgentPermissionPolicy.researchCapabilities),185    host: host, confirmation: confirmationUI, database: database)186Task { for await event in session.events { render(event) } }187await session.start()188// await session.stop()                 — immediate189// let result = await session.result()  — after the run ended and was saved190```191192At launch, before any session starts: `try await AgentRunHistory(database: database).markInterruptedRuns()`.193A run that was `running` or `awaitingConfirmation` when the app quit becomes `failed` with an "interrupted" step194(`AgentRunHistory.displayState(of:) == .interrupted`). There is no API to resume a run: the conversation, the195confirmations and the page state are not stored.196197## Budgets198199`AgentLimits` (= `AgentBudget` from NavigatorCore plus the limits it lacks) is copied into a `let` when the200session is created. Exceeding any limit ends the run with `budgetExhausted` and a sentence naming the limit.201202| Limit | Default | Enforced |203|---|---|---|204| `budget.maxSteps` | 20 | before every model call and every tool call |205| `budget.maxDurationSeconds` | 300 | a watchdog on the injected `AgentClock` (also while the model streams, a tool runs or a confirmation is open), and between steps |206| `budget.maxTokens` | 200 000 | cumulative input + output of all requests, after each response; a request that cannot fit is not sent |207| `budget.maxCostUSD` | 1.00 | after each response, from `CostEstimator` with the price passed in the configuration, or the cost the provider reports |208| `budget.allowedDomains` | none | every URL in tool arguments, every redirect (host callback), every final address |209| `maxTabsCreated` | 5 | `browser.create_tab` |210| `maxDownloads` / `maxDownloadBytes` | 3 / 50 MiB | `browser.download` (announced size, host cap, and the size actually written) |211| `maxToolResultCharacters` | 12 000 | every tool result |212| `maxExcerptLength` | 280 | `Citation.excerpt` |213| `maxConsecutiveInvalidCalls` | 3 | then the run fails |214| `maxContextCharacters` | 400 000 | older tool results are compacted above it |215216Stated limits of the limits:217218- **Tokens when the provider reports none** are counted from text length at 3 characters per token (higher than219  the usual 4) plus 1 500 per image; `AgentUsageReport.tokensAreEstimated` is then true and a `usageEstimated`220  warning is emitted. It is an estimate, not a measurement.221- **Cost** is an estimate (see AI_PROVIDERS.md). When no price is known, `costIsKnown` is false, a `costUnknown`222  warning is emitted and the cost limit **is not enforced**; the other limits still are.223- A response in flight is not interrupted by the token or cost limit: the limit is found exceeded when the224  response ends, so a run can overshoot by one response.225- Empty `allowedDomains` means the agent cannot navigate at all and works only with the shared tabs as they are.226227### Context compaction228229On `ProviderError.contextTooLong`, or above `maxContextCharacters`, older tool results are shortened **by230truncation** (first 600 characters, then 200, with a marker saying how much was removed); images are dropped; the231two most recent results stay whole on the first pass. No model is asked to summarise. Sources stay in the232registry, so citations and quote checks are unaffected. If nothing is left to shorten the run fails with a clear233reason.234235## Citations and the answer check236237`browser.read`, `browser.extract` and the tab sides of `browser.compare` register a source: URL, title,238access date (from the clock), and an excerpt of at most `maxExcerptLength` characters. Ids are integers handed239out by the registry; the same address keeps its id. The model cites as `[n]`.240241`finish` runs `AnswerVerifier` (no model involved):2422431. the answer is split into sentences;2442. a sentence is a claim unless it is a question, a heading, shorter than three words, or says nothing was found;2453. a claim must carry at least one id that exists in the registry of **this run**; ids that do not exist are246   removed from the text;2474. quoted text of 12 characters or more must appear (case- and space-insensitively) in a cited source;2485. failing sentences are marked `[uncited]` / `[quote not found in the cited source]`, or removed when the policy249   is `.drop`.250251The result is a `VerifiedAnswer` (`text`, `sentences` with their status, `citations` actually used). This proves252that each kept claim points at something that was read and that quotations are real. **It does not prove the253source supports the claim.** A final answer that describes actions ("I grouped your tabs") has no source and is254marked; what the agent did is in the step list.255256## What is sent to the provider257258Per request: the fixed system prompt (rules and the run's nonce), the user's goal with the list of tab handles,259allowed sites and limits, the model's own earlier turns, and tool results: page text, outlines, extracted260records, diff summaries and screenshots of tabs the user shared or the agent opened — after redaction, without261hidden text, bounded in size, each wrapped in the data envelope. Plus the tool definitions.262263Never sent: cookies, website storage, saved passwords, Keychain items, history, bookmarks, downloads, local264files, other profiles, tabs that were not shared, values of password / card / one-time-code fields, the API key265(ProviderKit adds it as a header).266267A screenshot is an image: whatever is displayed in it is sent, and it cannot be redacted.268269## Private windows270271`AgentSessionConfiguration.isGhost` removes the storage sink at construction: no code path can save the run. The272run lives in the session and in the events; it is gone when the session is released. The model provider still273receives what a normal run would send — a private window does not make a cloud model private; the UI should say so.274275## Assistant helpers (no tools)276277`AssistantHelpers` serves other modules: `summarize(text:title:)`, `explain(selection:context:)`,278`translate(selection:to:)`, `compare(_:_:)`, `extractFields(from:fields:)` (JSON for Lens), each returning279`AsyncThrowingStream<AssistantEvent, Error>` (`textDelta`, `warning`, `usage`, `structured`, `finished`).280281Consent is part of the signature: every call needs a `DisclosureAcknowledgement`, which only282`acknowledge(_:remember:)` and `standingAcknowledgement()` can produce.283284```swift285let helpers = AssistantHelpers(provider: provider, consent: consentStore)286let task = AssistantTask.summarize(text: readerText, title: title)287let acknowledgement: DisclosureAcknowledgement288if let standing = await helpers.standingAcknowledgement() { acknowledgement = standing }289else {290    let disclosure = helpers.disclosure(for: task)          // provider, model, each item with its size and a preview291    guard await ui.showConsent(disclosure) else { return }  // the UI's sheet292    acknowledgement = await helpers.acknowledge(disclosure)293}294for try await event in helpers.run(task, acknowledgement: acknowledgement) { … }295```296297`AssistantConsentStore` remembers approvals per provider and Orbit space; `InMemoryAssistantConsentStore` is298provided, the app persists its own (and uses a fresh in-memory one for a private window). The text is redacted,299cut to `maxInputCharacters` (the disclosure says how much is left out), wrapped in the same nonce envelope and300described to the model as data. No tool is offered, so text that tries to instruct the model can at worst change301the wording of the answer. `extractFields` accepts only the requested keys with scalar values.302303## Tests304305`swift test --disable-keychain --scratch-path build/spm-agent --filter AgentRuntimeTests` — 138 tests in 16306suites (Swift Testing), all with `ScriptedProvider`, `FakeHost`, `ManualClock`, `ScriptedDelegate`307(`Tests/AgentRuntimeTests/Support.swift`). No network, no model, no WebKit.308309## Not verified310311- Anything with a real model or a real page (see the note at the top). In particular: whether models call these312  tools sensibly, whether the revision message leads to better answers, whether the last-step "only `finish`"313  turn works on every provider, and tool-name acceptance by each provider.314- `BrowserAgentHost` has no production implementation yet; the contract above is what the runtime assumes.315- The on-device Apple model cannot call tools (AI_PROVIDERS.md), so it can serve the helpers but not the agent.316- iOS: the target compiles for iOS (`xcodebuild -scheme AgentRuntime -destination 'generic/platform=iOS'`); the317  tests ran on macOS only.318- Long runs, real latency, and memory use with large pages were not measured.319
Files main
Menu

Theme