SPB Git

Repository Public License

AgentTools.swift 14.3 KB 256 lines swift

1import Foundation2import ProviderKit34/// What the user grants, per run, before the agent starts. A tool whose capability is not granted is refused.5public enum AgentCapability: String, Sendable, Hashable, Codable, CaseIterable {6    case navigate, search, read, inspect, interact, submitForms, extract, screenshot, download, manageTabs78    public var label: String {9        switch self {10        case .navigate: "Open pages on the allowed sites"11        case .search: "Search the web with your search engine"12        case .read: "Read the text of shared pages and pages it opens"13        case .inspect: "See the structure of a page (headings, links, forms, buttons)"14        case .interact: "Click, scroll and type in pages"15        case .submitForms: "Submit forms (always asks first)"16        case .extract: "Extract structured data from a page"17        case .screenshot: "Capture the visible part of a page"18        case .download: "Download files (always asks first)"19        case .manageTabs: "Open tabs, and group, move or close its own or shared tabs"20        }21    }22}2324public enum AgentRiskLevel: String, Sendable, Hashable, Codable, Comparable {25    case low, medium, high2627    private var rank: Int { switch self { case .low: 0; case .medium: 1; case .high: 2 } }28    public static func < (lhs: AgentRiskLevel, rhs: AgentRiskLevel) -> Bool { lhs.rank < rhs.rank }29}3031/// When a tool asks the user before acting.32public enum AgentConfirmationRule: Sendable, Hashable {33    case never34    /// Asks when the stated condition holds.35    case conditional(String)36    case always3738    public var label: String {39        switch self {40        case .never: "No"41        case .conditional(let condition): "When \(condition)"42        case .always: "Always"43        }44    }45}4647/// Canonical tool names. `rawValue` is the name shown to the user and stored in `AgentStep.tool`.48public enum AgentToolName: String, Sendable, Hashable, CaseIterable {49    case navigate = "browser.navigate"50    case search = "browser.search"51    case read = "browser.read"52    case inspect = "browser.inspect"53    case click = "browser.click"54    case scroll = "browser.scroll"55    case type = "browser.type"56    case submitForm = "browser.submit_form"57    case extract = "browser.extract"58    case screenshot = "browser.screenshot"59    case compare = "browser.compare"60    case download = "browser.download"61    case createTab = "browser.create_tab"62    case organize = "browser.organize"63    case finish = "finish"6465    /// The name on the wire. Anthropic and OpenAI accept only `[A-Za-z0-9_-]` in tool names, so the dot becomes an66    /// underscore there.67    public var wireName: String { rawValue.replacingOccurrences(of: ".", with: "_") }68}6970/// One tool: its declared safety properties and the schema its arguments must satisfy.71public struct AgentToolSpec: Sendable, Hashable {72    public var name: AgentToolName73    public var summary: String74    /// `nil` for `finish`, which needs no capability.75    public var capability: AgentCapability?76    public var risk: AgentRiskLevel77    public var confirmation: AgentConfirmationRule78    /// What this tool can make leave the device, and to whom.79    public var dataLeavingDevice: String80    public var parameters: JSONValue8182    public var definition: ToolDefinition {83        ToolDefinition(name: name.wireName, description: summary, parameters: parameters)84    }85}8687/// The fixed tool list. It is a compile-time constant: nothing at run time adds, removes or edits a tool.88public enum AgentToolCatalog {89    public static let all: [AgentToolSpec] = [90        AgentToolSpec(91            name: .navigate,92            summary: "Load a URL in a tab you may use. Only sites the user allowed can be opened.",93            capability: .navigate, risk: .medium,94            confirmation: .conditional("the site is outside the allowed list (if the user chose to be asked) or the URL appears to carry copied data"),95            dataLeavingDevice: "The URL is requested from that site, with the profile's cookies for it.",96            parameters: object(["url": string("Absolute http(s) URL.", max: 2048), "tab": tab], required: ["url"])),97        AgentToolSpec(98            name: .search,99            summary: "Search the web with the user's search engine and load the results page.",100            capability: .search, risk: .medium,101            confirmation: .conditional("the query appears to carry text copied from a page or the conversation"),102            dataLeavingDevice: "The query is sent to the user's search engine.",103            parameters: object(["query": string("Search terms.", max: 256), "tab": tab], required: ["query"])),104        AgentToolSpec(105            name: .read,106            summary: "Read the visible text of a page (or its reader article). Long pages are paginated: pass the returned next_cursor to continue. Returns a source_id to cite.",107            capability: .read, risk: .low, confirmation: .never,108            dataLeavingDevice: "The page text (secrets redacted, hidden text excluded) is sent to the AI provider.",109            parameters: object([110                "tab": tab,111                "mode": string("page = all visible text, reader = main article only.", max: 16, options: ["page", "reader"]),112                "cursor": integer("Character offset to continue from.", min: 0, max: 50_000_000),113                "max_chars": integer("Characters to return.", min: 200, max: 12_000),114            ])),115        AgentToolSpec(116            name: .inspect,117            summary: "Get the outline of a page: headings, links, buttons and forms, each with an element ref usable by click, type, submit_form and extract.",118            capability: .inspect, risk: .low, confirmation: .never,119            dataLeavingDevice: "Headings, link texts and addresses, button labels and form field names are sent to the AI provider. Values of secret fields are masked.",120            parameters: object(["tab": tab])),121        AgentToolSpec(122            name: .click,123            summary: "Click a link or button by element ref (from browser.inspect).",124            capability: .interact, risk: .medium,125            confirmation: .conditional("the element looks like a purchase, payment, publication, message, account, settings, deletion, consent or sign-in action, submits a form, or is flagged irreversible"),126            dataLeavingDevice: "The click may make the page send requests to its site.",127            parameters: object(["tab": tab, "ref": ref], required: ["ref"])),128        AgentToolSpec(129            name: .scroll,130            summary: "Scroll a page.",131            capability: .interact, risk: .low, confirmation: .never,132            dataLeavingDevice: "Nothing, beyond what the page itself loads when scrolled.",133            parameters: object([134                "tab": tab,135                "direction": string("Where to scroll.", max: 8, options: ["up", "down", "top", "bottom"]),136                "pages": number("Viewport heights to scroll for up/down.", min: 0.1, max: 10),137            ], required: ["direction"])),138        AgentToolSpec(139            name: .type,140            summary: "Type text into a form field by element ref. Password, payment-card and one-time-code fields are always refused.",141            capability: .interact, risk: .medium,142            confirmation: .conditional("the text appears to be copied from a page or the conversation"),143            dataLeavingDevice: "The typed text is placed in the page, whose scripts can read it.",144            parameters: object(["tab": tab, "ref": ref, "text": string("Text to type.", max: 2000)], required: ["ref", "text"])),145        AgentToolSpec(146            name: .submitForm,147            summary: "Submit a form by its ref. The user is always asked first and sees every field that will be sent.",148            capability: .submitForms, risk: .high, confirmation: .always,149            dataLeavingDevice: "Every field of the form is sent to the form's destination.",150            parameters: object(["tab": tab, "ref": ref], required: ["ref"])),151        AgentToolSpec(152            name: .extract,153            summary: "Extract structured records from a page: by CSS selector, by element ref, or by a list of described fields. Give exactly one of selector, ref, fields. Returns a source_id to cite.",154            capability: .extract, risk: .low, confirmation: .never,155            dataLeavingDevice: "The extracted values (secrets redacted) are sent to the AI provider.",156            parameters: object([157                "tab": tab,158                "selector": string("CSS selector; one record per matching element.", max: 200),159                "ref": ref,160                "fields": .object([161                    "type": "array", "maxItems": 20, "minItems": 1,162                    "items": object([163                        "name": string("Field name.", max: 64),164                        "description": string("What the field contains.", max: 200),165                    ], required: ["name"]),166                ]),167                "max_items": integer("Maximum records.", min: 1, max: 100),168            ])),169        AgentToolSpec(170            name: .screenshot,171            summary: "Capture the visible part of a page as an image.",172            capability: .screenshot, risk: .medium, confirmation: .never,173            dataLeavingDevice: "The image of the visible page is sent to the AI provider, including anything displayed in it.",174            parameters: object(["tab": tab])),175        AgentToolSpec(176            name: .compare,177            summary: "Compare two texts and get a summary of differences. Each side is a tab (its current text) or a source_id read earlier. Give exactly one left_* and one right_*.",178            capability: .read, risk: .low, confirmation: .never,179            dataLeavingDevice: "A summary of added and removed lines is sent to the AI provider.",180            parameters: object([181                "left_tab": integer("Tab handle.", min: 1, max: 10_000), "right_tab": integer("Tab handle.", min: 1, max: 10_000),182                "left_source": integer("Source id.", min: 1, max: 100_000), "right_source": integer("Source id.", min: 1, max: 100_000),183            ])),184        AgentToolSpec(185            name: .download,186            summary: "Download a file to the user's downloads. The user is always asked first.",187            capability: .download, risk: .high, confirmation: .always,188            dataLeavingDevice: "The URL is requested from its site. The file is saved on this device.",189            parameters: object(["url": string("Absolute http(s) URL of the file.", max: 2048), "tab": tab], required: ["url"])),190        AgentToolSpec(191            name: .createTab,192            summary: "Open a new tab, optionally at a URL on an allowed site. Returns its tab handle.",193            capability: .manageTabs, risk: .medium,194            confirmation: .conditional("the URL is outside the allowed list (if the user chose to be asked) or appears to carry copied data"),195            dataLeavingDevice: "The URL, if any, is requested from that site.",196            parameters: object(["url": string("Absolute http(s) URL.", max: 2048)])),197        AgentToolSpec(198            name: .organize,199            summary: "Group, move or close tabs you created or that the user shared.",200            capability: .manageTabs, risk: .medium,201            confirmation: .conditional("a tab shared by the user would be closed"),202            dataLeavingDevice: "Nothing.",203            parameters: object([204                "action": string("What to do.", max: 8, options: ["group", "move", "close"]),205                "tabs": .object(["type": "array", "minItems": 1, "maxItems": 20, "items": integer("Tab handle.", min: 1, max: 10_000)]),206                "name": string("Group name (group).", max: 80),207                "index": integer("New position (move).", min: 0, max: 500),208            ], required: ["action", "tabs"])),209        AgentToolSpec(210            name: .finish,211            summary: "Give the final answer and end the run. Cite sources inline as [source_id] after each factual sentence; only ids returned by browser.read, browser.extract or browser.compare exist.",212            capability: nil, risk: .low, confirmation: .never,213            dataLeavingDevice: "Nothing.",214            parameters: object([215                "answer": string("The answer, with inline [n] citations.", max: 20_000),216                "citations": .object(["type": "array", "maxItems": 100, "items": integer("Source id used.", min: 1, max: 100_000)]),217            ], required: ["answer"])),218    ]219220    private static let byWireName: [String: AgentToolSpec] = Dictionary(uniqueKeysWithValues: all.map { ($0.name.wireName, $0) })221222    /// Looks a tool up by the exact name the model must use. There is no fuzzy matching.223    public static func spec(wireName: String) -> AgentToolSpec? { byWireName[wireName] }224    public static func spec(_ name: AgentToolName) -> AgentToolSpec {225        guard let spec = byWireName[name.wireName] else { preconditionFailure("tool \(name.rawValue) missing from the catalogue") }226        return spec227    }228229    public static var definitions: [ToolDefinition] { all.map(\.definition) }230231    // MARK: Schema builders232233    private static let tab: JSONValue = integer("Tab handle. Defaults to the tab used last.", min: 1, max: 10_000)234    private static let ref: JSONValue = string("Element ref from browser.inspect.", max: 64)235236    private static func object(_ properties: [String: JSONValue], required: [String] = []) -> JSONValue {237        var schema: [String: JSONValue] = ["type": "object", "properties": .object(properties), "additionalProperties": false]238        if !required.isEmpty { schema["required"] = .array(required.map(JSONValue.string)) }239        return .object(schema)240    }241242    private static func string(_ description: String, max: Int, options: [String]? = nil) -> JSONValue {243        var schema: [String: JSONValue] = ["type": "string", "description": .string(description), "maxLength": .number(Double(max))]244        if let options { schema["enum"] = .array(options.map(JSONValue.string)) }245        return .object(schema)246    }247248    private static func integer(_ description: String, min: Int, max: Int) -> JSONValue {249        ["type": "integer", "description": .string(description), "minimum": .number(Double(min)), "maximum": .number(Double(max))]250    }251252    private static func number(_ description: String, min: Double, max: Double) -> JSONValue {253        ["type": "number", "description": .string(description), "minimum": .number(min), "maximum": .number(max)]254    }255}256
Files main
Menu

Theme