Repository Public
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: Double128129 public init(maxSteps: Int = 12, maxToolCalls: Int = 30, maxOutputTokensPerTurn: Int? = 2_048, maxTotalTokens: Int? = nil,130 maxTotalCostUSD: Double? = nil, wallClockLimit: TimeInterval? = 600, maxToolOutputCharacters: Int = OutputLimiter.defaultMaxCharacters,131 repeatLimit: Int = 3, alternationLimit: Int = 2, warningFraction: Double = 0.8) {132 self.maxSteps = max(1, maxSteps); self.maxToolCalls = max(0, maxToolCalls); self.maxOutputTokensPerTurn = maxOutputTokensPerTurn133 self.maxTotalTokens = maxTotalTokens; self.maxTotalCostUSD = maxTotalCostUSD; self.wallClockLimit = wallClockLimit134 self.maxToolOutputCharacters = max(256, maxToolOutputCharacters); self.repeatLimit = max(2, repeatLimit)135 self.alternationLimit = max(2, alternationLimit); self.warningFraction = min(1, max(0.1, warningFraction))136 }137138 /// Decoding goes through the clamping initialiser: a stored, imported or synchronised value can never hold a limit the139 /// runner's arithmetic does not expect.140 public init(from decoder: Decoder) throws {141 let c = try decoder.container(keyedBy: CodingKeys.self)142 let d = AgentBudgets()143 func finite(_ v: Double?) -> Double? { v.flatMap { $0.isFinite ? $0 : nil } }144 self.init(maxSteps: try c.decodeIfPresent(Int.self, forKey: .maxSteps) ?? d.maxSteps,145 maxToolCalls: try c.decodeIfPresent(Int.self, forKey: .maxToolCalls) ?? d.maxToolCalls,146 maxOutputTokensPerTurn: try c.decodeIfPresent(Int.self, forKey: .maxOutputTokensPerTurn).map { max(1, $0) },147 maxTotalTokens: try c.decodeIfPresent(Int.self, forKey: .maxTotalTokens).map { max(1, $0) },148 maxTotalCostUSD: finite(try c.decodeIfPresent(Double.self, forKey: .maxTotalCostUSD)).map { max(0, $0) },149 wallClockLimit: finite(try c.decodeIfPresent(Double.self, forKey: .wallClockLimit)).map { max(1, $0) },150 maxToolOutputCharacters: try c.decodeIfPresent(Int.self, forKey: .maxToolOutputCharacters) ?? d.maxToolOutputCharacters,151 repeatLimit: try c.decodeIfPresent(Int.self, forKey: .repeatLimit) ?? d.repeatLimit,152 alternationLimit: try c.decodeIfPresent(Int.self, forKey: .alternationLimit) ?? d.alternationLimit,153 warningFraction: finite(try c.decodeIfPresent(Double.self, forKey: .warningFraction)) ?? d.warningFraction)154 }155}156157/// What an agent is and what it may do. The allowlist and the budgets are the only source of permissions.158public struct AgentProfile: Sendable, Codable, Hashable, Identifiable {159 public var id: String160 public var name: String161 public var instructions: String162 public var model: ModelRef163 /// Names of registry tools this agent may call. Anything else is refused in code.164 public var allowedTools: [String]165 public var budgets: AgentBudgets166 /// Hosts `web_fetch` may reach without asking (exact host names). A URL flagged as possible exfiltration still asks.167 public var preApprovedWebHosts: [String]168 public var parameters: GenerationParameters169 /// Offers the built-in `update_plan` tool.170 public var planningEnabled: Bool171 /// When set, older turns are dropped (whole tool exchanges at a time) so the request fits this many tokens.172 public var contextWindow: Int?173174 public init(id: String = UUID().uuidString, name: String, instructions: String = "", model: ModelRef, allowedTools: [String] = [],175 budgets: AgentBudgets = AgentBudgets(), preApprovedWebHosts: [String] = [], parameters: GenerationParameters = .default,176 planningEnabled: Bool = true, contextWindow: Int? = nil) {177 self.id = id; self.name = name; self.instructions = instructions; self.model = model; self.allowedTools = allowedTools178 self.budgets = budgets; self.preApprovedWebHosts = preApprovedWebHosts; self.parameters = parameters179 self.planningEnabled = planningEnabled; self.contextWindow = contextWindow180 }181}182183// MARK: - Plan184185public struct AgentPlan: Sendable, Codable, Hashable {186 public enum Status: String, Sendable, Codable, CaseIterable { case pending, inProgress = "in_progress", done, skipped }187 public struct Step: Sendable, Codable, Hashable, Identifiable {188 public var id: Int189 public var title: String190 public var status: Status191 public init(id: Int, title: String, status: Status = .pending) { self.id = id; self.title = title; self.status = status }192 }193 public var steps: [Step]194 public init(steps: [Step] = []) { self.steps = steps }195 public var completedCount: Int { steps.filter { $0.status == .done || $0.status == .skipped }.count }196}197198/// The built-in planning tool. It is handled by the runner (it changes run state, not user data) and never needs approval.199public enum PlanTool {200 public static let name = "update_plan"201 public static let definition = ToolDefinition(202 name: name,203 summary: "Records or updates your plan for this task as an explicit list of steps with statuses. Send the whole list each time. "204 + "Use it for tasks with several steps; keep exactly one step in_progress.",205 parameters: [206 "type": "object",207 "properties": [208 "steps": [209 "type": "array", "minItems": 1, "maxItems": 30,210 "items": [211 "type": "object",212 "properties": [213 "title": ["type": "string", "minLength": 1, "maxLength": 200],214 "status": ["type": "string", "enum": ["pending", "in_progress", "done", "skipped"]],215 ],216 "required": ["title", "status"],217 "additionalProperties": false,218 ],219 ],220 ],221 "required": ["steps"],222 "additionalProperties": false,223 ])224225 static func plan(from arguments: JSONValue) throws -> AgentPlan {226 try SchemaValidator.validate(arguments: arguments, for: definition)227 let steps = (arguments["steps"]?.arrayValue ?? []).enumerated().map { i, item in228 AgentPlan.Step(id: i + 1, title: item["title"]?.stringValue ?? "", status: item["status"]?.stringValue.flatMap(AgentPlan.Status.init(rawValue:)) ?? .pending)229 }230 return AgentPlan(steps: steps)231 }232}233234// MARK: - Usage and cost235236/// Cost of the run so far, built only from real usage reports. A turn whose cost cannot be established makes the total unknown.237public struct CostLedger: Sendable, Codable, Hashable {238 /// Sum of the turns whose cost is known: a lower bound of the real total.239 public private(set) var knownUSD: Double = 0240 public private(set) var knownTurns = 0241 public private(set) var unknownTurns = 0242 public private(set) var onDeviceTurns = 0243 public private(set) var estimatedTurns = 0244 public private(set) var pricingAsOf: String?245 public init() {}246247 public mutating func add(_ cost: CostEstimate) {248 switch cost.basis {249 case .onDevice: onDeviceTurns += 1250 case .unavailable: unknownTurns += 1251 default:252 guard let amount = cost.amountUSD else { unknownTurns += 1; return }253 knownUSD += amount; knownTurns += 1254 if cost.basis != .reportedByProvider { estimatedTurns += 1 }255 pricingAsOf = cost.pricingAsOf ?? pricingAsOf256 }257 }258259 public var isComplete: Bool { unknownTurns == 0 }260261 /// The total as it may be shown: unknown stays unknown, it is never reported as zero.262 public var total: CostEstimate {263 if unknownTurns > 0 || knownTurns + onDeviceTurns == 0 { return .unavailable }264 if knownTurns == 0 { return .onDevice }265 return CostEstimate(amountUSD: knownUSD, basis: estimatedTurns > 0 ? .estimatedFromUsage : .reportedByProvider, pricingAsOf: pricingAsOf)266 }267}268269extension TokenUsage {270 /// Adds two per-turn reports. A field nobody reported stays nil.271 func adding(_ other: TokenUsage) -> TokenUsage {272 func sum(_ a: Int?, _ b: Int?) -> Int? { a == nil && b == nil ? nil : (a ?? 0) + (b ?? 0) }273 let cost: Double? = reportedCostUSD == nil && other.reportedCostUSD == nil ? nil : (reportedCostUSD ?? 0) + (other.reportedCostUSD ?? 0)274 return TokenUsage(inputTokens: sum(inputTokens, other.inputTokens), outputTokens: sum(outputTokens, other.outputTokens),275 cachedInputTokens: sum(cachedInputTokens, other.cachedInputTokens), cacheWriteTokens: sum(cacheWriteTokens, other.cacheWriteTokens),276 reasoningTokens: sum(reasoningTokens, other.reasoningTokens), reportedCostUSD: cost)277 }278}279280// MARK: - Events281282public enum AgentRunStatus: Sendable, Codable, Hashable {283 case completed284 /// Cancelled by the person.285 case stopped286 case budgetExceeded(BudgetKind)287 case failed(String)288 case cycleDetected(String)289290 public var label: String {291 switch self {292 case .completed: "Completed"293 case .stopped: "Stopped"294 case .budgetExceeded(let kind): "Stopped at the \(kind.label)"295 case .failed(let message): "Failed: \(message)"296 case .cycleDetected(let message): "Stopped: \(message)"297 }298 }299}300301public struct AgentRunInfo: Sendable, Codable, Hashable {302 public var runID: UUID303 public var profileID: String304 public var profileName: String305 public var goal: String306 public var model: ModelRef307 /// Tools actually offered to the model in this run (allowlist ∩ installed, plus `update_plan` when enabled).308 public var tools: [String]309 /// Steps already completed when this run resumed from a checkpoint; 0 for a fresh run.310 public var resumedAfterStep: Int311 public var startedAt: Date312}313314public struct BudgetWarning: Sendable, Codable, Hashable {315 public var kind: BudgetKind316 public var message: String317 public init(kind: BudgetKind, message: String) { self.kind = kind; self.message = message }318}319320/// The audit timeline of a run. Tool arguments and outputs in these events are redacted; text deltas are the model's own words.321public enum AgentEvent: Sendable, Hashable {322 case runStarted(AgentRunInfo)323 case stepStarted(Int)324 case modelTextDelta(String)325 case planUpdated(AgentPlan)326 /// The call as the model made it (arguments redacted), before any check.327 case toolRequested(ToolCall)328 case approvalRequested(ApprovalRequest)329 case approvalResolved(callID: String, decision: ApprovalDecision)330 case toolStarted(callID: String, name: String)331 /// `output` is what the model receives, minus the envelope, redacted. `flagged` lists suspicious instructions found in it.332 case toolFinished(callID: String, name: String, output: String, isError: Bool, flagged: [InjectionFinding])333 /// Totals so far. `cost` is `.unavailable` whenever any turn's cost is unknown.334 case usage(total: TokenUsage, cost: CostEstimate)335 case budgetWarning(BudgetWarning)336 case checkpointSaved(AgentCheckpoint)337 case runFinished(status: AgentRunStatus, finalText: String)338}339340// MARK: - Checkpoint341342/// Everything needed to continue a run after the app was closed. Saved after every completed step; persist the latest one.343/// Permissions are not restored from here: the profile passed to the resumed run decides which tools exist.344public struct AgentCheckpoint: Sendable, Codable, Hashable {345 public static let currentVersion = 1346 public var version: Int347 public var runID: UUID348 public var profileID: String349 public var goal: String350 public var messages: [PromptMessage]351 public var step: Int352 public var toolCalls: Int353 public var usage: TokenUsage354 public var cost: CostLedger355 public var plan: AgentPlan?356 public var grants: ApprovalGrants357 /// Signatures of the latest tool calls, for cycle detection across a resume.358 public var recentCalls: [String]359 public var sawFlaggedContent: Bool360 public var elapsed: TimeInterval361 public var savedAt: Date362 /// True when the run had already produced its final answer.363 public var isComplete: Bool364365 public func encoded() throws -> Data {366 let encoder = JSONEncoder()367 encoder.outputFormatting = [.sortedKeys]368 return try encoder.encode(self)369 }370371 public static func decode(_ data: Data) throws -> AgentCheckpoint {372 let checkpoint = try JSONDecoder().decode(AgentCheckpoint.self, from: data)373 guard checkpoint.version <= currentVersion else { throw AstraError.unsupported("This run was saved by a newer version of the app.") }374 return checkpoint375 }376}377