SPB Git

Repository Public

Timeline.swift 8.5 KB 195 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/Timeline.swift10// Description      : The observable record of an agent run: a Codable stream of11//                    events (plan, steps, tool calls, proposals, applied12//                    changes, validation, errors, budget, final report) that a13//                    view can render live and that a host can persist and14//                    replay.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 AstraAgents9495public struct AgentTimelineEvent: Sendable, Codable, Hashable, Identifiable {96    /// Position in the timeline, starting at 1.97    public var id: Int98    public var date: Date99    public var runID: String100    /// The agent that produced the event (a role name in multi-agent mode).101    public var agent: String102    /// The model turn during which it happened (0 before the first).103    public var step: Int104    public var kind: Kind105106    public enum Kind: Sendable, Codable, Hashable {107        case runStarted(objective: String, model: String, autonomy: String, scopes: [String], tools: [String], resumed: Bool)108        case stepStarted109        /// Text the model wrote besides its tool calls.110        case modelText(String)111        case planUpdated(AgentPlan)112        case toolStarted(callID: String, tool: String, arguments: String)113        case toolFinished(callID: String, tool: String, result: String, isError: Bool, milliseconds: Int)114        /// Content was supplied to the model: the sections concerned and the coverage so far.115        case sectionsExamined(sections: [String], blocks: Int, coverage: String)116        /// Text that looks like injected instructions was found in content shown to the model.117        case suspiciousContent(source: String, findings: [InjectionFinding])118        case changesProposed(ChangeProposal)119        case approvalResolved(proposal: String, decision: String, detail: String?)120        case actionRequested(ActionRequest)121        case actionResolved(request: String, allowed: Bool)122        case questionAsked(UserQuestion)123        case questionAnswered(question: String, answered: Bool)124        case changesApplied(AppliedBatch)125        /// Integrity check of a step: `stage` is "preview" (before applying) or "applied".126        case validation(stage: String, result: IntegrityResult)127        case artifactDelivered(ArtifactReceipt)128        case error(String)129        /// What the loop did to recover from an error or a conflict.130        case recovery(String)131        case budget(BudgetUsage)132        case checkpointSaved(reason: String)133        case finalReport(AgentReport)134    }135}136137/// The timeline of one run (or of a whole multi-agent run). Safe to read from any task; `stream()` replays what happened and then follows live.138public final class AgentTimeline: Sendable {139    private struct State: Sendable {140        var events: [AgentTimelineEvent]141        var subscribers: [UUID: AsyncStream<AgentTimelineEvent>.Continuation] = [:]142        var closed = false143    }144    private let state: Locked<State>145146    /// `events` restores a persisted timeline, so a resumed run continues the same record.147    public init(events: [AgentTimelineEvent] = []) { state = Locked(State(events: events)) }148149    public var events: [AgentTimelineEvent] { state.value.events }150151    /// Every past event, then every new one until the run ends.152    public func stream() -> AsyncStream<AgentTimelineEvent> {153        AsyncStream(bufferingPolicy: .unbounded) { continuation in154            let id = UUID()155            let closed: Bool = state.withLock { s in156                for event in s.events { continuation.yield(event) }157                if !s.closed { s.subscribers[id] = continuation }158                return s.closed159            }160            if closed { continuation.finish(); return }161            continuation.onTermination = { [state] _ in state.withLock { $0.subscribers[id] = nil } }162        }163    }164165    @discardableResult166    func emit(_ kind: AgentTimelineEvent.Kind, runID: String, agent: String, step: Int, date: Date) -> AgentTimelineEvent {167        state.withLock { s in168            let event = AgentTimelineEvent(id: (s.events.last?.id ?? 0) + 1, date: date, runID: runID, agent: agent, step: step, kind: kind)169            s.events.append(event)170            for subscriber in s.subscribers.values { subscriber.yield(event) }171            return event172        }173    }174175    /// Ends every live stream. Called when the run (or the whole tree) is over.176    func close() {177        let subscribers: [AsyncStream<AgentTimelineEvent>.Continuation] = state.withLock { s in178            s.closed = true179            defer { s.subscribers = [:] }180            return Array(s.subscribers.values)181        }182        for subscriber in subscribers { subscriber.finish() }183    }184185    public func encoded() throws -> Data {186        // Dates keep their full precision (the default encoding), so a restored record equals the original.187        let e = JSONEncoder(); e.outputFormatting = [.sortedKeys]188        return try e.encode(events)189    }190    public static func decode(_ data: Data) throws -> AgentTimeline {191        let d = JSONDecoder()192        return AgentTimeline(events: try d.decode([AgentTimelineEvent].self, from: data))193    }194}195
Files main
Menu

Theme