SPB Git

Repository Public MIT

AgentSupport.swift 18.6 KB 415 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraUI/Sources/Agents/AgentSupport.swift10// Module           : Agents11// 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 SwiftUI90import AstraCore91import AstraAgents92import AstraPersistence93import AstraDesign9495// The runtime and the store both define a run status and an approval decision; these names keep the two apart.96typealias AgentOutcome = AstraAgents.AgentRunStatus97typealias AgentStoredStatus = AstraPersistence.AgentRunStatus98typealias AgentDecision = AstraAgents.ApprovalDecision99typealias AgentStoredDecision = AstraPersistence.ApprovalDecision100101// MARK: - Tool catalogue102103/// What the editor and the timeline say about one tool. The risk comes from the runtime's own tool, never from this table.104struct AgentToolInfo: Identifiable, Sendable, Hashable {105    let name: String106    let title: String107    /// One plain sentence about what the tool can touch.108    let touches: String109    let symbol: String110    let risk: ToolRisk111    var id: String { name }112}113114enum AgentToolCatalog {115    // Stand-ins used only to read each tool's name and risk from the runtime; they are never handed to a run.116    private struct NoDocuments: DocumentSearching {117        func search(_ query: String, limit: Int) async throws -> [DocumentHit] { [] }118    }119    private struct NoFiles: FileAccessing {120        func grantedItems() async throws -> [GrantedItem] { [] }121        func readText(itemID: String, maxBytes: Int) async throws -> FileText { throw ToolError("No file is shared.") }122        func proposeWrite(fileName: String, text: String) async throws -> FileWriteResult { .cancelled }123    }124    private struct NoWeb: WebFetching {125        func fetch(_ request: WebFetchRequest) async throws -> WebFetchResponse { throw ToolError("Web access is off.") }126    }127    private struct NoConversations: ConversationSearching {128        func search(_ query: String, limit: Int) async throws -> [ConversationHit] { [] }129    }130    private struct NoMemory: MemoryStoring {131        func memories(matching query: String?, limit: Int) async throws -> [MemoryItem] { [] }132        func save(_ text: String, runID: UUID) async throws {}133    }134    private struct NoSearch: WebSearching {135        let serviceName = TavilySearch.name, serviceHost = TavilySearch.host136        func search(_ query: String, limit: Int) async throws -> [WebSearchResult] { [] }137    }138139    private static let copy: [String: (title: String, touches: String, symbol: String)] = [140        "calculator": ("Calculator", "Evaluates arithmetic expressions exactly. It touches nothing on your iPhone.", "plus.forwardslash.minus"),141        "datetime": ("Date and time", "Reads this iPhone's current date, time and time zone, and does date arithmetic. Nothing else.", "calendar.badge.clock"),142        "data_transform": ("Table operations", "Filters, sorts, groups and totals CSV or JSON text the agent already has. It cannot open files or reach the network.", "tablecells"),143        "text_stats": ("Text statistics", "Counts words, sentences and characters in text the agent already has.", "textformat.123"),144        "regex_extract": ("Pattern extraction", "Finds patterns such as dates or amounts in text the agent already has, under a time limit.", "text.magnifyingglass"),145        "unit_convert": ("Unit conversion", "Converts lengths, masses, temperatures, volumes, data sizes and durations.", "arrow.left.arrow.right"),146        "document_search": ("Search your documents", "Reads passages from the documents you imported in Knowledge. It asks you once per run. With a cloud model, the passages it finds are sent to that provider.", "doc.text.magnifyingglass"),147        "read_file": ("Read shared files", "Reads only the files you share with a run. It cannot browse your iPhone. It asks you once per run.", "doc.viewfinder"),148        "write_file": ("Save a new file", "Proposes a new file. You approve the content, then choose where to save it in Files. Nothing is overwritten silently.", "square.and.arrow.down"),149        "conversation_search": ("Search your conversations", "Reads excerpts of your earlier conversations in this app. With a cloud model, the excerpts it finds are sent to that provider.", "bubble.left.and.text.bubble.right"),150        "memory_search": ("Read your memories", "Reads what you asked this app to remember.", "brain"),151        "remember": ("Propose a memory", "Proposes one short note to keep for later conversations. You see the exact sentence and decide; nothing is stored otherwise.", "brain.head.profile"),152        "web_search": ("Search the web", "Sends a search query to Tavily with your own key and returns result titles, addresses and excerpts. Never put private information in a query.", "magnifyingglass"),153        "web_fetch": ("Fetch a web page", "Downloads one public https page. The address is sent to that website. It asks you for every website you did not pre-approve.", "globe"),154    ]155156    /// Every tool the app can install, in the runtime's order.157    static let all: [AgentToolInfo] = {158        let registry = ToolRegistry.standard(documents: NoDocuments(), files: NoFiles(), web: NoWeb(), conversations: NoConversations(),159                                             memory: NoMemory(), search: NoSearch())160        return registry.names.compactMap { name in161            guard let tool = registry.tool(named: name) else { return nil }162            let text = copy[name]163            return AgentToolInfo(name: name, title: text?.title ?? name, touches: text?.touches ?? tool.definition.summary,164                                 symbol: text?.symbol ?? "wrench.and.screwdriver", risk: tool.risk)165        }166    }()167168    static func info(_ name: String) -> AgentToolInfo? { all.first { $0.name == name } }169    static func title(_ name: String) -> String { name == PlanTool.name ? "Plan" : name == DelegateTool.name ? "Sub-agents" : (info(name)?.title ?? name) }170    static func symbol(_ name: String) -> String {171        name == PlanTool.name ? "list.bullet.clipboard" : name == DelegateTool.name ? "person.2.badge.gearshape" : (info(name)?.symbol ?? "wrench.and.screwdriver")172    }173174    /// Tools grouped by risk, lowest first; empty groups are left out.175    static var grouped: [(risk: ToolRisk, tools: [AgentToolInfo])] {176        ToolRisk.allCases.compactMap { risk in177            let tools = all.filter { $0.risk == risk }178            return tools.isEmpty ? nil : (risk, tools)179        }180    }181}182183extension ToolRisk {184    var tone: AstraBadge.Tone {185        switch self {186        case .safe: .success187        case .readsUserData: .cyan188        case .writesUserData, .sendsDataExternally: .warning189        case .destructive: .danger190        }191    }192    var symbol: String {193        switch self {194        case .safe: "checkmark.shield"195        case .readsUserData: "eye"196        case .writesUserData: "square.and.pencil"197        case .sendsDataExternally: "arrow.up.right.circle"198        case .destructive: "exclamationmark.triangle"199        }200    }201    /// How the approval policy treats this risk, in the person's words.202    var approvalRule: String {203        switch self {204        case .safe: "Never asks: these tools cannot reach your data or the network."205        case .readsUserData: "Asks you the first time in each run."206        case .writesUserData: "Asks you every time."207        case .sendsDataExternally: "Asks you every time, per website."208        case .destructive: "Asks you every time."209        }210    }211}212213// MARK: - Profile ⇄ record214215/// The parts of a profile the store's profile row has no column for. Saved in settings under the profile's id.216struct AgentProfileExtras: Codable, Sendable, Hashable {217    var maxTotalTokens: Int?218    var wallClockLimit: TimeInterval?219    var preApprovedWebHosts: [String]220    var planningEnabled: Bool221    var autonomy: AutonomyProfile222    var delegation: DelegationPolicy223224    init(maxTotalTokens: Int? = nil, wallClockLimit: TimeInterval? = 600, preApprovedWebHosts: [String] = [], planningEnabled: Bool = true,225         autonomy: AutonomyProfile = .balanced, delegation: DelegationPolicy = DelegationPolicy()) {226        self.maxTotalTokens = maxTotalTokens; self.wallClockLimit = wallClockLimit227        self.preApprovedWebHosts = preApprovedWebHosts; self.planningEnabled = planningEnabled228        self.autonomy = autonomy; self.delegation = delegation229    }230231    /// Extras saved by builds before 2.0 have neither autonomy nor delegation: they read as balanced, without sub-agents.232    init(from decoder: Decoder) throws {233        let c = try decoder.container(keyedBy: CodingKeys.self)234        maxTotalTokens = try c.decodeIfPresent(Int.self, forKey: .maxTotalTokens)235        wallClockLimit = try c.decodeIfPresent(TimeInterval.self, forKey: .wallClockLimit)236        preApprovedWebHosts = try c.decodeIfPresent([String].self, forKey: .preApprovedWebHosts) ?? []237        planningEnabled = try c.decodeIfPresent(Bool.self, forKey: .planningEnabled) ?? true238        autonomy = try c.decodeIfPresent(AutonomyProfile.self, forKey: .autonomy) ?? .balanced239        delegation = try c.decodeIfPresent(DelegationPolicy.self, forKey: .delegation) ?? DelegationPolicy()240    }241242    static func key(_ profileID: String) -> String { "agents.profile.extras." + profileID }243}244245extension AgentProfile {246    init(record: AgentProfileRecord, extras: AgentProfileExtras) {247        self.init(id: record.id, name: record.name, instructions: record.instructions, model: record.model, allowedTools: record.allowedTools,248                  budgets: AgentBudgets(maxSteps: record.maxSteps, maxToolCalls: record.maxToolCalls, maxOutputTokensPerTurn: record.maxOutputTokens,249                                        maxTotalTokens: extras.maxTotalTokens, maxTotalCostUSD: record.maxCostUSD, wallClockLimit: extras.wallClockLimit),250                  preApprovedWebHosts: extras.preApprovedWebHosts, planningEnabled: extras.planningEnabled,251                  autonomy: extras.autonomy, delegation: extras.delegation)252    }253254    func record(createdAt: Date = Date()) -> AgentProfileRecord {255        AgentProfileRecord(id: id, name: name, instructions: instructions, model: model, allowedTools: allowedTools, maxSteps: budgets.maxSteps,256                           maxToolCalls: budgets.maxToolCalls, maxOutputTokens: budgets.maxOutputTokensPerTurn ?? 2_048,257                           maxCostUSD: budgets.maxTotalCostUSD, createdAt: createdAt)258    }259260    var extras: AgentProfileExtras {261        AgentProfileExtras(maxTotalTokens: budgets.maxTotalTokens, wallClockLimit: budgets.wallClockLimit,262                           preApprovedWebHosts: preApprovedWebHosts, planningEnabled: planningEnabled, autonomy: autonomy, delegation: delegation)263    }264265    var usesFiles: Bool { allowedTools.contains("read_file") || allowedTools.contains("write_file") }266    var usesWeb: Bool { allowedTools.contains("web_fetch") }267    var usesSearch: Bool { allowedTools.contains("web_search") }268    var usesMemory: Bool { allowedTools.contains("memory_search") || allowedTools.contains("remember") }269}270271// MARK: - Labels272273extension AgentStoredStatus {274    var label: String {275        switch self {276        case .running: "Running"277        case .awaitingApproval: "Waiting for approval"278        case .completed: "Completed"279        case .failed: "Failed"280        case .cancelled: "Stopped"281        case .budgetExceeded: "Budget reached"282        }283    }284    var tone: AstraBadge.Tone {285        switch self {286        case .running: .accent287        case .awaitingApproval, .budgetExceeded: .warning288        case .completed: .success289        case .failed: .danger290        case .cancelled: .neutral291        }292    }293    var symbol: String {294        switch self {295        case .running: "play.circle"296        case .awaitingApproval: "hand.raised"297        case .completed: "checkmark.circle"298        case .failed: "xmark.octagon"299        case .cancelled: "stop.circle"300        case .budgetExceeded: "gauge.with.dots.needle.67percent"301        }302    }303}304305extension AgentOutcome {306    var tone: AstraBadge.Tone {307        switch self {308        case .completed: .success309        case .stopped: .neutral310        case .budgetExceeded, .cycleDetected: .warning311        case .failed: .danger312        }313    }314    var symbol: String {315        switch self {316        case .completed: "checkmark.circle.fill"317        case .stopped: "stop.circle.fill"318        case .budgetExceeded: "gauge.with.dots.needle.67percent"319        case .cycleDetected: "arrow.triangle.2.circlepath"320        case .failed: "xmark.octagon.fill"321        }322    }323    var noticeKind: NoticeCard.Kind {324        switch self {325        case .completed: .success326        case .stopped: .info327        case .budgetExceeded, .cycleDetected: .warning328        case .failed: .error329        }330    }331    /// The store's coarser status for the same outcome.332    var stored: AgentStoredStatus {333        switch self {334        case .completed: .completed335        case .stopped: .cancelled336        case .budgetExceeded: .budgetExceeded337        case .failed, .cycleDetected: .failed338        }339    }340}341342extension AgentDecision {343    var label: String {344        switch self {345        case .allowOnce: return "Allowed once"346        case .allowForRun: return "Allowed for this run"347        case .deny(let reason):348            let trimmed = reason?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""349            return trimmed.isEmpty ? "Denied" : "Denied: \(trimmed)"350        }351    }352}353354extension AgentPlan.Status {355    var label: String {356        switch self {357        case .pending: "To do"358        case .inProgress: "In progress"359        case .done: "Done"360        case .skipped: "Skipped"361        case .failed: "Failed"362        }363    }364    var symbol: String {365        switch self {366        case .pending: "circle"367        case .inProgress: "circle.dotted.circle"368        case .done: "checkmark.circle.fill"369        case .skipped: "minus.circle"370        case .failed: "xmark.circle"371        }372    }373    var color: Color {374        switch self {375        case .pending: AstraColor.textTertiary376        case .inProgress: AstraColor.violet377        case .done: AstraColor.success378        case .skipped: AstraColor.textTertiary379        case .failed: AstraColor.danger380        }381    }382}383384enum AgentFormat {385    static func count(_ value: Int) -> String { value.formatted(.number.grouping(.automatic)) }386387    static func bytes(_ value: Int64) -> String { ByteCountFormatter.string(fromByteCount: value, countStyle: .file) }388389    /// "1:05", "12:40", "1:02:03".390    static func clock(_ seconds: TimeInterval) -> String {391        let total = max(0, Int(seconds.rounded()))392        let h = total / 3600, m = (total % 3600) / 60, s = total % 60393        return h > 0 ? String(format: "%d:%02d:%02d", h, m, s) : String(format: "%d:%02d", m, s)394    }395396    static func minutes(_ seconds: TimeInterval) -> String {397        let m = Int((seconds / 60).rounded())398        return m == 1 ? "1 minute" : "\(m) minutes"399    }400401    static func stamp(_ date: Date) -> String { date.formatted(date: .abbreviated, time: .shortened) }402403    /// Tokens used by a stored or live run, or nil when the model never reported any.404    static func tokens(_ usage: TokenUsage) -> String? { usage.totalTokens.map(count) }405}406407/// The transcript font size for agent text, scaled with Dynamic Type like the chat transcript.408struct AgentMarkdown: View {409    let text: String410    @ScaledMetric(relativeTo: .body) private var fontSize: CGFloat = 16411    var body: some View {412        MarkdownView(text: text).environment(\.transcriptFontSize, fontSize)413    }414}415
Files main
Menu

Theme