SPB Git

Repository Public MIT

AgentModel.swift 21.0 KB 418 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraAgents/Sources/AgentModel.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// MARK: - Profile and budgets9293public enum BudgetKind: String, Sendable, Codable, Hashable, CaseIterable {94    case steps, toolCalls, tokens, cost, wallClock9596    public var label: String {97        switch self {98        case .steps: "step limit"99        case .toolCalls: "tool call limit"100        case .tokens: "token limit"101        case .cost: "cost limit"102        case .wallClock: "time limit"103        }104    }105}106107/// Hard limits of one run. All of them are enforced by the runner; nothing a model writes can change them.108public struct AgentBudgets: Sendable, Codable, Hashable {109    /// Model turns.110    public var maxSteps: Int111    /// Tool calls requested by the model (executed, refused or denied alike). `update_plan` does not count.112    public var maxToolCalls: Int113    public var maxOutputTokensPerTurn: Int?114    /// Input plus output tokens over the whole run, enforced when the provider reports usage.115    public var maxTotalTokens: Int?116    /// Enforced when the cost is known (provider-reported, or usage × published price). Never enforced against a guess.117    public var maxTotalCostUSD: Double?118    /// Seconds of wall-clock time, counted across resumes.119    public var wallClockLimit: TimeInterval?120    /// Characters of one tool result handed to the model.121    public var maxToolOutputCharacters: Int122    /// The same call (tool and normalised arguments) this many times in a row is a cycle.123    public var repeatLimit: Int124    /// A-B-A-B… alternation of two calls repeated this many times is a cycle (2 = A-B-A-B).125    public var alternationLimit: Int126    /// Share of a budget at which `budgetWarning` is emitted.127    public var warningFraction: Double128    /// Seconds a model turn may go without producing anything before the run is ended as stalled. Nil = no limit.129    public var stallTimeout: TimeInterval?130131    public init(maxSteps: Int = 12, maxToolCalls: Int = 30, maxOutputTokensPerTurn: Int? = 2_048, maxTotalTokens: Int? = nil,132                maxTotalCostUSD: Double? = nil, wallClockLimit: TimeInterval? = 600, maxToolOutputCharacters: Int = OutputLimiter.defaultMaxCharacters,133                repeatLimit: Int = 3, alternationLimit: Int = 2, warningFraction: Double = 0.8, stallTimeout: TimeInterval? = 180) {134        self.stallTimeout = stallTimeout.flatMap { $0.isFinite ? max(0.05, $0) : nil }135        self.maxSteps = max(1, maxSteps); self.maxToolCalls = max(0, maxToolCalls); self.maxOutputTokensPerTurn = maxOutputTokensPerTurn136        self.maxTotalTokens = maxTotalTokens; self.maxTotalCostUSD = maxTotalCostUSD; self.wallClockLimit = wallClockLimit137        self.maxToolOutputCharacters = max(256, maxToolOutputCharacters); self.repeatLimit = max(2, repeatLimit)138        self.alternationLimit = max(2, alternationLimit); self.warningFraction = min(1, max(0.1, warningFraction))139    }140141    /// Decoding goes through the clamping initialiser: a stored, imported or synchronised value can never hold a limit the142    /// runner's arithmetic does not expect.143    public init(from decoder: Decoder) throws {144        let c = try decoder.container(keyedBy: CodingKeys.self)145        let d = AgentBudgets()146        func finite(_ v: Double?) -> Double? { v.flatMap { $0.isFinite ? $0 : nil } }147        self.init(maxSteps: try c.decodeIfPresent(Int.self, forKey: .maxSteps) ?? d.maxSteps,148                  maxToolCalls: try c.decodeIfPresent(Int.self, forKey: .maxToolCalls) ?? d.maxToolCalls,149                  maxOutputTokensPerTurn: try c.decodeIfPresent(Int.self, forKey: .maxOutputTokensPerTurn).map { max(1, $0) },150                  maxTotalTokens: try c.decodeIfPresent(Int.self, forKey: .maxTotalTokens).map { max(1, $0) },151                  maxTotalCostUSD: finite(try c.decodeIfPresent(Double.self, forKey: .maxTotalCostUSD)).map { max(0, $0) },152                  wallClockLimit: finite(try c.decodeIfPresent(Double.self, forKey: .wallClockLimit)).map { max(1, $0) },153                  maxToolOutputCharacters: try c.decodeIfPresent(Int.self, forKey: .maxToolOutputCharacters) ?? d.maxToolOutputCharacters,154                  repeatLimit: try c.decodeIfPresent(Int.self, forKey: .repeatLimit) ?? d.repeatLimit,155                  alternationLimit: try c.decodeIfPresent(Int.self, forKey: .alternationLimit) ?? d.alternationLimit,156                  warningFraction: finite(try c.decodeIfPresent(Double.self, forKey: .warningFraction)) ?? d.warningFraction,157                  stallTimeout: c.contains(.stallTimeout) ? finite(try c.decodeIfPresent(Double.self, forKey: .stallTimeout)) : d.stallTimeout)158    }159}160161/// What an agent is and what it may do. The allowlist and the budgets are the only source of permissions.162public struct AgentProfile: Sendable, Codable, Hashable, Identifiable {163    public var id: String164    public var name: String165    public var instructions: String166    public var model: ModelRef167    /// Names of registry tools this agent may call. Anything else is refused in code.168    public var allowedTools: [String]169    public var budgets: AgentBudgets170    /// Hosts `web_fetch` may reach without asking (exact host names). A URL flagged as possible exfiltration still asks.171    public var preApprovedWebHosts: [String]172    public var parameters: GenerationParameters173    /// Offers the built-in `update_plan` tool.174    public var planningEnabled: Bool175    /// When set, older turns are dropped (whole tool exchanges at a time) so the request fits this many tokens.176    public var contextWindow: Int?177    /// How much the agent may do without asking.178    public var autonomy: AutonomyProfile179    /// Whether it may hand subtasks to sub-agents.180    public var delegation: DelegationPolicy181182    public init(id: String = UUID().uuidString, name: String, instructions: String = "", model: ModelRef, allowedTools: [String] = [],183                budgets: AgentBudgets = AgentBudgets(), preApprovedWebHosts: [String] = [], parameters: GenerationParameters = .default,184                planningEnabled: Bool = true, contextWindow: Int? = nil, autonomy: AutonomyProfile = .balanced,185                delegation: DelegationPolicy = DelegationPolicy()) {186        self.id = id; self.name = name; self.instructions = instructions; self.model = model; self.allowedTools = allowedTools187        self.budgets = budgets; self.preApprovedWebHosts = preApprovedWebHosts; self.parameters = parameters188        self.planningEnabled = planningEnabled; self.contextWindow = contextWindow; self.autonomy = autonomy; self.delegation = delegation189    }190191    /// A profile saved before autonomy and delegation existed reads as balanced, without delegation.192    public init(from decoder: Decoder) throws {193        let c = try decoder.container(keyedBy: CodingKeys.self)194        self.init(id: try c.decode(String.self, forKey: .id), name: try c.decode(String.self, forKey: .name),195                  instructions: try c.decodeIfPresent(String.self, forKey: .instructions) ?? "", model: try c.decode(ModelRef.self, forKey: .model),196                  allowedTools: try c.decodeIfPresent([String].self, forKey: .allowedTools) ?? [],197                  budgets: try c.decodeIfPresent(AgentBudgets.self, forKey: .budgets) ?? AgentBudgets(),198                  preApprovedWebHosts: try c.decodeIfPresent([String].self, forKey: .preApprovedWebHosts) ?? [],199                  parameters: try c.decodeIfPresent(GenerationParameters.self, forKey: .parameters) ?? .default,200                  planningEnabled: try c.decodeIfPresent(Bool.self, forKey: .planningEnabled) ?? true,201                  contextWindow: try c.decodeIfPresent(Int.self, forKey: .contextWindow),202                  autonomy: try c.decodeIfPresent(AutonomyProfile.self, forKey: .autonomy) ?? .balanced,203                  delegation: try c.decodeIfPresent(DelegationPolicy.self, forKey: .delegation) ?? DelegationPolicy())204    }205}206207// MARK: - Plan208209public struct AgentPlan: Sendable, Codable, Hashable {210    public enum Status: String, Sendable, Codable, CaseIterable { case pending, inProgress = "in_progress", done, skipped, failed }211    public struct Step: Sendable, Codable, Hashable, Identifiable {212        public var id: Int213        public var title: String214        public var status: Status215        public init(id: Int, title: String, status: Status = .pending) { self.id = id; self.title = title; self.status = status }216    }217    public var steps: [Step]218    public init(steps: [Step] = []) { self.steps = steps }219    public var completedCount: Int { steps.filter { $0.status == .done || $0.status == .skipped }.count }220}221222/// The built-in planning tool. It is handled by the runner (it changes run state, not user data) and never needs approval.223public enum PlanTool {224    public static let name = "update_plan"225    public static let definition = ToolDefinition(226        name: name,227        summary: "Records or updates your plan for this task as an explicit list of steps with statuses. Send the whole list each time: that is how "228            + "you add, remove, reorder or reword steps as you learn more. Mark a step failed when it cannot be done, then change the plan. "229            + "Use it for tasks with several steps; keep exactly one step in_progress.",230        parameters: [231            "type": "object",232            "properties": [233                "steps": [234                    "type": "array", "minItems": 1, "maxItems": 30,235                    "items": [236                        "type": "object",237                        "properties": [238                            "title": ["type": "string", "minLength": 1, "maxLength": 200],239                            "status": ["type": "string", "enum": ["pending", "in_progress", "done", "skipped", "failed"]],240                        ],241                        "required": ["title", "status"],242                        "additionalProperties": false,243                    ],244                ],245            ],246            "required": ["steps"],247            "additionalProperties": false,248        ])249250    static func plan(from arguments: JSONValue) throws -> AgentPlan {251        try SchemaValidator.validate(arguments: arguments, for: definition)252        let steps = (arguments["steps"]?.arrayValue ?? []).enumerated().map { i, item in253            AgentPlan.Step(id: i + 1, title: item["title"]?.stringValue ?? "", status: item["status"]?.stringValue.flatMap(AgentPlan.Status.init(rawValue:)) ?? .pending)254        }255        return AgentPlan(steps: steps)256    }257}258259// MARK: - Usage and cost260261/// Cost of the run so far, built only from real usage reports. A turn whose cost cannot be established makes the total unknown.262public struct CostLedger: Sendable, Codable, Hashable {263    /// Sum of the turns whose cost is known: a lower bound of the real total.264    public private(set) var knownUSD: Double = 0265    public private(set) var knownTurns = 0266    public private(set) var unknownTurns = 0267    public private(set) var onDeviceTurns = 0268    public private(set) var estimatedTurns = 0269    public private(set) var pricingAsOf: String?270    public init() {}271272    public mutating func add(_ cost: CostEstimate) {273        switch cost.basis {274        case .onDevice: onDeviceTurns += 1275        case .unavailable: unknownTurns += 1276        default:277            guard let amount = cost.amountUSD else { unknownTurns += 1; return }278            knownUSD += amount; knownTurns += 1279            if cost.basis != .reportedByProvider { estimatedTurns += 1 }280            pricingAsOf = cost.pricingAsOf ?? pricingAsOf281        }282    }283284    public var isComplete: Bool { unknownTurns == 0 }285286    /// Adds the turns of a sub-agent to this ledger.287    public mutating func absorb(_ other: CostLedger) {288        knownUSD += other.knownUSD; knownTurns += other.knownTurns; unknownTurns += other.unknownTurns289        onDeviceTurns += other.onDeviceTurns; estimatedTurns += other.estimatedTurns; pricingAsOf = other.pricingAsOf ?? pricingAsOf290    }291292    /// The total as it may be shown: unknown stays unknown, it is never reported as zero.293    public var total: CostEstimate {294        if unknownTurns > 0 || knownTurns + onDeviceTurns == 0 { return .unavailable }295        if knownTurns == 0 { return .onDevice }296        return CostEstimate(amountUSD: knownUSD, basis: estimatedTurns > 0 ? .estimatedFromUsage : .reportedByProvider, pricingAsOf: pricingAsOf)297    }298}299300extension TokenUsage {301    /// Adds two per-turn reports. A field nobody reported stays nil.302    func adding(_ other: TokenUsage) -> TokenUsage {303        func sum(_ a: Int?, _ b: Int?) -> Int? { a == nil && b == nil ? nil : (a ?? 0) + (b ?? 0) }304        let cost: Double? = reportedCostUSD == nil && other.reportedCostUSD == nil ? nil : (reportedCostUSD ?? 0) + (other.reportedCostUSD ?? 0)305        return TokenUsage(inputTokens: sum(inputTokens, other.inputTokens), outputTokens: sum(outputTokens, other.outputTokens),306                          cachedInputTokens: sum(cachedInputTokens, other.cachedInputTokens), cacheWriteTokens: sum(cacheWriteTokens, other.cacheWriteTokens),307                          reasoningTokens: sum(reasoningTokens, other.reasoningTokens), reportedCostUSD: cost)308    }309}310311// MARK: - Events312313public enum AgentRunStatus: Sendable, Codable, Hashable {314    case completed315    /// Cancelled by the person.316    case stopped317    case budgetExceeded(BudgetKind)318    case failed(String)319    case cycleDetected(String)320321    public var label: String {322        switch self {323        case .completed: "Completed"324        case .stopped: "Stopped"325        case .budgetExceeded(let kind): "Stopped at the \(kind.label)"326        case .failed(let message): "Failed: \(message)"327        case .cycleDetected(let message): "Stopped: \(message)"328        }329    }330}331332public struct AgentRunInfo: Sendable, Codable, Hashable {333    public var runID: UUID334    public var profileID: String335    public var profileName: String336    public var goal: String337    public var model: ModelRef338    /// Tools actually offered to the model in this run (allowlist ∩ installed, plus `update_plan` when enabled).339    public var tools: [String]340    /// Steps already completed when this run resumed from a checkpoint; 0 for a fresh run.341    public var resumedAfterStep: Int342    public var startedAt: Date343}344345public struct BudgetWarning: Sendable, Codable, Hashable {346    public var kind: BudgetKind347    public var message: String348    public init(kind: BudgetKind, message: String) { self.kind = kind; self.message = message }349}350351/// The audit timeline of a run. Tool arguments and outputs in these events are redacted; text deltas are the model's own words.352public indirect enum AgentEvent: Sendable, Hashable {353    case runStarted(AgentRunInfo)354    case stepStarted(Int)355    case modelTextDelta(String)356    case planUpdated(AgentPlan)357    /// The call as the model made it (arguments redacted), before any check.358    case toolRequested(ToolCall)359    case approvalRequested(ApprovalRequest)360    case approvalResolved(callID: String, decision: ApprovalDecision)361    case toolStarted(callID: String, name: String)362    /// `output` is what the model receives, minus the envelope, redacted. `flagged` lists suspicious instructions found in it.363    case toolFinished(callID: String, name: String, output: String, isError: Bool, flagged: [InjectionFinding])364    /// Totals so far. `cost` is `.unavailable` whenever any turn's cost is unknown.365    case usage(total: TokenUsage, cost: CostEstimate)366    case budgetWarning(BudgetWarning)367    case checkpointSaved(AgentCheckpoint)368    /// A tool call failed in a way that may not repeat and is being made again (idempotent tools only, once).369    case toolRetried(callID: String, name: String, reason: String)370    /// A sub-agent was started by a `delegate` call. `id` identifies it in the events that follow.371    case delegateStarted(id: String, role: DelegateRole, task: String)372    /// Something a sub-agent did: its own timeline, one level down.373    case delegateEvent(id: String, event: AgentEvent)374    case delegateFinished(id: String, role: DelegateRole, status: AgentRunStatus, report: String)375    case runFinished(status: AgentRunStatus, finalText: String)376}377378// MARK: - Checkpoint379380/// Everything needed to continue a run after the app was closed. Saved after every completed step; persist the latest one.381/// Permissions are not restored from here: the profile passed to the resumed run decides which tools exist.382public struct AgentCheckpoint: Sendable, Codable, Hashable {383    public static let currentVersion = 1384    public var version: Int385    public var runID: UUID386    public var profileID: String387    public var goal: String388    public var messages: [PromptMessage]389    public var step: Int390    public var toolCalls: Int391    public var usage: TokenUsage392    public var cost: CostLedger393    public var plan: AgentPlan?394    public var grants: ApprovalGrants395    /// Signatures of the latest tool calls, for cycle detection across a resume.396    public var recentCalls: [String]397    public var sawFlaggedContent: Bool398    public var elapsed: TimeInterval399    public var savedAt: Date400    /// True when the run had already produced its final answer.401    public var isComplete: Bool402    /// Set in the checkpoint saved just before a call that is not idempotent starts. If the app is closed while it runs, the403    /// resumed run knows that call may have taken effect and does not make it again.404    public var inFlightCallID: String?405406    public func encoded() throws -> Data {407        let encoder = JSONEncoder()408        encoder.outputFormatting = [.sortedKeys]409        return try encoder.encode(self)410    }411412    public static func decode(_ data: Data) throws -> AgentCheckpoint {413        let checkpoint = try JSONDecoder().decode(AgentCheckpoint.self, from: data)414        guard checkpoint.version <= currentVersion else { throw AstraError.unsupported("This run was saved by a newer version of the app.") }415        return checkpoint416    }417}418
Files main
Menu

Theme