SPB Git

Repository Public License

AGENT.md 20.8 KB

# The browsing agent (AgentRuntime)

ORIX Navigator works fully without AI. AgentRuntime is used only after the user has configured a provider (docs/AI_PROVIDERS.md), opened the agent panel, chosen what to share and pressed Start.

Module: Packages/NavigatorKit/Sources/AgentRuntime (imports Foundation, NavigatorCore, ProviderKit, Persistence, Diagnostics; never WebKit, WebRuntime or SwiftUI). Security design: docs/AGENT_SECURITY.md.

Not verified with a real model. No API key was available. Every test drives the runtime with a scripted provider and a scripted fake browser; no request was sent to any model, and no real page was driven. How a real model behaves with these tools, prompts and error messages is unknown.

# Architecture

text
 UI (NavigatorUI)                         AgentRuntime                               ProviderKit
 ─────────────────                        ─────────────                              ───────────
 agent panel  ── AgentSessionConfiguration ─▶ AgentSession (actor) ── ChatRequest ─▶ ChatProvider.stream
      ▲                                        │  loop: model → tool calls → results
      │ AsyncStream<AgentEvent>                │  budget · permissions · confirmations
      │◀───────────────────────────────────────┤  envelope · redaction · citations
 AgentConfirmationDelegate ◀── confirm / handOff
 BrowserAgentHost (over WebEngine) ◀── navigate / read / click …                    Persistence
                                               └── AgentRun after every step ─────▶ database.agentRuns

One actor, AgentSession, owns a run. There are no sub-agents: the roles are phases of the one loop.

Phase (AgentPhase) When What the orchestrator does
research navigate, search, read, inspect, click, scroll, type, submit, tabs executes tool calls
extraction extract, compare, screenshot, download executes tool calls
synthesis the model calls finish, or one step is left with one step left only finish is offered, with a runtime notice
verification inside finish checks the answer against the sources of the run, deterministically

A step is one tool call (executed, refused or rejected) or one model turn that called no tool.

# Files

File Content
JSONSchema.swift SchemaValidator: strict JSON Schema subset
AgentTools.swift AgentToolCatalog: the 15 tools and their declared properties
BrowserAgentHost.swift the host protocol and its value types
AgentPolicy.swift AgentLimits, AgentPermissionPolicy, DomainPolicy, AgentURL, AgentClock
AgentClassifiers.swift SensitiveActionClassifier, SecretFieldClassifier, WallDetector, InjectionScanner
ExfiltrationGuard.swift outbound URL / text checks
DataEnvelope.swift DataEnvelope (nonce delimiters), ResultSanitizer (redaction, bounds)
Citations.swift source registry, AnswerVerifier, VerifiedAnswer
TextDiff.swift line diff for browser.compare
AgentEvents.swift AgentEvent, ConfirmationRequest, AgentConfirmationDelegate, hand-off types
AgentSession.swift, AgentSession+Tools.swift the orchestrator and one function per tool
AgentRunHistory.swift stored runs; interrupted runs at relaunch
AssistantHelpers.swift tool-less helpers with a consent step

# Tools

Names shown to the user and stored in AgentStep.tool use a dot (browser.navigate). On the wire the dot is an underscore (browser_navigate), because Anthropic and OpenAI accept only [A-Za-z0-9_-] in tool names. The model refers to tabs by small integer handles (tab: 1), never by identifier; a handle exists only for a tab the user shared or the agent opened.

Tool Capability Risk Asks the user What leaves the device
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
browser.search search medium if the query appears to carry copied text the query, to the user's search engine
browser.read read low no page text (redacted, hidden text excluded), to the AI provider
browser.inspect inspect low no headings, link texts and addresses, button labels, field names, to the AI provider
browser.click interact medium sensitive label, submit control, or irreversible flag whatever the page sends when clicked
browser.scroll interact low no nothing beyond what the page loads
browser.type interact medium if the text appears copied; secret fields are always refused the text, into the page (its scripts can read it)
browser.submit_form submitForms high always every field of the form, to the form's destination
browser.extract extract low no extracted values (redacted), to the AI provider
browser.screenshot screenshot medium no an image of the visible page, to the AI provider
browser.compare read low no a summary of added and removed lines, to the AI provider
browser.download download high always; executables refused unless the user enabled them the URL, to its site; the file stays on the device
browser.create_tab manageTabs medium as navigate the URL, if any
browser.organize manageTabs medium when a tab shared by the user would be closed nothing
finish — low no nothing

The same information is in code: AgentToolCatalog.all (capability, risk, confirmation, dataLeavingDevice, parameters). Arguments are validated by SchemaValidator against parameters before anything runs. The validator supports type (object, string, integer, number, boolean, array), description, properties, required, additionalProperties (must be false), enum, minimum, maximum, minLength, maxLength, items, minItems, maxItems. A schema using any other keyword is invalid and nothing validates against it.

Behaviour worth knowing:

  • browser.read returns at most maxToolResultCharacters per call with next_cursor; all pages of one address share one source_id.
  • browser.extract takes exactly one of selector, ref, fields. Described-field extraction is done by the host (microdata, JSON-LD, tables, labelled values), not by a model.
  • browser.compare takes a tab or a source_id on each side; the diff (longest common subsequence over lines, or sentences for prose, first 1 500 units per side) is computed by the runtime.
  • browser.click looks the element up in a fresh outline at click time, so the label that is classified is the one on the page now. A click on a submit control is handled as browser.submit_form.
  • finish may be handed back once (maxAnswerRevisions) with the verifier's findings; the second answer is checked the same way and then repaired by the runtime.

# Events

AgentSession.events is a single-consumer AsyncStream<AgentEvent> that ends after .finished.

Event Meaning
started(AgentRun) first event
phaseChanged(AgentPhase)
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
textDelta(String) model text as it streams. Commentary, never a record of something done
citationAdded(Citation) a source was read for the first time
confirmationRequested(ConfirmationRequest) / confirmationResolved(id:decision:)
handoffRequested(AgentHandoffRequest) / handoffResolved(id:decision:) CAPTCHA or sign-in: the tab is the user's
warning(AgentWarning) injectionSuspected, hiddenTextOmitted, usageEstimated, costUnknown, contextCompacted, answerNotFullyVerified, persistenceFailed
usage(AgentUsageReport) after every model call
finished(AgentRunResult) always last: final AgentRun, the reason in one sentence, the VerifiedAnswer if completed

Run status: running, awaitingConfirmation (also during a hand-off), then completed, failed, cancelled or budgetExhausted. The reason is also stored as the last step of the run (AgentRunHistory.endReason).

# What the UI implements

# BrowserAgentHost

swift
public protocol BrowserAgentHost: Sendable {
    func pageInfo(tab: TabID) async throws -> AgentPageInfo
    func searchURL(for query: String) async throws -> URL
    func navigate(tab: TabID, to url: URL, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentPageInfo
    func readText(tab: TabID, mode: AgentReadMode) async throws -> AgentPageText
    func outline(tab: TabID) async throws -> AgentPageOutline
    func click(tab: TabID, ref: String, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentActionOutcome
    func type(tab: TabID, ref: String, text: String) async throws
    func submitForm(tab: TabID, ref: String, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentActionOutcome
    func scroll(tab: TabID, direction: AgentScrollDirection, pages: Double) async throws -> AgentScrollState
    func extract(tab: TabID, query: AgentExtractionQuery) async throws -> AgentExtraction
    func screenshot(tab: TabID) async throws -> AgentScreenshot
    func probeDownload(url: URL, fromTab: TabID?, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentDownloadProbe
    func download(url: URL, fromTab: TabID?, maxBytes: Int64, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentDownloadResult
    func createTab(url: URL?, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentCreatedTab
    func organize(_ operation: AgentTabOperation) async throws
}

The implementation is part of the safety of the whole. It must:

  1. evaluate scripts in the agent content world (ScriptBridge), never in the page world;
  2. call redirectGuard with the destination of every server and client redirect before it commits, and cancel the navigation (throw BrowserAgentHostError.navigationBlocked) when it returns false;
  3. never start a download from navigate, click or submitForm — report AgentActionOutcome.blockedDownload;
  4. mark every text segment and element a person could not see (AgentTextSegment.hiddenReason, AgentElement.isHidden, AgentFormField.isHidden): display:none, visibility:hidden, aria-hidden, font size under a few pixels, opacity near zero, text the colour of its background, off-screen or clipped boxes, comments;
  5. report field kinds truthfully (AgentFieldKind) and pass type / autocomplete as written;
  6. give elements refs that are stable for the document and fail an action whose ref no longer matches;
  7. honour task cancellation promptly; stop a download above maxBytes and delete the partial file;
  8. record history with NavigationEntry.Transition.agent, and use the tab's own profile.

It must not grow methods to list tabs or read cookies, storage, passwords, history, files or other profiles.

# AgentConfirmationDelegate

swift
public protocol AgentConfirmationDelegate: Sendable {
    func confirm(_ request: ConfirmationRequest) async -> ConfirmationDecision      // .approved / .denied
    func handOff(_ request: AgentHandoffRequest) async -> AgentHandoffDecision      // .userCompleted / .declined
}

Both suspend until the user answers. The UI must show ConfirmationRequest.action, destination, every data item (name and value; isMasked values are already masked) and reasons. If the run stops meanwhile the call's task is cancelled and confirmationResolved(…, .cancelled) tells the UI to dismiss the sheet. A session created without a delegate refuses every action that needs confirmation.

# Starting a run

swift
let provider = try await registry.provider(for: providerID, space: spaceID)
let price = await registry.price(family: provider.family, model: provider.configuration.model)
let session = AgentSession(
    goal: goal, provider: provider, price: price, isGhost: profile.isGhost,
    limits: AgentLimits(budget: AgentBudget(maxSteps: 20, allowedDomains: ["example.com"])),
    policy: AgentPermissionPolicy(sharedTabs: [currentTab], capabilities: AgentPermissionPolicy.researchCapabilities),
    host: host, confirmation: confirmationUI, database: database)
Task { for await event in session.events { render(event) } }
await session.start()
// await session.stop()                 — immediate
// let result = await session.result()  — after the run ended and was saved

At launch, before any session starts: try await AgentRunHistory(database: database).markInterruptedRuns(). A run that was running or awaitingConfirmation when the app quit becomes failed with an "interrupted" step (AgentRunHistory.displayState(of:) == .interrupted). There is no API to resume a run: the conversation, the confirmations and the page state are not stored.

# Budgets

AgentLimits (= AgentBudget from NavigatorCore plus the limits it lacks) is copied into a let when the session is created. Exceeding any limit ends the run with budgetExhausted and a sentence naming the limit.

Limit Default Enforced
budget.maxSteps 20 before every model call and every tool call
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
budget.maxTokens 200 000 cumulative input + output of all requests, after each response; a request that cannot fit is not sent
budget.maxCostUSD 1.00 after each response, from CostEstimator with the price passed in the configuration, or the cost the provider reports
budget.allowedDomains none every URL in tool arguments, every redirect (host callback), every final address
maxTabsCreated 5 browser.create_tab
maxDownloads / maxDownloadBytes 3 / 50 MiB browser.download (announced size, host cap, and the size actually written)
maxToolResultCharacters 12 000 every tool result
maxExcerptLength 280 Citation.excerpt
maxConsecutiveInvalidCalls 3 then the run fails
maxContextCharacters 400 000 older tool results are compacted above it

Stated limits of the limits:

  • Tokens when the provider reports none are counted from text length at 3 characters per token (higher than the usual 4) plus 1 500 per image; AgentUsageReport.tokensAreEstimated is then true and a usageEstimated warning is emitted. It is an estimate, not a measurement.
  • Cost is an estimate (see AI_PROVIDERS.md). When no price is known, costIsKnown is false, a costUnknown warning is emitted and the cost limit is not enforced; the other limits still are.
  • A response in flight is not interrupted by the token or cost limit: the limit is found exceeded when the response ends, so a run can overshoot by one response.
  • Empty allowedDomains means the agent cannot navigate at all and works only with the shared tabs as they are.

# Context compaction

On ProviderError.contextTooLong, or above maxContextCharacters, older tool results are shortened by truncation (first 600 characters, then 200, with a marker saying how much was removed); images are dropped; the two most recent results stay whole on the first pass. No model is asked to summarise. Sources stay in the registry, so citations and quote checks are unaffected. If nothing is left to shorten the run fails with a clear reason.

# Citations and the answer check

browser.read, browser.extract and the tab sides of browser.compare register a source: URL, title, access date (from the clock), and an excerpt of at most maxExcerptLength characters. Ids are integers handed out by the registry; the same address keeps its id. The model cites as [n].

finish runs AnswerVerifier (no model involved):

  1. the answer is split into sentences;
  2. a sentence is a claim unless it is a question, a heading, shorter than three words, or says nothing was found;
  3. a claim must carry at least one id that exists in the registry of this run; ids that do not exist are removed from the text;
  4. quoted text of 12 characters or more must appear (case- and space-insensitively) in a cited source;
  5. failing sentences are marked [uncited] / [quote not found in the cited source], or removed when the policy is .drop.

The result is a VerifiedAnswer (text, sentences with their status, citations actually used). This proves that each kept claim points at something that was read and that quotations are real. It does not prove the source supports the claim. A final answer that describes actions ("I grouped your tabs") has no source and is marked; what the agent did is in the step list.

# What is sent to the provider

Per request: the fixed system prompt (rules and the run's nonce), the user's goal with the list of tab handles, allowed sites and limits, the model's own earlier turns, and tool results: page text, outlines, extracted records, diff summaries and screenshots of tabs the user shared or the agent opened — after redaction, without hidden text, bounded in size, each wrapped in the data envelope. Plus the tool definitions.

Never sent: cookies, website storage, saved passwords, Keychain items, history, bookmarks, downloads, local files, other profiles, tabs that were not shared, values of password / card / one-time-code fields, the API key (ProviderKit adds it as a header).

A screenshot is an image: whatever is displayed in it is sent, and it cannot be redacted.

# Private windows

AgentSessionConfiguration.isGhost removes the storage sink at construction: no code path can save the run. The run lives in the session and in the events; it is gone when the session is released. The model provider still receives what a normal run would send — a private window does not make a cloud model private; the UI should say so.

# Assistant helpers (no tools)

AssistantHelpers serves other modules: summarize(text:title:), explain(selection:context:), translate(selection:to:), compare(_:_:), extractFields(from:fields:) (JSON for Lens), each returning AsyncThrowingStream<AssistantEvent, Error> (textDelta, warning, usage, structured, finished).

Consent is part of the signature: every call needs a DisclosureAcknowledgement, which only acknowledge(_:remember:) and standingAcknowledgement() can produce.

swift
let helpers = AssistantHelpers(provider: provider, consent: consentStore)
let task = AssistantTask.summarize(text: readerText, title: title)
let acknowledgement: DisclosureAcknowledgement
if let standing = await helpers.standingAcknowledgement() { acknowledgement = standing }
else {
    let disclosure = helpers.disclosure(for: task)          // provider, model, each item with its size and a preview
    guard await ui.showConsent(disclosure) else { return }  // the UI's sheet
    acknowledgement = await helpers.acknowledge(disclosure)
}
for try await event in helpers.run(task, acknowledgement: acknowledgement) { … }

AssistantConsentStore remembers approvals per provider and Orbit space; InMemoryAssistantConsentStore is provided, the app persists its own (and uses a fresh in-memory one for a private window). The text is redacted, cut to maxInputCharacters (the disclosure says how much is left out), wrapped in the same nonce envelope and described to the model as data. No tool is offered, so text that tries to instruct the model can at worst change the wording of the answer. extractFields accepts only the requested keys with scalar values.

# Tests

swift test --disable-keychain --scratch-path build/spm-agent --filter AgentRuntimeTests — 138 tests in 16 suites (Swift Testing), all with ScriptedProvider, FakeHost, ManualClock, ScriptedDelegate (Tests/AgentRuntimeTests/Support.swift). No network, no model, no WebKit.

# Not verified

  • Anything with a real model or a real page (see the note at the top). In particular: whether models call these tools sensibly, whether the revision message leads to better answers, whether the last-step "only finish" turn works on every provider, and tool-name acceptance by each provider.
  • BrowserAgentHost has no production implementation yet; the contract above is what the runtime assumes.
  • The on-device Apple model cannot call tools (AI_PROVIDERS.md), so it can serve the helpers but not the agent.
  • iOS: the target compiles for iOS (xcodebuild -scheme AgentRuntime -destination 'generic/platform=iOS'); the tests ran on macOS only.
  • Long runs, real latency, and memory use with large pages were not measured.
Files main
Menu

Theme