SPB Git

Repository Public MIT

ToolRuntime.swift 14.4 KB 295 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraAgents/Sources/ToolRuntime.swift10// Module           : Packages11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import AstraCore9091/// What a tool can touch. The approval policy is derived from this value in code; a model cannot change it.92public enum ToolRisk: String, Sendable, Codable, Hashable, CaseIterable {93    case safe, readsUserData, writesUserData, sendsDataExternally, destructive9495    public var label: String {96        switch self {97        case .safe: "No access to your data"98        case .readsUserData: "Reads your data"99        case .writesUserData: "Writes a file"100        case .sendsDataExternally: "Sends data to a website"101        case .destructive: "Changes or deletes data"102        }103    }104}105106/// A failure whose message is written for the model (and shown in the timeline): short, specific, actionable.107public struct ToolError: Error, LocalizedError, Sendable, Hashable {108    public var message: String109    /// True when the same call may succeed if it is simply made again (a dropped connection, a busy server). The runner110    /// retries such a failure once, and only for tools that declare themselves idempotent.111    public var isTransient: Bool112    public init(_ message: String, isTransient: Bool = false) { self.message = message; self.isTransient = isTransient }113    public var errorDescription: String? { message }114}115116public struct ToolOutput: Sendable, Hashable, Codable {117    public var text: String118    public var isError: Bool119    public var truncated: Bool120    public init(_ text: String, isError: Bool = false, truncated: Bool = false) {121        self.text = text; self.isError = isError; self.truncated = truncated122    }123}124125public struct ToolContext: Sendable, Hashable {126    public var runID: UUID127    public var callID: String128    /// Upper bound the runner applies to the result; tools may use it to stop early.129    public var maxOutputCharacters: Int130    public init(runID: UUID = UUID(), callID: String = "call", maxOutputCharacters: Int = OutputLimiter.defaultMaxCharacters) {131        self.runID = runID; self.callID = callID; self.maxOutputCharacters = maxOutputCharacters132    }133}134135/// One capability an agent may be given. Tools never spawn processes, never evaluate code and never touch file paths themselves.136public protocol AgentTool: Sendable {137    var definition: ToolDefinition { get }138    var risk: ToolRisk { get }139    /// Cheap checks that must fail before the user is asked anything (for example a URL that can never be fetched).140    func preflight(_ arguments: JSONValue) throws141    /// Narrows an "allow for this run" grant (the host for `web_fetch`); nil means the grant covers the whole tool.142    func approvalScope(_ arguments: JSONValue) -> String?143    /// One human-readable line for the approval sheet; nil lets the runtime build one from the arguments.144    func approvalSummary(_ arguments: JSONValue) -> String?145    /// What the person grants by allowing this tool. Derived from `risk` unless a tool says otherwise.146    var permission: PermissionLevel { get }147    /// Seconds the runner waits for `run` before giving the model a timeout error. Nil for tools that wait for the person148    /// (a save dialog), which have no deadline.149    var timeout: TimeInterval? { get }150    /// True when running the same call twice has the same effect as running it once. Only such tools are retried after a151    /// transient failure, and only such calls are run again when a run resumes after the app was closed.152    var isIdempotent: Bool { get }153    /// One sentence describing what the tool returns.154    var outputSummary: String { get }155    /// What this call would send off the device, as addresses, for the exfiltration check. Default: every URL in the arguments.156    func outboundProbes(_ arguments: JSONValue) -> [URL]157    func run(_ arguments: JSONValue, context: ToolContext) async throws -> ToolOutput158}159160/// Everything a tool declares about itself, in one value: for the registry screen, the audit trail and the documentation.161public struct ToolDescriptor: Sendable, Hashable, Identifiable {162    public var id: String163    public var summary: String164    public var inputSchema: JSONValue165    public var outputSummary: String166    public var risk: ToolRisk167    public var permission: PermissionLevel168    public var timeout: TimeInterval?169    public var isIdempotent: Bool170    /// Every tool can be cancelled: the runner stops waiting at once and the tool's task is cancelled.171    public var supportsCancellation: Bool { true }172    /// What the tool leaves behind, in words.173    public var sideEffects: String {174        switch permission {175        case .readOnly: "None."176        case .sensitiveData: "None. It reads data you keep in the app or shared with it."177        case .localModification: "Saves or changes data on this iPhone, after you confirm."178        case .externalNetwork: "Sends a request to a website; the address is visible to that site."179        case .externalSideEffects: "Changes something outside this iPhone, or cannot be undone."180        }181    }182}183184public extension AgentTool {185    var name: String { definition.name }186    func preflight(_ arguments: JSONValue) throws {}187    func approvalScope(_ arguments: JSONValue) -> String? { nil }188    func approvalSummary(_ arguments: JSONValue) -> String? { nil }189    var permission: PermissionLevel { PermissionLevel(risk: risk) }190    var timeout: TimeInterval? { ToolDefaults.timeout }191    var isIdempotent: Bool { risk == .safe || risk == .readsUserData }192    var outputSummary: String { "Text." }193    func outboundProbes(_ arguments: JSONValue) -> [URL] { AgentSession.urls(in: arguments) }194    var descriptor: ToolDescriptor {195        ToolDescriptor(id: name, summary: definition.summary, inputSchema: definition.parameters, outputSummary: outputSummary, risk: risk,196                       permission: permission, timeout: timeout, isIdempotent: isIdempotent)197    }198}199200public enum ToolDefaults {201    /// Default deadline of one tool call.202    public static let timeout: TimeInterval = 30203}204205/// Caps text handed back to a model and marks the cut so neither the model nor the reader mistakes it for the whole.206public enum OutputLimiter {207    public static let defaultMaxCharacters = 12_000208    public static let markerPrefix = "[… output truncated:"209210    public static func cap(_ text: String, maxCharacters: Int) -> (text: String, truncated: Bool) {211        let limit = max(64, maxCharacters)212        guard text.count > limit else { return (text, false) }213        let total = text.count214        return (String(text.prefix(limit)) + "\n\(markerPrefix) \(limit) of \(total) characters shown]", true)215    }216217    public static func cap(_ output: ToolOutput, maxCharacters: Int) -> ToolOutput {218        let capped = cap(output.text, maxCharacters: maxCharacters)219        return ToolOutput(capped.text, isError: output.isError, truncated: output.truncated || capped.truncated)220    }221}222223/// The set of tools the app has installed. Which of them an agent may call is decided by the profile's allowlist, checked here in code.224public struct ToolRegistry: Sendable {225    private var tools: [String: any AgentTool] = [:]226    public private(set) var names: [String] = []227228    public init(_ tools: [any AgentTool] = []) { for tool in tools { register(tool) } }229230    public mutating func register(_ tool: any AgentTool) {231        if tools[tool.name] == nil { names.append(tool.name) }232        tools[tool.name] = tool233    }234235    public func tool(named name: String) -> (any AgentTool)? { tools[name] }236237    /// What every installed tool declares about itself, in installation order.238    public var descriptors: [ToolDescriptor] { names.compactMap { tools[$0]?.descriptor } }239240    /// Definitions offered to the model: installed tools that are also on the allowlist, in allowlist order.241    public func definitions(allowed: [String]) -> [ToolDefinition] {242        var seen = Set<String>()243        return allowed.compactMap { name in seen.insert(name).inserted ? tools[name]?.definition : nil }244    }245246    /// Resolves a call by name. A tool outside the allowlist is reported exactly like a tool that does not exist.247    public func resolve(_ name: String, allowed: [String]) throws -> any AgentTool {248        guard allowed.contains(name), let tool = tools[name] else {249            let available = definitions(allowed: allowed).map(\.name)250            let list = available.isEmpty ? "No tool is available." : "Available tools: " + available.joined(separator: ", ") + "."251            throw ToolError("The tool “\(String(name.prefix(80)))” is not available to this agent. \(list)")252        }253        return tool254    }255256    /// The built-in set. Tools that depend on an app service are installed only when that service is supplied.257    public static func standard(documents: (any DocumentSearching)? = nil, files: (any FileAccessing)? = nil, web: (any WebFetching)? = nil,258                                webPolicy: WebHostPolicy = WebHostPolicy(), now: @escaping @Sendable () -> Date = { Date() },259                                defaultTimeZone: TimeZone = .current, conversations: (any ConversationSearching)? = nil,260                                memory: (any MemoryStoring)? = nil, search: (any WebSearching)? = nil) -> ToolRegistry {261        var registry = ToolRegistry([262            CalculatorTool(), DateTimeTool(now: now, defaultTimeZone: defaultTimeZone), DataTransformTool(),263            TextStatsTool(), RegexExtractTool(), UnitConvertTool(),264        ])265        if let documents { registry.register(DocumentSearchTool(documents: documents)) }266        if let files { registry.register(ReadFileTool(files: files)); registry.register(WriteFileTool(files: files)) }267        if let web { registry.register(WebFetchTool(fetcher: web, policy: webPolicy)) }268        if let search { registry.register(WebSearchTool(search: search)) }269        if let conversations { registry.register(ConversationSearchTool(conversations: conversations)) }270        if let memory { registry.register(MemorySearchTool(memory: memory)); registry.register(RememberTool(memory: memory)) }271        return registry272    }273}274275/// There is deliberately no code-execution tool.276public enum CodeExecutionPolicy {277    public static let explanation = """278    ORIX Astra does not run arbitrary code. iOS apps may not download and execute code, spawn processes or open a shell, and an agent \279    that could would be able to act outside what you approved. Two limited evaluators are provided instead: “calculator” evaluates \280    arithmetic expressions with a fixed grammar and a fixed function list, and “data_transform” applies a fixed set of table operations \281    (select, filter, sort, group, aggregate) to CSV or JSON text. Neither can read files, reach the network or define new behaviour.282    """283}284285// MARK: - Argument helpers286287extension JSONValue {288    /// An integer only when the value is a whole number that fits; never traps on huge values.289    var exactInt: Int? {290        guard case .number(let n) = self, n.isFinite, n.rounded() == n, abs(n) < 9_007_199_254_740_992 else { return nil }291        return Int(n)292    }293    var number: Double? { if case .number(let n) = self { return n }; return nil }294}295
Files main
Menu

Theme