SPB Git

Repository Public MIT

AgentRunSession.swift 23.3 KB 475 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/AgentRunSession.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 Observation90import SwiftUI91import AstraCore92import AstraAgents93import AstraPersistence9495/// One tool call as the timeline shows it. Arguments and output are the redacted values the runner emits.96struct AgentToolActivity: Equatable, Sendable {97    enum State: Equatable, Sendable { case requested, awaitingApproval, running, finished, interrupted }98    var callID: String99    var name: String100    var arguments: JSONValue101    var state: State = .requested102    var approval: AgentDecision?103    var output: String?104    var isError = false105    var flagged: [InjectionFinding] = []106107    var wasDenied: Bool { if case .deny = approval { return true }; return false }108}109110/// A sub-agent started by a `delegate` call, as the timeline shows it: what it was asked, what it is doing, what it reported.111struct AgentDelegateActivity: Equatable, Sendable {112    var id: String113    var role: DelegateRole114    var task: String115    var step = 0116    /// The tools it called, in order, with how each ended (nil while running).117    var tools: [(name: String, failed: Bool?)] = []118    var waitingForApproval = false119    var status: AgentOutcome?120    var report = ""121122    var isRunning: Bool { status == nil }123    static func == (a: AgentDelegateActivity, b: AgentDelegateActivity) -> Bool {124        a.id == b.id && a.step == b.step && a.waitingForApproval == b.waitingForApproval && a.status == b.status && a.report == b.report125            && a.tools.count == b.tools.count && zip(a.tools, b.tools).allSatisfy { $0.name == $1.name && $0.failed == $1.failed }126    }127}128129struct AgentTimelineItem: Identifiable, Equatable, Sendable {130    enum Content: Equatable, Sendable {131        case delegate(AgentDelegateActivity)132        case notice(String)133        case step(Int)134        case text(String)135        case plan(AgentPlan)136        case tool(AgentToolActivity)137        case warning(BudgetWarning)138        case problem(String)139    }140    let id: Int141    var content: Content142}143144/// A run in progress or just finished: the live timeline built from the runner's events, and the audit trail written to the145/// store as the events arrive. Lives in `AgentsController`, so it survives leaving the run screen.146@MainActor @Observable final class AgentRunSession {147    static func checkpointKey(_ recordID: String) -> String { "agents.checkpoint." + recordID }148149    let profile: AgentProfile150    let goal: String151    /// The store's id of this run (the audit trail's key). The runner has its own run id inside the checkpoint.152    let recordID: String153    let isResumed: Bool154155    private(set) var items: [AgentTimelineItem] = []156    private(set) var plan: AgentPlan?157    private(set) var step = 0158    private(set) var toolCalls = 0159    private(set) var usage = TokenUsage()160    /// Nil until a model turn has reported in; `.unavailable` when a turn's cost cannot be established.161    private(set) var cost: CostEstimate?162    private(set) var hasUsageReport = false163    private(set) var outcome: AgentOutcome?164    private(set) var finalText = ""165    private(set) var offeredTools: [String] = []166    private(set) var stopRequested = false167    private(set) var waitingForApproval = false168    private(set) var startedAt = Date()169    private(set) var finishedAt: Date?170    /// Seconds already spent before this process took the run over (a resumed run).171    let elapsedBefore: TimeInterval172    /// Set when the audit trail could not be written; the run itself continues.173    private(set) var auditError: String?174175    var isRunning: Bool { outcome == nil }176    var elapsed: TimeInterval { elapsedBefore + (finishedAt ?? Date()).timeIntervalSince(startedAt) }177178    @ObservationIgnored private let store: AstraStore179    @ObservationIgnored private var run: AgentRun?180    @ObservationIgnored private var pump: Task<Void, Never>?181    @ObservationIgnored private var nextID = 0182    @ObservationIgnored private var openText: Int?183    @ObservationIgnored private var pendingText = ""184    @ObservationIgnored private var pendingUsage: TokenUsage?185    @ObservationIgnored private var lastUsage: TokenUsage186    @ObservationIgnored private var toolSteps: [String: String] = [:]187    @ObservationIgnored private var approvalSteps: [String: String] = [:]188    @ObservationIgnored private var planCalls: Set<String> = []189    @ObservationIgnored private var planEchoExpected = false190    @ObservationIgnored private var onFinish: (@MainActor (AgentRunSession) async -> Void)?191192    init(profile: AgentProfile, goal: String, recordID: String, store: AstraStore, resumedFrom checkpoint: AgentCheckpoint? = nil) {193        self.profile = profile; self.goal = goal; self.recordID = recordID; self.store = store194        isResumed = checkpoint != nil195        elapsedBefore = checkpoint?.elapsed ?? 0196        lastUsage = checkpoint?.usage ?? TokenUsage()197        if let checkpoint {198            step = checkpoint.step; toolCalls = checkpoint.toolCalls; usage = checkpoint.usage; plan = checkpoint.plan199            hasUsageReport = checkpoint.step > 0200            cost = checkpoint.step > 0 ? checkpoint.cost.total : nil201            planEchoExpected = checkpoint.plan != nil202        }203    }204205    /// Starts consuming the run's events. `onFinish` runs once, after the final status has been stored.206    func begin(_ run: AgentRun, onFinish: @escaping @MainActor (AgentRunSession) async -> Void) {207        self.run = run208        self.onFinish = onFinish209        startedAt = Date()210        pump = Task { [weak self] in211            for await event in run.events { await self?.handle(event) }212            await self?.streamEnded()213        }214    }215216    /// Stops the run wherever it is. The runner answers with a final `stopped` event, which closes the session.217    func stop() {218        guard isRunning else { return }219        stopRequested = true220        run?.cancel()221    }222223    // MARK: Timeline224225    @discardableResult private func append(_ content: AgentTimelineItem.Content) -> Int {226        nextID += 1227        items.append(AgentTimelineItem(id: nextID, content: content))228        return nextID229    }230231    private func updateTool(_ callID: String, _ change: (inout AgentToolActivity) -> Void) {232        guard let index = items.lastIndex(where: { if case .tool(let tool) = $0.content { return tool.callID == callID }; return false }),233              case .tool(var tool) = items[index].content else { return }234        change(&tool)235        items[index].content = .tool(tool)236    }237238    private func updateDelegate(_ id: String, _ change: (inout AgentDelegateActivity) -> Void) {239        guard let index = items.lastIndex(where: { if case .delegate(let d) = $0.content { return d.id == id }; return false }),240              case .delegate(var activity) = items[index].content else { return }241        change(&activity)242        items[index].content = .delegate(activity)243    }244245    /// What a sub-agent did. Its tool calls and approvals go to the audit trail like the agent's own, marked with its role.246    private func handleDelegate(_ id: String, _ event: AgentEvent) async {247        let role: String = items.compactMap { if case .delegate(let d) = $0.content, d.id == id { return d.role.title }; return nil }.last ?? "Sub-agent"248        switch event {249        case .stepStarted(let number): updateDelegate(id) { $0.step = number }250        case .toolRequested(let call):251            toolCalls += 1252            updateDelegate(id) { $0.tools.append((call.name, nil)) }253            if let stepID = await record(AgentStepDraft(kind: .toolCall, toolName: call.name, text: "\(role) sub-agent", input: call.arguments)) { toolSteps[call.id] = stepID }254        case .toolFinished(let callID, let name, let output, let isError, _):255            updateDelegate(id) { activity in256                if let index = activity.tools.lastIndex(where: { $0.name == name && $0.failed == nil }) { activity.tools[index].failed = isError }257            }258            if let stepID = toolSteps.removeValue(forKey: callID) {259                await attempt { try await store.completeAgentStep(id: stepID, output: .object(["text": .string(output), "isError": .bool(isError)])) }260            }261        case .approvalRequested(let request):262            waitingForApproval = true263            updateDelegate(id) { $0.waitingForApproval = true }264            var text = "\(role) sub-agent: " + request.summary265            if !request.warnings.isEmpty { text += "\nWarnings: " + request.warnings.joined(separator: " ") }266            if let stepID = await record(AgentStepDraft(kind: .approvalRequest, toolName: request.toolName, text: text, input: request.arguments)) { approvalSteps[request.id] = stepID }267            await attempt { try await store.setAgentRunStatus(id: recordID, .awaitingApproval) }268        case .approvalResolved(let callID, let decision):269            waitingForApproval = false270            updateDelegate(id) { $0.waitingForApproval = false }271            let stored: AgentStoredDecision = decision.isAllowed ? .approved : .denied272            if let stepID = approvalSteps.removeValue(forKey: callID) { await attempt { try await store.completeAgentStep(id: stepID, approval: stored) } }273            await record(AgentStepDraft(kind: .approvalDecision, text: "\(role) sub-agent: " + decision.label, approval: stored))274            await attempt { try await store.setAgentRunStatus(id: recordID, .running) }275        case .delegateEvent(let nested, let inner): await handleDelegate(nested, inner)276        default: break   // its words arrive as its report; its own usage is in the run's totals277        }278    }279280    private func appendText(_ delta: String) {281        pendingText += delta282        if let id = openText, let index = items.lastIndex(where: { $0.id == id }) { items[index].content = .text(pendingText) }283        else { openText = append(.text(pendingText)) }284    }285286    // MARK: Audit trail287288    @discardableResult private func record(_ draft: AgentStepDraft) async -> String? {289        do { return try await store.appendAgentStep(runID: recordID, draft).id }290        catch { auditError = "The audit trail could not be saved: \(AstraError.wrap(error).message)"; return nil }291    }292293    private func attempt(_ operation: () async throws -> Void) async {294        do { try await operation() } catch { auditError = "The audit trail could not be saved: \(AstraError.wrap(error).message)" }295    }296297    /// Stores the model's words of the current turn (with the turn's token usage when it was reported) and closes the open text item.298    private func flushModelMessage() async {299        let text = pendingText, turnUsage = pendingUsage300        pendingText = ""; pendingUsage = nil; openText = nil301        guard !text.isEmpty || turnUsage != nil else { return }302        await record(AgentStepDraft(kind: .modelMessage, text: text, usage: turnUsage))303    }304305    static func difference(_ total: TokenUsage, _ previous: TokenUsage) -> TokenUsage {306        func minus(_ a: Int?, _ b: Int?) -> Int? { a.map { max(0, $0 - (b ?? 0)) } }307        return TokenUsage(inputTokens: minus(total.inputTokens, previous.inputTokens), outputTokens: minus(total.outputTokens, previous.outputTokens),308                          cachedInputTokens: minus(total.cachedInputTokens, previous.cachedInputTokens),309                          cacheWriteTokens: minus(total.cacheWriteTokens, previous.cacheWriteTokens),310                          reasoningTokens: minus(total.reasoningTokens, previous.reasoningTokens),311                          reportedCostUSD: total.reportedCostUSD.map { max(0, $0 - (previous.reportedCostUSD ?? 0)) })312    }313314    static func planText(_ plan: AgentPlan) -> String {315        plan.steps.map { "\($0.id). [\($0.status.label)] \($0.title)" }.joined(separator: "\n")316    }317318    // MARK: Events319320    private func handle(_ event: AgentEvent) async {321        guard isRunning else { return }322        switch event {323        case .runStarted(let info):324            offeredTools = info.tools325            if info.resumedAfterStep > 0 {326                append(.notice("Resumed after step \(info.resumedAfterStep). The earlier activity is in this run's audit trail. Files shared before the app closed must be shared again."))327                await record(AgentStepDraft(kind: .note, text: "Resumed after step \(info.resumedAfterStep)."))328            }329330        case .stepStarted(let number):331            await flushModelMessage()332            step = number333            append(.step(number))334            await record(AgentStepDraft(kind: .note, text: "Step \(number)"))335336        case .modelTextDelta(let delta):337            appendText(delta)338339        case .planUpdated(let updated):340            plan = updated341            // A resumed run re-announces the plan it already had; that is not a new audit event.342            if planEchoExpected { planEchoExpected = false; return }343            append(.plan(updated))344            await record(AgentStepDraft(kind: .plan, toolName: PlanTool.name, text: Self.planText(updated)))345346        case .toolRequested(let call):347            await flushModelMessage()348            if profile.planningEnabled, call.name == PlanTool.name { planCalls.insert(call.id); return }349            if call.name == DelegateTool.name, profile.delegation.enabled {350                // shown through the sub-agents it starts; the call itself is still in the audit trail351                toolCalls += 1352                planCalls.insert(call.id)353                await record(AgentStepDraft(kind: .toolCall, toolName: call.name, input: call.arguments))354                return355            }356            toolCalls += 1357            append(.tool(AgentToolActivity(callID: call.id, name: call.name, arguments: call.arguments)))358            if let id = await record(AgentStepDraft(kind: .toolCall, toolName: call.name, input: call.arguments)) { toolSteps[call.id] = id }359360        case .approvalRequested(let request):361            waitingForApproval = true362            AccessibilityNotification.Announcement("The agent needs your approval. " + request.summary).post()363            updateTool(request.id) { $0.state = .awaitingApproval }364            var text = request.summary365            if !request.warnings.isEmpty { text += "\nWarnings: " + request.warnings.joined(separator: " ") }366            if let id = await record(AgentStepDraft(kind: .approvalRequest, toolName: request.toolName, text: text, input: request.arguments)) {367                approvalSteps[request.id] = id368            }369            await attempt { try await store.setAgentRunStatus(id: recordID, .awaitingApproval) }370371        case .approvalResolved(let callID, let decision):372            waitingForApproval = false373            updateTool(callID) { $0.approval = decision; if $0.state == .awaitingApproval { $0.state = .requested } }374            let stored: AgentStoredDecision = decision.isAllowed ? .approved : .denied375            if let id = approvalSteps.removeValue(forKey: callID) {376                await attempt { try await store.completeAgentStep(id: id, approval: stored) }377            }378            await record(AgentStepDraft(kind: .approvalDecision, text: decision.label, approval: stored))379            await attempt { try await store.setAgentRunStatus(id: recordID, .running) }380381        case .toolStarted(let callID, _):382            updateTool(callID) { $0.state = .running }383384        case .toolFinished(let callID, _, let output, let isError, let flagged):385            if planCalls.remove(callID) != nil {386                if isError {387                    append(.problem("The plan could not be recorded: \(output)"))388                    await record(AgentStepDraft(kind: .error, toolName: PlanTool.name, text: output))389                }390                return391            }392            updateTool(callID) { $0.state = .finished; $0.output = output; $0.isError = isError; $0.flagged = flagged }393            if let id = toolSteps.removeValue(forKey: callID) {394                var result: [String: JSONValue] = ["text": .string(output), "isError": .bool(isError)]395                if !flagged.isEmpty {396                    result["flagged"] = .array(flagged.map { ["category": .string($0.category.rawValue), "excerpt": .string($0.excerpt)] })397                }398                await attempt { try await store.completeAgentStep(id: id, output: .object(result)) }399            }400401        case .usage(let total, let estimate):402            pendingUsage = Self.difference(total, lastUsage)403            lastUsage = total404            usage = total405            cost = estimate406            hasUsageReport = true407            await flushModelMessage()408409        case .budgetWarning(let warning):410            append(.warning(warning))411            await record(AgentStepDraft(kind: .note, text: "Budget warning (\(warning.kind.label)): \(warning.message)"))412413        case .checkpointSaved(let checkpoint):414            // The latest checkpoint is what makes a run resumable after the app is closed.415            await attempt { try await store.setSetting(Self.checkpointKey(recordID), try checkpoint.encoded()) }416417        case .toolRetried(_, let name, let reason):418            append(.notice("\(AgentToolCatalog.title(name)) failed (\(reason)) and is being tried once more."))419            await record(AgentStepDraft(kind: .note, toolName: name, text: "Retried once after: \(reason)"))420421        case .delegateStarted(let id, let role, let task):422            append(.delegate(AgentDelegateActivity(id: id, role: role, task: task)))423            await record(AgentStepDraft(kind: .note, toolName: DelegateTool.name, text: "\(role.title) sub-agent started: \(task)"))424425        case .delegateEvent(let id, let inner):426            await handleDelegate(id, inner)427428        case .delegateFinished(let id, let role, let status, let report):429            updateDelegate(id) { $0.status = status; $0.report = report; $0.waitingForApproval = false }430            await record(AgentStepDraft(kind: status == .completed ? .note : .error, toolName: DelegateTool.name, text: "\(role.title) sub-agent: \(status.label)\n\(report)"))431432        case .runFinished(let status, let text):433            await finish(status, text: text)434        }435    }436437    private func streamEnded() async {438        if isRunning { await finish(.failed("The run ended without a final status."), text: pendingText) }439    }440441    private func finish(_ status: AgentOutcome, text: String) async {442        guard isRunning else { return }443        await flushModelMessage()444        finishedAt = Date()445        finalText = text446        waitingForApproval = false447        // Calls that never got their result (the run stopped mid-call) are shown as interrupted, not as still running.448        for index in items.indices {449            if case .tool(var tool) = items[index].content, tool.state != .finished { tool.state = .interrupted; items[index].content = .tool(tool) }450            if case .delegate(var activity) = items[index].content, activity.isRunning { activity.status = .stopped; items[index].content = .delegate(activity) }451        }452        if case .completed = status, let last = items.last, case .text(let shown) = last.content, shown == text {453            // The final answer is shown once, in its own card below the timeline.454            items.removeLast()455        }456        outcome = status457458        // The cost is stored only when it is known for the whole run; a partial figure would read as a total.459        let total = cost.flatMap { $0.basis == .unavailable ? nil : $0.amountUSD }460        switch status {461        case .completed:462            await record(AgentStepDraft(kind: .final, text: status.label, costUSD: total))463            await attempt { try await store.setAgentRunStatus(id: recordID, .completed, result: text) }464        default:465            await record(AgentStepDraft(kind: status == .stopped ? .note : .error, text: status.label, costUSD: total))466            await attempt { try await store.setAgentRunStatus(id: recordID, status.stored, result: text.isEmpty ? nil : text, error: status == .stopped ? nil : status.label) }467        }468        await attempt { try await store.recordAgentRunUsage(runID: recordID) }469        await attempt { try await store.removeSetting(Self.checkpointKey(recordID)) }470        let callback = onFinish471        onFinish = nil472        await callback?(self)473    }474}475
Files main
Menu

Theme