SPB Git

Repository Public

Tools.swift 13.1 KB 246 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatAgents/Sources/Tools.swift3// Description: Tool contract, explicit permissions, JSON-schema argument validation and the registry that is the only way to execute a tool.4import Foundation5import LocalChatCore67public enum ToolPlatform: String, Sendable, CaseIterable {8    case macOS, iOS9    public static var current: ToolPlatform {10        #if os(macOS)11        .macOS12        #else13        .iOS14        #endif15    }16}1718public struct ToolOutput: Sendable, Hashable {19    public var text: String20    public var isError: Bool21    public var sources: [SourceReference]22    public init(_ text: String, isError: Bool = false, sources: [SourceReference] = []) { self.text = text; self.isError = isError; self.sources = sources }23    public static func error(_ message: String) -> ToolOutput { ToolOutput("Error: " + message, isError: true) }24}2526public struct ToolError: LocalizedError, Sendable, Equatable {27    public var message: String28    public init(_ message: String) { self.message = message }29    public var errorDescription: String? { message }30}3132/// What the user allowed. Nothing outside this struct can widen what a tool may do.33public struct ToolPermissions: Sendable, Hashable {34    public var enabledTools: Set<String>35    public var grantedFolders: [URL]        // resolved by the app from security-scoped bookmarks36    public var allowShell: Bool37    public var shellAllowlist: [String]     // when not empty, the command's first word must be in it38    public var shellDenylist: [String]      // extra substrings refused on top of the built-in hard denylist39    public var approval: ApprovalMode40    public init(enabledTools: Set<String> = ToolPermissions.defaultTools, grantedFolders: [URL] = [], allowShell: Bool = false,41                shellAllowlist: [String] = [], shellDenylist: [String] = [], approval: ApprovalMode = .risky) {42        self.enabledTools = enabledTools; self.grantedFolders = grantedFolders; self.allowShell = allowShell43        self.shellAllowlist = shellAllowlist; self.shellDenylist = shellDenylist; self.approval = approval44    }45    /// Safe defaults: no network, no writes, no shell.46    public static let defaultTools: Set<String> = ["calculator", "current_datetime", "knowledge_search"]47}4849public struct ToolContext: Sendable {50    public var permissions: ToolPermissions51    public var knowledge: (any KnowledgeSearching)?52    public var collectionIDs: [UUID]53    public init(permissions: ToolPermissions, knowledge: (any KnowledgeSearching)? = nil, collectionIDs: [UUID] = []) {54        self.permissions = permissions; self.knowledge = knowledge; self.collectionIDs = collectionIDs55    }56    var jail: FolderJail { FolderJail(roots: permissions.grantedFolders) }57}5859public protocol AgentTool: Sendable {60    var definition: ToolDefinition { get }61    var risk: ToolRisk { get }62    var platforms: Set<ToolPlatform> { get }63    /// True when the tool must be approved by a human on every call, whatever the approval mode.64    var alwaysRequiresApproval: Bool { get }65    func run(arguments: JSONValue, context: ToolContext) async throws -> ToolOutput66}6768public extension AgentTool {69    var platforms: Set<ToolPlatform> { Set(ToolPlatform.allCases) }70    var alwaysRequiresApproval: Bool { false }71    var name: String { definition.name }72}7374/// Minimal JSON Schema validation (type, required, enum, nested properties, items) with messages a model can act on.75public enum SchemaValidator {76    public static func validate(_ value: JSONValue, against schema: JSONValue, path: String = "arguments") -> [String] {77        var errors: [String] = []78        if let type = schema["type"]?.stringValue, !matches(value, type) {79            return ["\(path) must be of type \(type), got \(typeName(value))."]80        }81        if let options = schema["enum"]?.arrayValue, !options.contains(value) {82            errors.append("\(path) must be one of \(options.map { $0.serialized() }.joined(separator: ", ")).")83        }84        if let object = value.objectValue {85            let properties = schema["properties"]?.objectValue ?? [:]86            for key in schema["required"]?.arrayValue?.compactMap(\.stringValue) ?? [] where object[key] == nil || object[key] == .null {87                errors.append("Missing required argument \"\(key)\".")88            }89            for (key, child) in object.sorted(by: { $0.key < $1.key }) {90                if let sub = properties[key] { if child != .null { errors += validate(child, against: sub, path: key) } }91                else if schema["additionalProperties"]?.boolValue == false { errors.append("Unknown argument \"\(key)\".") }92            }93        }94        if let array = value.arrayValue, let items = schema["items"] {95            for (i, child) in array.enumerated() { errors += validate(child, against: items, path: "\(path)[\(i)]") }96        }97        return errors98    }99100    static func matches(_ v: JSONValue, _ type: String) -> Bool {101        switch (type, v) {102        case ("string", .string), ("boolean", .bool), ("number", .number), ("array", .array), ("object", .object), ("null", .null): true103        case ("integer", .number(let n)): n.rounded() == n104        default: false105        }106    }107    static func typeName(_ v: JSONValue) -> String {108        switch v { case .null: "null"; case .bool: "boolean"; case .number: "number"; case .string: "string"; case .array: "array"; case .object: "object" }109    }110111    /// Models often send numbers and booleans as strings; coerce what is unambiguous before validating.112    public static func coerce(_ value: JSONValue, to schema: JSONValue) -> JSONValue {113        switch (schema["type"]?.stringValue, value) {114        case ("number", .string(let s)), ("integer", .string(let s)): if let n = Double(s.trimmingCharacters(in: .whitespaces)) { return .number(n) }115        case ("boolean", .string(let s)): if ["true", "false"].contains(s.lowercased()) { return .bool(s.lowercased() == "true") }116        case ("string", .number(let n)): return .string(n.rounded() == n ? String(Int(n)) : String(n))117        case ("object", .object(let o)):118            let properties = schema["properties"]?.objectValue ?? [:]119            return .object(Dictionary(uniqueKeysWithValues: o.map { pair in (pair.key, properties[pair.key].map { coerce(pair.value, to: $0) } ?? pair.value) }))120        case ("object", .string(let s)): if let parsed = JSONValue.parse(s), parsed.objectValue != nil { return coerce(parsed, to: schema) }121        default: break122        }123        return value124    }125}126127public struct ToolRegistry: Sendable {128    private let tools: [String: any AgentTool]129    private let order: [String]130131    public init(tools: [any AgentTool]) {132        self.tools = Dictionary(tools.map { ($0.name, $0) }, uniquingKeysWith: { a, _ in a }); order = tools.map(\.name)133    }134135    /// Every built-in tool. `shellPermitted` is the app's statement that it may spawn processes (false for a sandboxed app).136    public static func builtIn(shellPermitted: Bool = false, urlFetcher: (any URLFetching)? = nil) -> ToolRegistry {137        var list: [any AgentTool] = [CalculatorTool(), DateTimeTool(), KnowledgeSearchTool(), ReadFileTool(), ListDirectoryTool(),138                                     SearchFilesTool(), WriteFileTool(), FetchURLTool(fetcher: urlFetcher ?? SafeURLFetcher())]139        #if os(macOS)140        if ShellTool.isShellAvailable(appPermitsShell: shellPermitted) { list.append(ShellTool()) }141        #endif142        return ToolRegistry(tools: list)143    }144145    public var allTools: [any AgentTool] { order.compactMap { tools[$0] } }146    public func tool(named name: String) -> (any AgentTool)? { tools[name] }147148    public func isAllowed(_ tool: any AgentTool, permissions: ToolPermissions) -> Bool {149        guard permissions.enabledTools.contains(tool.name), tool.platforms.contains(.current) else { return false }150        if tool.risk == .execute && !permissions.allowShell { return false }151        return true152    }153154    /// The definitions offered to the model: only tools the user enabled and this platform supports.155    public func definitions(for permissions: ToolPermissions) -> [ToolDefinition] {156        allTools.filter { isAllowed($0, permissions: permissions) }.map(\.definition)157    }158159    public func requiresApproval(_ tool: any AgentTool, permissions: ToolPermissions) -> Bool {160        if tool.alwaysRequiresApproval { return true }161        switch permissions.approval {162        case .always: return true163        case .risky: return tool.risk >= .write164        case .never: return false165        }166    }167168    /// Checks name, permission and arguments. Returns the tool and the coerced arguments, or the error text to feed back to the model.169    public func prepare(_ call: ToolInvocation, permissions: ToolPermissions) -> Result<(tool: any AgentTool, arguments: JSONValue), ToolError> {170        guard let tool = tools[call.name] else {171            return .failure(ToolError("Unknown tool \"\(call.name)\". Available tools: \(definitions(for: permissions).map(\.name).joined(separator: ", "))."))172        }173        guard isAllowed(tool, permissions: permissions) else {174            return .failure(ToolError("The tool \"\(call.name)\" is not enabled. The user has not granted permission to use it."))175        }176        let arguments = SchemaValidator.coerce(call.arguments == .null ? .object([:]) : call.arguments, to: tool.definition.parameters)177        let errors = SchemaValidator.validate(arguments, against: tool.definition.parameters)178        guard errors.isEmpty else { return .failure(ToolError("Invalid arguments for \(call.name): " + errors.joined(separator: " "))) }179        return .success((tool, arguments))180    }181182    /// Validates then runs. Never throws: failures come back as an error output for the model. Approval is the caller's job (AgentRunner).183    public func execute(_ call: ToolInvocation, context: ToolContext) async -> ToolOutput {184        switch prepare(call, permissions: context.permissions) {185        case .failure(let error): return .error(error.message)186        case .success(let ready):187            do { return try await ready.tool.run(arguments: ready.arguments, context: context) }188            catch is CancellationError { return .error("Cancelled.") }189            catch { return .error((error as? LocalizedError)?.errorDescription ?? String(describing: error)) }190        }191    }192}193194/// Folder confinement (same rules as LocalChatSecurity.PathSandbox; this module depends on Core only).195struct FolderJail: Sendable {196    let roots: [URL]197    init(roots: [URL]) { self.roots = roots.map(Self.canonical) }198199    /// A realpath that also works for paths that do not exist yet: walks the components, follows every symlink (also dangling ones),200    /// applies `..` on the already-resolved prefix, and keeps the non-existing tail as written.201    static func canonical(_ url: URL) -> URL {202        var pending = Array(url.path.split(separator: "/", omittingEmptySubsequences: true).map(String.init).reversed())203        var resolved: [String] = []204        var hops = 0205        while let component = pending.popLast() {206            if component == "." { continue }207            if component == ".." { _ = resolved.popLast(); continue }208            let candidate = "/" + (resolved + [component]).joined(separator: "/")209            if let destination = try? FileManager.default.destinationOfSymbolicLink(atPath: candidate) {210                hops += 1211                if hops > 40 { return URL(fileURLWithPath: "/dev/null/symlink-loop") }   // never inside a granted folder212                if destination.hasPrefix("/") { resolved = [] }213                pending.append(contentsOf: destination.split(separator: "/", omittingEmptySubsequences: true).map(String.init).reversed())214                continue215            }216            resolved.append(component)217        }218        return URL(fileURLWithPath: "/" + resolved.joined(separator: "/"))219    }220221    static func isInside(_ url: URL, _ root: URL) -> Bool {222        let a = url.pathComponents, b = root.pathComponents223        return a.count >= b.count && Array(a.prefix(b.count)) == b224    }225    func resolve(_ path: String) throws -> URL {226        guard !roots.isEmpty else { throw ToolError("No folder has been granted. Ask the user to grant a folder in the agent's permissions.") }227        let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines)228        guard !trimmed.contains("\0") else { throw ToolError("Invalid path.") }229        let url: URL230        if trimmed.isEmpty || trimmed == "." { url = roots[0] }231        else if trimmed.hasPrefix("/") { url = URL(fileURLWithPath: trimmed) }232        else if trimmed.hasPrefix("~") { url = URL(fileURLWithPath: (trimmed as NSString).expandingTildeInPath) }233        else { url = roots[0].appendingPathComponent(trimmed) }234        let c = Self.canonical(url)235        guard roots.contains(where: { Self.isInside(c, $0) }) else { throw ToolError("Access denied: \(trimmed) is outside the granted folders.") }236        return c237    }238    func display(_ url: URL) -> String {239        for root in roots where Self.isInside(url, root) {240            let rel = url.pathComponents.dropFirst(root.pathComponents.count).joined(separator: "/")241            return rel.isEmpty ? "." : rel242        }243        return url.path244    }245}246
Files main
Menu

Theme