SPB Git

Repository Public License

Support.swift 21.3 KB 475 lines swift

1import Foundation2import NavigatorCore3import ProviderKit4import Testing5@testable import AgentRuntime67// MARK: - Scripted provider89/// One scripted model turn.10indirect enum Turn: Sendable {11    case reply([ChatEvent])12    case fail(ProviderError)13    /// Never answers; ends when the consumer cancels.14    case hang15    case dynamic(@Sendable (ChatRequest) -> Turn)1617    static let defaultUsage = ProviderUsage(inputTokens: 100, outputTokens: 10)1819    static func tools(_ calls: [ToolCall], text: String = "", usage: ProviderUsage? = defaultUsage) -> Turn {20        var events: [ChatEvent] = [.started(ResponseStart())]21        if !text.isEmpty { events.append(.textDelta(text)) }22        events += calls.map(ChatEvent.toolCallCompleted)23        if let usage { events.append(.usage(usage)) }24        events.append(.finished(.toolCalls))25        return .reply(events)26    }2728    static func text(_ text: String, usage: ProviderUsage? = defaultUsage) -> Turn {29        var events: [ChatEvent] = [.started(ResponseStart()), .textDelta(text)]30        if let usage { events.append(.usage(usage)) }31        events.append(.finished(.endOfTurn))32        return .reply(events)33    }3435    static func finish(_ answer: String, usage: ProviderUsage? = defaultUsage) -> Turn {36        .tools([call(.finish, ["answer": .string(answer)])], usage: usage)37    }38}3940func call(_ tool: AgentToolName, _ arguments: JSONValue = [:]) -> ToolCall {41    ToolCall(id: "call-" + UUID().uuidString.prefix(8), name: tool.wireName, arguments: arguments)42}4344func rawCall(_ name: String, _ arguments: JSONValue = [:]) -> ToolCall {45    ToolCall(id: "call-" + UUID().uuidString.prefix(8), name: name, arguments: arguments)46}4748/// A provider that plays a script and records what it was sent. No network, no model.49final class ScriptedProvider: ChatProvider, @unchecked Sendable {50    let family = ProviderFamily.compatible51    private let lock = NSLock()52    private var script: [Turn]53    private var recorded: [ChatRequest] = []54    private var cancelled = 055    /// Played when the script runs out.56    private let fallback: Turn5758    init(_ script: [Turn], fallback: Turn = .text("I have nothing to add.")) { self.script = script; self.fallback = fallback }5960    var requests: [ChatRequest] { lock.withLock { recorded } }61    var cancellations: Int { lock.withLock { cancelled } }6263    /// Text of every tool result in the last request.64    var lastToolResults: [String] { (requests.last?.messages ?? []).filter { $0.role == .tool }.map(\.text) }65    var allToolResults: String { lastToolResults.joined(separator: "\n=====\n") }6667    private func next(_ request: ChatRequest) -> Turn {68        var turn = lock.withLock { () -> Turn in69            recorded.append(request)70            return script.isEmpty ? fallback : script.removeFirst()71        }72        while case .dynamic(let make) = turn { turn = make(request) }73        return turn74    }7576    private func noteCancelled() { lock.withLock { cancelled += 1 } }7778    func stream(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, Error> {79        let turn = next(request)80        return AsyncThrowingStream { continuation in81            let task = Task {82                switch turn {83                case .reply(let events):84                    for event in events { continuation.yield(event) }85                    continuation.finish()86                case .fail(let error):87                    continuation.finish(throwing: error)88                case .hang, .dynamic:89                    while !Task.isCancelled { try? await Task.sleep(for: .milliseconds(3)) }90                    self.noteCancelled()91                    continuation.finish(throwing: ProviderError.cancelled)92                }93            }94            continuation.onTermination = { _ in task.cancel() }95        }96    }9798    func listModels() async throws -> [ModelInfo] { [] }99    func testConnection() async throws -> ConnectionReport { ConnectionReport(family: family, summary: "scripted", latencyMilliseconds: 0) }100}101102// MARK: - Fake host103104struct FakePage: Sendable {105    var title = "Page"106    var segments: [AgentTextSegment] = []107    var headings: [AgentHeading] = []108    var links: [AgentElement] = []109    var buttons: [AgentElement] = []110    var forms: [AgentForm] = []111    var challenges: [AgentChallenge] = []112    var redirect: URL?113    var records: [[String: String]] = []114115    static func text(_ text: String, title: String = "Page") -> FakePage { FakePage(title: title, segments: [AgentTextSegment(text)]) }116}117118func url(_ text: String) -> URL { URL(string: text)! }119120/// A scripted browser. It honours the redirect guard like a correct host unless told to misbehave.121actor FakeHost: BrowserAgentHost {122    var pages: [String: FakePage] = [:]123    var tabURLs: [TabID: URL] = [:]124    private(set) var calls: [String] = []125    private(set) var sawCancellation = false126    /// Methods that never return until cancelled.127    var hanging = Set<String>()128    /// A buggy host that commits redirects the guard refused.129    var ignoresGuard = false130    var clickTargets: [String: URL] = [:]131    var submitTargets: [String: URL] = [:]132    var probes: [String: AgentDownloadProbe] = [:]133    var downloadedBytes: Int64 = 100134    var searchEngine = "https://search.example/?q="135    /// Makes the next `outline` report this page instead (a page that changes between inspect and click).136    var outlineOverride: FakePage?137138    /// Outlines returned by successive `outline` calls before falling back to the page (a page that changes).139    var outlineQueue: [FakePage] = []140    var failures: [String: BrowserAgentHostError] = [:]141    /// `readText` first moves the tab here: a page that navigates itself between the runtime's check and the read.142    var readMovesTo: URL?143144    func setOutlineQueue(_ pages: [FakePage]) { outlineQueue = pages }145    func setFailure(_ method: String, _ error: BrowserAgentHostError?) { failures[method] = error }146    func setReadMovesTo(_ address: String) { readMovesTo = url(address) }147    func setSubmitTarget(_ ref: String, _ address: String) { submitTargets[ref] = url(address) }148    func setPage(_ address: String, _ page: FakePage) { pages[address] = page }149    func open(_ tab: TabID, at address: String) { tabURLs[tab] = url(address) }150    func hang(on method: String) { hanging.insert(method) }151    func setIgnoresGuard(_ value: Bool) { ignoresGuard = value }152    func setClickTarget(_ ref: String, _ address: String) { clickTargets[ref] = url(address) }153    func setProbe(_ address: String, _ probe: AgentDownloadProbe) { probes[address] = probe }154    func setDownloadedBytes(_ value: Int64) { downloadedBytes = value }155    func setOutlineOverride(_ page: FakePage?) { outlineOverride = page }156    func removeChallenges(_ address: String) { pages[address]?.challenges = [] }157    func called(_ prefix: String) -> Bool { calls.contains { $0.hasPrefix(prefix) } }158159    private func enter(_ method: String, _ detail: String = "") async throws {160        calls.append(detail.isEmpty ? method : "\(method) \(detail)")161        if let failure = failures[method] { throw failure }162        guard hanging.contains(method) else { return }163        while !Task.isCancelled { try? await Task.sleep(for: .milliseconds(3)) }164        sawCancellation = true165        throw CancellationError()166    }167168    private func page(_ tab: TabID) throws -> (URL, FakePage) {169        guard let current = tabURLs[tab] else { throw BrowserAgentHostError.tabUnavailable }170        return (current, pages[current.absoluteString] ?? FakePage(title: ""))171    }172173    private func info(_ tab: TabID) throws -> AgentPageInfo {174        let (current, page) = try page(tab)175        return AgentPageInfo(url: current, title: page.title)176    }177178    private func follow(_ start: URL, guard allowed: AgentNavigationGuard) throws -> URL {179        var target = start, hops = 0180        while let next = pages[target.absoluteString]?.redirect, hops < 5 {181            guard ignoresGuard || allowed(next) else { throw BrowserAgentHostError.navigationBlocked(next) }182            target = next; hops += 1183        }184        return target185    }186187    func pageInfo(tab: TabID) async throws -> AgentPageInfo {188        try await enter("pageInfo")189        return try info(tab)190    }191192    func searchURL(for query: String) async throws -> URL {193        try await enter("searchURL", query)194        var components = URLComponents(string: searchEngine)!195        components.queryItems = [URLQueryItem(name: "q", value: query)]196        return components.url!197    }198199    func navigate(tab: TabID, to url: URL, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentPageInfo {200        try await enter("navigate", url.absoluteString)201        tabURLs[tab] = try follow(url, guard: redirectGuard)202        return try info(tab)203    }204205    func readText(tab: TabID, mode: AgentReadMode) async throws -> AgentPageText {206        try await enter("readText", tab.string)207        if let readMovesTo { tabURLs[tab] = readMovesTo }208        let (_, page) = try page(tab)209        return AgentPageText(info: try info(tab), segments: page.segments)210    }211212    func outline(tab: TabID) async throws -> AgentPageOutline {213        try await enter("outline")214        let page = try outlineQueue.isEmpty ? (outlineOverride ?? page(tab).1) : outlineQueue.removeFirst()215        return AgentPageOutline(info: try info(tab), headings: page.headings, links: page.links, buttons: page.buttons, forms: page.forms, challenges: page.challenges)216    }217218    func click(tab: TabID, ref: String, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentActionOutcome {219        try await enter("click", ref)220        if let target = clickTargets[ref] {221            guard ignoresGuard || redirectGuard(target) else { throw BrowserAgentHostError.navigationBlocked(target) }222            tabURLs[tab] = try follow(target, guard: redirectGuard)223            return AgentActionOutcome(page: try info(tab), didNavigate: true)224        }225        return AgentActionOutcome(page: try info(tab))226    }227228    func type(tab: TabID, ref: String, text: String) async throws {229        try await enter("type", "\(ref)=\(text)")230        guard let current = tabURLs[tab], var page = pages[current.absoluteString] else { return }231        for formIndex in page.forms.indices {232            for fieldIndex in page.forms[formIndex].fields.indices where page.forms[formIndex].fields[fieldIndex].ref == ref {233                page.forms[formIndex].fields[fieldIndex].value = text234            }235        }236        pages[current.absoluteString] = page237    }238239    func submitForm(tab: TabID, ref: String, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentActionOutcome {240        try await enter("submitForm", ref)241        if let target = submitTargets[ref] { tabURLs[tab] = try follow(target, guard: redirectGuard) }242        return AgentActionOutcome(page: try info(tab), didNavigate: submitTargets[ref] != nil)243    }244245    func scroll(tab: TabID, direction: AgentScrollDirection, pages: Double) async throws -> AgentScrollState {246        try await enter("scroll", direction.rawValue)247        return AgentScrollState(position: direction == .top ? 0 : 0.5, atTop: direction == .top, atBottom: direction == .bottom)248    }249250    func extract(tab: TabID, query: AgentExtractionQuery) async throws -> AgentExtraction {251        try await enter("extract")252        return AgentExtraction(info: try info(tab), records: try page(tab).1.records)253    }254255    func screenshot(tab: TabID) async throws -> AgentScreenshot {256        try await enter("screenshot")257        return AgentScreenshot(info: try info(tab), data: Data(repeating: 7, count: 2_048))258    }259260    func probeDownload(url: URL, fromTab: TabID?, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentDownloadProbe {261        try await enter("probeDownload", url.absoluteString)262        let final = try follow(url, guard: redirectGuard)263        return probes[final.absoluteString] ?? AgentDownloadProbe(url: final, filename: final.lastPathComponent, mimeType: "application/pdf", expectedBytes: 100)264    }265266    func download(url: URL, fromTab: TabID?, maxBytes: Int64, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentDownloadResult {267        try await enter("download", url.absoluteString)268        return AgentDownloadResult(filename: url.lastPathComponent, byteCount: downloadedBytes)269    }270271    func createTab(url: URL?, redirectGuard: @escaping AgentNavigationGuard) async throws -> AgentCreatedTab {272        try await enter("createTab", url?.absoluteString ?? "")273        let tab = TabID()274        guard let url else { return AgentCreatedTab(id: tab) }275        tabURLs[tab] = try follow(url, guard: redirectGuard)276        return AgentCreatedTab(id: tab, info: try info(tab))277    }278279    func organize(_ operation: AgentTabOperation) async throws {280        switch operation {281        case .group(let tabs, let name): try await enter("group", "\(tabs.count) \(name)")282        case .move(_, let index): try await enter("move", "\(index)")283        case .close(let tab): try await enter("close", tab.string); tabURLs[tab] = nil284        }285    }286}287288// MARK: - Clock289290/// Time that moves only when a test says so.291final class ManualClock: AgentClock, @unchecked Sendable {292    private let lock = NSLock()293    private var current = Date(timeIntervalSince1970: 1_800_000_000)294    private var sleepers: [UUID: (deadline: Date, continuation: CheckedContinuation<Void, Error>)] = [:]295296    func now() -> Date { lock.withLock { current } }297    var sleeperCount: Int { lock.withLock { sleepers.count } }298299    private func register(_ id: UUID, seconds: TimeInterval, _ continuation: CheckedContinuation<Void, Error>) {300        let resumeNow = lock.withLock { () -> Bool in301            if seconds <= 0 { return true }302            sleepers[id] = (current.addingTimeInterval(seconds), continuation)303            return false304        }305        if resumeNow { continuation.resume() }306    }307308    private func cancel(_ id: UUID) {309        lock.withLock { sleepers.removeValue(forKey: id) }?.continuation.resume(throwing: CancellationError())310    }311312    func sleep(for seconds: TimeInterval) async throws {313        let id = UUID()314        try await withTaskCancellationHandler(operation: {315            try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in316                if Task.isCancelled { continuation.resume(throwing: CancellationError()) } else { self.register(id, seconds: seconds, continuation) }317            }318        }, onCancel: { self.cancel(id) })319    }320321    func advance(by seconds: TimeInterval) {322        let due = lock.withLock { () -> [CheckedContinuation<Void, Error>] in323            current = current.addingTimeInterval(seconds)324            let ready = sleepers.filter { $0.value.deadline <= current }325            for key in ready.keys { sleepers[key] = nil }326            return ready.values.map(\.continuation)327        }328        for continuation in due { continuation.resume() }329    }330}331332// MARK: - Delegate333334final class ScriptedDelegate: AgentConfirmationDelegate, @unchecked Sendable {335    enum Mode: Sendable { case approve, deny, hang, decide(@Sendable (ConfirmationRequest) -> ConfirmationDecision) }336337    private let lock = NSLock()338    private var seen: [ConfirmationRequest] = []339    private var handoffsSeen: [AgentHandoffRequest] = []340    let mode: Mode341    let handoff: AgentHandoffDecision?342    /// Runs when the user "deals with" a hand-off (for example to remove the CAPTCHA from the fake page).343    let onHandoff: (@Sendable () async -> Void)?344345    init(_ mode: Mode, handoff: AgentHandoffDecision? = .declined, onHandoff: (@Sendable () async -> Void)? = nil) {346        self.mode = mode; self.handoff = handoff; self.onHandoff = onHandoff347    }348349    var requests: [ConfirmationRequest] { lock.withLock { seen } }350    var handoffs: [AgentHandoffRequest] { lock.withLock { handoffsSeen } }351352    func confirm(_ request: ConfirmationRequest) async -> ConfirmationDecision {353        lock.withLock { seen.append(request) }354        switch mode {355        case .approve: return .approved356        case .deny: return .denied357        case .decide(let decide): return decide(request)358        case .hang:359            while !Task.isCancelled { try? await Task.sleep(for: .milliseconds(3)) }360            return .denied361        }362    }363364    func handOff(_ request: AgentHandoffRequest) async -> AgentHandoffDecision {365        lock.withLock { handoffsSeen.append(request) }366        guard let handoff else {367            while !Task.isCancelled { try? await Task.sleep(for: .milliseconds(3)) }368            return .declined369        }370        await onHandoff?()371        return handoff372    }373}374375// MARK: - Sinks376377actor RecordingSink: AgentRunSink {378    private(set) var saves: [AgentRun] = []379    func save(_ run: AgentRun) { saves.append(run) }380}381382struct FailingSink: AgentRunSink {383    struct Broken: Error {}384    func save(_ run: AgentRun) async throws { throw Broken() }385}386387// MARK: - Harness388389struct Harness {390    static let start = "https://example.com/start"391    static let startText = "Paris is the capital of France. The city lies on the river Seine and has about two million inhabitants."392393    let session: AgentSession394    let provider: ScriptedProvider395    let host: FakeHost396    let delegate: ScriptedDelegate?397    let clock: ManualClock398    let tab: TabID399    private let collector: Task<[AgentEvent], Never>400401    /// A session over one shared tab showing `https://example.com/start`.402    static func make(_ script: [Turn], goal: String = "What is the capital of France? Cite your source.", domains: [String] = ["example.com"],403                     steps: Int = 12, capabilities: Set<AgentCapability> = Set(AgentCapability.allCases), delegate: ScriptedDelegate? = nil,404                     limits: ((inout AgentLimits) -> Void)? = nil, policy: ((inout AgentPermissionPolicy) -> Void)? = nil,405                     price: ModelPrice? = nil, isGhost: Bool = false, sink: (any AgentRunSink)? = nil, shareTab: Bool = true,406                     fallback: Turn = .text("I have nothing to add."), host: FakeHost? = nil, clock: ManualClock = ManualClock()) async -> Harness {407        let host = host ?? FakeHost()408        let tab = TabID()409        await host.open(tab, at: start)410        if await host.pages[start] == nil { await host.setPage(start, .text(startText, title: "France")) }411        var agentLimits = AgentLimits(budget: AgentBudget(maxSteps: steps, maxDurationSeconds: 300, maxTokens: 200_000, maxCostUSD: 1, allowedDomains: domains))412        limits?(&agentLimits)413        var agentPolicy = AgentPermissionPolicy(sharedTabs: shareTab ? [tab] : [], capabilities: capabilities)414        policy?(&agentPolicy)415        let configuration = AgentSessionConfiguration(goal: goal, isGhost: isGhost, providerID: "scripted", model: "scripted-1", price: price,416                                                      limits: agentLimits, policy: agentPolicy)417        let provider = ScriptedProvider(script, fallback: fallback)418        let session = AgentSession(configuration: configuration, provider: provider, host: host, confirmation: delegate, sink: sink, clock: clock,419                                   envelope: DataEnvelope(nonce: "testnonce0123456789abcdef"))420        let events = session.events421        let collector = Task { () -> [AgentEvent] in422            var all: [AgentEvent] = []423            for await event in events { all.append(event) }424            return all425        }426        return Harness(session: session, provider: provider, host: host, delegate: delegate, clock: clock, tab: tab, collector: collector)427    }428429    /// Runs to the end.430    func run() async -> (result: AgentRunResult, events: [AgentEvent]) {431        await session.start()432        let result = await session.result()433        return (result, await collector.value)434    }435436    func finish() async -> (result: AgentRunResult, events: [AgentEvent]) {437        let result = await session.result()438        return (result, await collector.value)439    }440}441442struct Timeout: Error {}443444/// Polls until `condition` holds; fails the test after `seconds`.445func eventually(_ what: String, seconds: Double = 5, _ condition: @Sendable () async -> Bool) async throws {446    let deadline = Date().addingTimeInterval(seconds)447    while !(await condition()) {448        if Date() > deadline { Issue.record("timed out waiting for: \(what)"); throw Timeout() }449        try await Task.sleep(for: .milliseconds(4))450    }451}452453extension Array where Element == AgentEvent {454    var steps: [AgentStep] {455        var latest: [Int: AgentStep] = [:], order: [Int] = []456        for event in self {457            switch event {458            case .stepStarted(let step), .stepUpdated(let step), .stepFinished(let step):459                if latest[step.id] == nil { order.append(step.id) }460                latest[step.id] = step461            default: break462            }463        }464        return order.compactMap { latest[$0] }465    }466467    var toolSteps: [AgentStep] { steps.filter { $0.kind == .toolCall } }468    var confirmations: [ConfirmationRequest] { compactMap { if case .confirmationRequested(let request) = $0 { request } else { nil } } }469    var warnings: [AgentWarning] { compactMap { if case .warning(let warning) = $0 { warning } else { nil } } }470    var citations: [Citation] { compactMap { if case .citationAdded(let citation) = $0 { citation } else { nil } } }471    var phases: [AgentPhase] { compactMap { if case .phaseChanged(let phase) = $0 { phase } else { nil } } }472    var text: String { compactMap { if case .textDelta(let delta) = $0 { delta } else { nil } }.joined() }473    var finished: AgentRunResult? { if case .finished(let result)? = last { result } else { nil } }474}475
Files main
Menu

Theme