SPB Git

Repository Public

RunRecords.swift 17.7 KB 421 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Docs9// File             : Packages/ORIXDocsAI/Sources/DocAgent/RunRecords.swift10// Description      : The records of an agent run: budgets and their meter,11//                    applied batches, the final report, and the checkpoint a12//                    run resumes from. Everything here is Codable so a host can13//                    persist it; none of it is written to disk by the agent14//                    itself.15// Module           : DocAgent16// Repository       : https://git.spboucher.ai/orix-docs17// Created          : 2026-11-2218// Last Modified    : 2026-11-2219//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : None specified (no license file in this repository)85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Foundation93import AstraCore94import AstraAgents95import DocCommands9697// MARK: - Budget9899public struct AgentBudget: Sendable, Codable, Hashable {100    /// Model turns.101    public var maxSteps: Int102    /// Input plus output tokens over the whole run (and the whole tree in multi-agent mode). Nil: no limit.103    public var maxTokens: Int?104    /// Cost in US dollars. Needs a price for the model: a turn whose cost cannot be established ends the run rather than run unmetered.105    public var maxCostUSD: Double?106    /// Seconds of wall-clock time, waits for approval included.107    public var maxWallClock: TimeInterval?108    public var maxOutputTokensPerTurn: Int109    /// Characters of one tool result handed back to the model.110    public var maxToolOutputCharacters: Int111    public var maxToolCallsPerStep: Int112113    public init(maxSteps: Int = 40, maxTokens: Int? = nil, maxCostUSD: Double? = nil, maxWallClock: TimeInterval? = nil, maxOutputTokensPerTurn: Int = 4_096,114                maxToolOutputCharacters: Int = 24_000, maxToolCallsPerStep: Int = 32) {115        self.maxSteps = max(1, maxSteps); self.maxTokens = maxTokens; self.maxCostUSD = maxCostUSD; self.maxWallClock = maxWallClock116        self.maxOutputTokensPerTurn = max(64, maxOutputTokensPerTurn); self.maxToolOutputCharacters = max(500, maxToolOutputCharacters)117        self.maxToolCallsPerStep = max(1, maxToolCallsPerStep)118    }119}120121public enum BudgetLimit: String, Sendable, Codable, Hashable { case steps, tokens, cost, wallClock }122123/// What a run has spent. Token counts are the provider's own when it reports them; `tokensEstimated` says when they are not.124public struct BudgetUsage: Sendable, Codable, Hashable {125    public var steps = 0126    public var inputTokens = 0127    public var outputTokens = 0128    public var tokensEstimated = false129    /// Sum of the turns whose cost is known.130    public var costUSD: Double = 0131    /// False when at least one turn had no establishable cost: `costUSD` is then a lower bound.132    public var costComplete = true133    public var elapsed: TimeInterval = 0134    public var totalTokens: Int { inputTokens + outputTokens }135    public init() {}136}137138/// Counts what is spent against a budget. One meter is shared by every agent of a multi-agent run.139public final class BudgetMeter: Sendable {140    public let budget: AgentBudget141    private struct State: Sendable { var usage: BudgetUsage; var startedAt: Date; var elapsedBefore: TimeInterval }142    private let state: Locked<State>143    private let clock: @Sendable () -> Date144145    public init(budget: AgentBudget, restoring usage: BudgetUsage = BudgetUsage(), clock: @escaping @Sendable () -> Date = { Date() }) {146        self.budget = budget; self.clock = clock147        state = Locked(State(usage: usage, startedAt: clock(), elapsedBefore: usage.elapsed))148    }149150    public var usage: BudgetUsage {151        let now = clock()152        return state.withLock { s in153            var u = s.usage154            u.elapsed = s.elapsedBefore + max(0, now.timeIntervalSince(s.startedAt))155            return u156        }157    }158159    /// The limit already reached, if any.160    public func exhausted() -> BudgetLimit? {161        let u = usage162        if let limit = budget.maxWallClock, u.elapsed >= limit { return .wallClock }163        if u.steps >= budget.maxSteps { return .steps }164        if let limit = budget.maxTokens, u.totalTokens >= limit { return .tokens }165        if let limit = budget.maxCostUSD, u.costUSD >= limit || !u.costComplete { return .cost }166        return nil167    }168169    /// Takes one step from the budget, or reports the limit that forbids it. Atomic, so parallel agents cannot overdraw.170    func beginStep() -> BudgetLimit? {171        if let limit = exhausted() { return limit }172        let max = budget.maxSteps173        return state.withLock { s in174            guard s.usage.steps < max else { return .steps }175            s.usage.steps += 1176            return nil177        }178    }179180    func charge(reported: TokenUsage?, estimatedInput: Int, estimatedOutput: Int, cost: CostEstimate) {181        state.withLock { s in182            if let reported, reported.inputTokens != nil || reported.outputTokens != nil {183                s.usage.inputTokens += reported.inputTokens ?? estimatedInput184                s.usage.outputTokens += reported.outputTokens ?? estimatedOutput185                if reported.inputTokens == nil || reported.outputTokens == nil { s.usage.tokensEstimated = true }186            } else {187                s.usage.inputTokens += estimatedInput; s.usage.outputTokens += estimatedOutput; s.usage.tokensEstimated = true188            }189            switch cost.basis {190            case .onDevice: break191            case .unavailable: s.usage.costComplete = false192            default: if let amount = cost.amountUSD { s.usage.costUSD += amount } else { s.usage.costComplete = false }193            }194        }195    }196197    /// Continues the count of a run that is being resumed.198    func restore(_ usage: BudgetUsage) {199        let now = clock()200        state.withLock { $0 = State(usage: usage, startedAt: now, elapsedBefore: usage.elapsed) }201    }202203    /// Seconds left before the wall-clock limit; nil when there is none.204    var remainingWallClock: TimeInterval? { budget.maxWallClock.map { max(0, $0 - usage.elapsed) } }205}206207// MARK: - What was done208209/// One batch of commands applied to the document: one transaction, one revision, one undo step. Built from the executor's change set.210public struct AppliedBatch: Sendable, Codable, Hashable, Identifiable {211    public var id: String212    public var agent: String213    public var step: Int214    public var callIDs: [String]215    public var commands: [String]216    public var revisionBefore: Int217    public var revisionAfter: Int218    public var blocks: [ProposedBlockChange]219    public var parts: [String]220    /// Recorded as tracked changes.221    public var tracked: Bool222    /// How it was authorised: "pre-authorized", "approved", "approved (selection)", "approved (edited)".223    public var approval: String224    /// Content-free audit records of the host's executor for this batch.225    public var audit: [DocAuditEntry]226    public var warnings: [String]227    /// True when the post-apply integrity check failed and the step was undone.228    public var undone: Bool229}230231public struct RejectedProposal: Sendable, Codable, Hashable {232    public var proposal: String233    public var agent: String234    public var commands: [String]235    public var reason: String236}237238public enum DocAgentStatus: Sendable, Codable, Hashable {239    case completed240    case budgetExhausted(BudgetLimit)241    case cancelled242    case failed(String)243244    public var label: String {245        switch self {246        case .completed: "Completed"247        case .budgetExhausted(let limit): "Stopped: \(limit.rawValue) budget exhausted"248        case .cancelled: "Cancelled"249        case .failed(let why): "Failed: \(why)"250        }251    }252}253254public struct ChangeTotals: Sendable, Codable, Hashable {255    public var batches = 0256    public var inserted = 0257    public var deleted = 0258    public var modified = 0259    public var moved = 0260    public var formattingOnly = 0261    public var parts: [String] = []262    public var citationsAdded: [String] = []263    public var citationsRemoved: [String] = []264}265266/// The final report of a run. Everything about the document comes from the command engine's records and from the document itself;267/// the model's own words are kept apart and labelled.268public struct AgentReport: Sendable, Codable, Hashable {269    public var runID: String270    public var agent: String271    public var objective: String272    public var model: String273    public var status: DocAgentStatus274    /// What the model said it did. Not verified; compare with `applied`.275    public var modelSummary: String276    /// The coverage the model claimed in `finish` ("whole_document" / "partial"), if it called it.277    public var modelClaimedScope: String?278    /// True when the model claimed whole-document analysis that the coverage record contradicts.279    public var modelOverstatedCoverage: Bool280    public var unresolved: [String]281    /// Every batch applied, in order, with its block-level changes.282    public var applied: [AppliedBatch]283    public var totals: ChangeTotals284    public var rejected: [RejectedProposal]285    public var artifacts: [ArtifactReceipt]286    public var coverage: CoverageReport287    /// Integrity problems of the document at the end of the run (whoever caused them).288    public var integrityIssues: [IntegrityIssue]289    public var revisionAtStart: Int290    public var revisionAtEnd: Int291    /// Number of times the document was found changed by someone else during the run.292    public var externalChanges: Int293    public var budget: BudgetUsage294    public var toolCalls: [String: Int]295    public var errors: [String]296    public var suspiciousPassages: Int297    /// Content-free audit records of the run (reads, previews, applications), most recent last, bounded.298    public var audit: [DocAuditEntry]299    public var startedAt: Date300    public var finishedAt: Date301302    /// The changes, one line each, derived from `applied`.303    public var changeList: [String] {304        applied.filter { !$0.undone }.flatMap { batch in305            batch.blocks.map { c -> String in306                let what: String307                switch c.kind {308                case .inserted: what = "inserted \(c.blockType) \(c.block): \"\((c.proposed ?? "").clipped(80))\""309                case .deleted: what = "deleted \(c.blockType) \(c.block): \"\((c.original ?? "").clipped(80))\""310                case .moved: what = "moved \(c.blockType) \(c.block)"311                case .modified: what = c.formattingOnly ? "reformatted \(c.blockType) \(c.block)" : "modified \(c.blockType) \(c.block): \"\((c.original ?? "").clipped(60))\" → \"\((c.proposed ?? "").clipped(60))\""312                }313                return "r\(batch.revisionAfter) [\(batch.agent)] \(what)"314            } + batch.parts.map { "r\(batch.revisionAfter) [\(batch.agent)] changed \($0)" }315        }316    }317318    static func totals(of batches: [AppliedBatch]) -> ChangeTotals {319        var t = ChangeTotals()320        for b in batches where !b.undone {321            t.batches += 1322            for c in b.blocks {323                switch c.kind {324                case .inserted: t.inserted += 1325                case .deleted: t.deleted += 1326                case .moved: t.moved += 1327                case .modified: if c.formattingOnly { t.formattingOnly += 1 } else { t.modified += 1 }328                }329                t.citationsAdded += c.citationsAdded; t.citationsRemoved += c.citationsRemoved330            }331            for p in b.parts where !t.parts.contains(p) { t.parts.append(p) }332        }333        return t334    }335}336337// MARK: - Checkpoint338339/// A model turn whose tool calls are not all answered yet.340public struct InFlightStep: Sendable, Codable, Hashable {341    public var assistant: PromptMessage342    /// Tool results already produced, by call identifier.343    public var results: [String: PromptMessage]344}345346/// Written before a batch is handed to the host: if the run stops before the outcome is recorded, the resume knows not to apply it twice.347public struct ApplyIntent: Sendable, Codable, Hashable {348    public var callIDs: [String]349    public var commands: [String]350    public var baseRevision: Int351}352353public struct ToolLogEntry: Sendable, Codable, Hashable {354    public var step: Int355    public var tool: String356    public var isError: Bool357    /// The result, shortened.358    public var result: String359}360361/// Everything needed to continue a run after the app was closed. The messages hold the tool results; the log holds bounded summaries.362public struct DocAgentCheckpoint: Sendable, Codable, Hashable {363    public static let currentVersion = 1364    public var version = DocAgentCheckpoint.currentVersion365    public var runID: String366    public var agent: String367    public var objective: String368    public var documentID: String369    /// Revision of the document when the checkpoint was written.370    public var documentRevision: Int371    /// Revision the model last read (nil before its first read).372    public var knownRevision: Int?373    public var messages: [PromptMessage]374    public var inFlight: InFlightStep?375    public var plan: AgentPlan?376    public var step: Int377    public var applied: [AppliedBatch]378    public var rejected: [RejectedProposal]379    public var artifacts: [ArtifactReceipt]380    public var toolLog: [ToolLogEntry]381    /// A proposal waiting for the person when the checkpoint was written. It is rebuilt from a fresh preview on resume.382    public var pendingProposal: ChangeProposal?383    public var intent: ApplyIntent?384    public var usage: BudgetUsage385    public var coverage: CoverageTracker386    public var sawSuspiciousContent: Bool387    public var suspiciousPassages: Int388    public var errors: [String]389    public var toolCalls: [String: Int]390    public var finishRejections: Int391    public var externalChanges: Int392    public var revisionAtStart: Int393    public var startedAt: Date394    public var savedAt: Date395    public var isComplete: Bool396397    public func encoded() throws -> Data {398        // Dates keep their full precision (the default encoding), so a restored record equals the original.399        let e = JSONEncoder(); e.outputFormatting = [.sortedKeys]400        return try e.encode(self)401    }402    public static func decode(_ data: Data) throws -> DocAgentCheckpoint {403        let d = JSONDecoder()404        let c = try d.decode(DocAgentCheckpoint.self, from: data)405        guard c.version == currentVersion else { throw DocCommandError(.unsupported, "This checkpoint was written by another version of the agent (\(c.version)).") }406        return c407    }408}409410/// Where checkpoints go. The host decides (a file beside the document, a database row); the agent only hands them over.411public protocol CheckpointStore: Sendable {412    func save(_ checkpoint: DocAgentCheckpoint) async413}414415public actor InMemoryCheckpointStore: CheckpointStore {416    public private(set) var history: [DocAgentCheckpoint] = []417    public init() {}418    public func save(_ checkpoint: DocAgentCheckpoint) async { history.append(checkpoint) }419    public var latest: DocAgentCheckpoint? { history.last }420}421
Files main
Menu

Theme