Repository Public
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 public init(_ message: String) { self.message = message }110 public var errorDescription: String? { message }111}112113public struct ToolOutput: Sendable, Hashable, Codable {114 public var text: String115 public var isError: Bool116 public var truncated: Bool117 public init(_ text: String, isError: Bool = false, truncated: Bool = false) {118 self.text = text; self.isError = isError; self.truncated = truncated119 }120}121122public struct ToolContext: Sendable, Hashable {123 public var runID: UUID124 public var callID: String125 /// Upper bound the runner applies to the result; tools may use it to stop early.126 public var maxOutputCharacters: Int127 public init(runID: UUID = UUID(), callID: String = "call", maxOutputCharacters: Int = OutputLimiter.defaultMaxCharacters) {128 self.runID = runID; self.callID = callID; self.maxOutputCharacters = maxOutputCharacters129 }130}131132/// One capability an agent may be given. Tools never spawn processes, never evaluate code and never touch file paths themselves.133public protocol AgentTool: Sendable {134 var definition: ToolDefinition { get }135 var risk: ToolRisk { get }136 /// Cheap checks that must fail before the user is asked anything (for example a URL that can never be fetched).137 func preflight(_ arguments: JSONValue) throws138 /// Narrows an "allow for this run" grant (the host for `web_fetch`); nil means the grant covers the whole tool.139 func approvalScope(_ arguments: JSONValue) -> String?140 /// One human-readable line for the approval sheet; nil lets the runtime build one from the arguments.141 func approvalSummary(_ arguments: JSONValue) -> String?142 func run(_ arguments: JSONValue, context: ToolContext) async throws -> ToolOutput143}144145public extension AgentTool {146 var name: String { definition.name }147 func preflight(_ arguments: JSONValue) throws {}148 func approvalScope(_ arguments: JSONValue) -> String? { nil }149 func approvalSummary(_ arguments: JSONValue) -> String? { nil }150}151152/// Caps text handed back to a model and marks the cut so neither the model nor the reader mistakes it for the whole.153public enum OutputLimiter {154 public static let defaultMaxCharacters = 12_000155 public static let markerPrefix = "[… output truncated:"156157 public static func cap(_ text: String, maxCharacters: Int) -> (text: String, truncated: Bool) {158 let limit = max(64, maxCharacters)159 guard text.count > limit else { return (text, false) }160 let total = text.count161 return (String(text.prefix(limit)) + "\n\(markerPrefix) \(limit) of \(total) characters shown]", true)162 }163164 public static func cap(_ output: ToolOutput, maxCharacters: Int) -> ToolOutput {165 let capped = cap(output.text, maxCharacters: maxCharacters)166 return ToolOutput(capped.text, isError: output.isError, truncated: output.truncated || capped.truncated)167 }168}169170/// 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.171public struct ToolRegistry: Sendable {172 private var tools: [String: any AgentTool] = [:]173 public private(set) var names: [String] = []174175 public init(_ tools: [any AgentTool] = []) { for tool in tools { register(tool) } }176177 public mutating func register(_ tool: any AgentTool) {178 if tools[tool.name] == nil { names.append(tool.name) }179 tools[tool.name] = tool180 }181182 public func tool(named name: String) -> (any AgentTool)? { tools[name] }183184 /// Definitions offered to the model: installed tools that are also on the allowlist, in allowlist order.185 public func definitions(allowed: [String]) -> [ToolDefinition] {186 var seen = Set<String>()187 return allowed.compactMap { name in seen.insert(name).inserted ? tools[name]?.definition : nil }188 }189190 /// Resolves a call by name. A tool outside the allowlist is reported exactly like a tool that does not exist.191 public func resolve(_ name: String, allowed: [String]) throws -> any AgentTool {192 guard allowed.contains(name), let tool = tools[name] else {193 let available = definitions(allowed: allowed).map(\.name)194 let list = available.isEmpty ? "No tool is available." : "Available tools: " + available.joined(separator: ", ") + "."195 throw ToolError("The tool “\(String(name.prefix(80)))” is not available to this agent. \(list)")196 }197 return tool198 }199200 /// The built-in set. Tools that depend on an app service are installed only when that service is supplied.201 public static func standard(documents: (any DocumentSearching)? = nil, files: (any FileAccessing)? = nil, web: (any WebFetching)? = nil,202 webPolicy: WebHostPolicy = WebHostPolicy(), now: @escaping @Sendable () -> Date = { Date() },203 defaultTimeZone: TimeZone = .current) -> ToolRegistry {204 var registry = ToolRegistry([205 CalculatorTool(), DateTimeTool(now: now, defaultTimeZone: defaultTimeZone), DataTransformTool(),206 TextStatsTool(), RegexExtractTool(), UnitConvertTool(),207 ])208 if let documents { registry.register(DocumentSearchTool(documents: documents)) }209 if let files { registry.register(ReadFileTool(files: files)); registry.register(WriteFileTool(files: files)) }210 if let web { registry.register(WebFetchTool(fetcher: web, policy: webPolicy)) }211 return registry212 }213}214215/// There is deliberately no code-execution tool.216public enum CodeExecutionPolicy {217 public static let explanation = """218 ORIX Astra does not run arbitrary code. iOS apps may not download and execute code, spawn processes or open a shell, and an agent \219 that could would be able to act outside what you approved. Two limited evaluators are provided instead: “calculator” evaluates \220 arithmetic expressions with a fixed grammar and a fixed function list, and “data_transform” applies a fixed set of table operations \221 (select, filter, sort, group, aggregate) to CSV or JSON text. Neither can read files, reach the network or define new behaviour.222 """223}224225// MARK: - Argument helpers226227extension JSONValue {228 /// An integer only when the value is a whole number that fits; never traps on huge values.229 var exactInt: Int? {230 guard case .number(let n) = self, n.isFinite, n.rounded() == n, abs(n) < 9_007_199_254_740_992 else { return nil }231 return Int(n)232 }233 var number: Double? { if case .number(let n) = self { return n }; return nil }234}235