SPB Git

Repository Public License

AgentPolicy.swift 8.6 KB 170 lines swift

1import Foundation2import NavigatorCore34// MARK: - Limits56/// Every hard limit of one run. `budget` is the shared NavigatorCore value; the rest are limits the runtime needs7/// that `AgentBudget` does not carry. The session copies this value once, at creation, into a `let`.8public struct AgentLimits: Sendable, Hashable, Codable {9    public var budget: AgentBudget10    public var maxTabsCreated: Int11    public var maxDownloads: Int12    /// Per file.13    public var maxDownloadBytes: Int6414    /// Characters of page-derived data in one tool result.15    public var maxToolResultCharacters: Int16    /// Characters of a page kept in a `Citation.excerpt`.17    public var maxExcerptLength: Int18    public var maxScreenshotBytes: Int19    /// Malformed, unknown or schema-invalid tool calls in a row before the run fails.20    public var maxConsecutiveInvalidCalls: Int21    /// Times a `finish` whose answer fails verification is handed back to the model before being repaired.22    public var maxAnswerRevisions: Int23    /// Characters of conversation sent in one request; older tool results are compacted above it.24    public var maxContextCharacters: Int2526    public init(budget: AgentBudget = AgentBudget(), maxTabsCreated: Int = 5, maxDownloads: Int = 3,27                maxDownloadBytes: Int64 = 50 * 1024 * 1024, maxToolResultCharacters: Int = 12_000, maxExcerptLength: Int = 280,28                maxScreenshotBytes: Int = 4 * 1024 * 1024, maxConsecutiveInvalidCalls: Int = 3, maxAnswerRevisions: Int = 1,29                maxContextCharacters: Int = 400_000) {30        self.budget = budget; self.maxTabsCreated = maxTabsCreated; self.maxDownloads = maxDownloads31        self.maxDownloadBytes = maxDownloadBytes; self.maxToolResultCharacters = maxToolResultCharacters32        self.maxExcerptLength = maxExcerptLength; self.maxScreenshotBytes = maxScreenshotBytes33        self.maxConsecutiveInvalidCalls = maxConsecutiveInvalidCalls; self.maxAnswerRevisions = maxAnswerRevisions34        self.maxContextCharacters = maxContextCharacters35    }36}3738// MARK: - Permission policy3940/// What the user decided before the run. Immutable for the run.41public struct AgentPermissionPolicy: Sendable, Hashable, Codable {42    public enum OffDomainNavigation: String, Sendable, Hashable, Codable {43        /// Navigation outside the allowed domains is refused.44        case deny45        /// The user is asked for each new site; an approval covers that exact host for the rest of the run.46        case ask47    }4849    public enum UncitedClaims: String, Sendable, Hashable, Codable {50        /// Keep the sentence and mark it `[uncited]`.51        case flag52        /// Remove the sentence from the answer (it stays in `VerifiedAnswer.sentences`).53        case drop54    }5556    /// Tabs the user explicitly shared. Only these, and tabs the agent creates, can be read, captured or acted on.57    public var sharedTabs: [TabID]58    public var capabilities: Set<AgentCapability>59    public var offDomainNavigation: OffDomainNavigation60    /// Text the host marked as not visible is left out of `browser.read` unless the user turns this on.61    public var includeHiddenText: Bool62    public var uncitedClaims: UncitedClaims63    /// Executable downloads are refused outright unless the user turns this on (they are still confirmed).64    public var allowExecutableDownloads: Bool6566    public init(sharedTabs: [TabID] = [], capabilities: Set<AgentCapability> = AgentPermissionPolicy.readOnlyCapabilities,67                offDomainNavigation: OffDomainNavigation = .deny, includeHiddenText: Bool = false,68                uncitedClaims: UncitedClaims = .flag, allowExecutableDownloads: Bool = false) {69        self.sharedTabs = sharedTabs; self.capabilities = capabilities; self.offDomainNavigation = offDomainNavigation70        self.includeHiddenText = includeHiddenText; self.uncitedClaims = uncitedClaims71        self.allowExecutableDownloads = allowExecutableDownloads72    }7374    public static let readOnlyCapabilities: Set<AgentCapability> = [.read, .inspect, .extract]75    public static let researchCapabilities: Set<AgentCapability> = [.navigate, .search, .read, .inspect, .extract, .manageTabs]76}7778// MARK: - URLs and domains7980/// Strict parsing of URLs that come from the model or from a page.81public enum AgentURL {82    /// An absolute http(s) URL without credentials, or `nil`. Strings a browser engine and Foundation could read83    /// differently (backslashes, whitespace, control characters) are refused rather than interpreted.84    public static func parse(_ text: String) -> URL? {85        guard !text.isEmpty, text.count <= 2048 else { return nil }86        for scalar in text.unicodeScalars {87            if scalar == "\\" || scalar.properties.isWhitespace || scalar.properties.generalCategory == .control88                || scalar.properties.generalCategory == .format { return nil }89        }90        guard let url = URL(string: text), let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https" else { return nil }91        guard url.user == nil, url.password == nil, DomainPolicy.normalisedHost(of: url) != nil else { return nil }92        return url93    }9495    /// `scheme://host[:port]`, for display in confirmations.96    public static func origin(of url: URL) -> String {97        let host = DomainPolicy.normalisedHost(of: url) ?? "unknown"98        let scheme = url.scheme?.lowercased() ?? "https"99        if let port = url.port, !((scheme == "https" && port == 443) || (scheme == "http" && port == 80)) { return "\(scheme)://\(host):\(port)" }100        return "\(scheme)://\(host)"101    }102}103104/// The domain allow-list of a run. A URL is allowed when its host, after IDN normalisation, equals an entry or is a105/// subdomain of one.106public struct DomainPolicy: Sendable, Hashable {107    /// Normalised (lowercase ASCII / punycode, no trailing dot) entries.108    public let domains: [String]109110    public init(allowedDomains: [String]) {111        var seen = Set<String>()112        domains = allowedDomains.compactMap(Self.normalise(entry:)).filter { seen.insert($0).inserted }113    }114115    /// An entry as the user typed it: a bare host, `*.host`, or a URL.116    static func normalise(entry: String) -> String? {117        var text = entry.trimmingCharacters(in: .whitespacesAndNewlines)118        if text.hasPrefix("*.") { text.removeFirst(2) }119        if text.contains("://") { return URL(string: text).flatMap(normalisedHost(of:)) }120        return normalise(host: text)121    }122123    /// Lowercase punycode form of a host, or `nil` when it is not a host name.124    public static func normalise(host: String) -> String? {125        let trimmed = host.trimmingCharacters(in: .whitespacesAndNewlines)126        guard !trimmed.isEmpty, !trimmed.contains("/"), !trimmed.contains("@"), !trimmed.contains("\\"), !trimmed.contains("?"),127              !trimmed.contains("#"), !trimmed.contains(" ") else { return nil }128        let bracketed = trimmed.contains(":") && !trimmed.hasPrefix("[") ? "[\(trimmed)]" : trimmed129        return URL(string: "https://\(bracketed)/").flatMap(normalisedHost(of:))130    }131132    public static func normalisedHost(of url: URL) -> String? {133        // Foundation applies IDNA (UTS 46) to the host; `percentEncoded: false` returns the punycode form.134        guard var host = url.host(percentEncoded: false)?.lowercased(), !host.isEmpty else { return nil }135        while host.hasSuffix(".") { host.removeLast() }136        guard !host.isEmpty, !host.contains("%"), !host.contains(".."), !host.hasPrefix("."),137              host.unicodeScalars.allSatisfy({ $0.isASCII && $0.value > 0x20 }) else { return nil }138        return host139    }140141    public func allows(host: String) -> Bool {142        guard let host = Self.normalise(host: host) else { return false }143        return domains.contains { host == $0 || host.hasSuffix("." + $0) }144    }145146    /// http(s), no credentials, and a host on the list.147    public func allows(_ url: URL) -> Bool {148        guard let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https", url.user == nil, url.password == nil,149              let host = Self.normalisedHost(of: url) else { return false }150        return domains.contains { host == $0 || host.hasSuffix("." + $0) }151    }152}153154// MARK: - Clock155156/// Time as the session sees it. Injectable so that tests control the wall-clock limit.157public protocol AgentClock: Sendable {158    func now() -> Date159    /// Suspends for `seconds`; throws `CancellationError` when the task is cancelled.160    func sleep(for seconds: TimeInterval) async throws161}162163public struct SystemAgentClock: AgentClock {164    public init() {}165    public func now() -> Date { Date() }166    public func sleep(for seconds: TimeInterval) async throws {167        try await Task.sleep(for: .seconds(max(0, seconds)))168    }169}170
Files main
Menu

Theme