SPB Git

Repository Public MIT

Agents.swift 12.0 KB 246 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraPersistence/Sources/Agents.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 GRDB90import AstraCore9192public extension AstraStore {93    // MARK: Profiles9495    func saveAgentProfile(_ profile: AgentProfileRecord, at date: Date = Date()) async throws {96        var record = profile97        record.updatedAt = date98        let saved = record99        try await write { db in try saved.save(db) }100    }101102    func agentProfiles() async throws -> [AgentProfileRecord] {103        try await read { db in try AgentProfileRecord.fetchAll(db, sql: "SELECT * FROM agentProfile ORDER BY name COLLATE NOCASE, id") }104    }105106    func agentProfile(id: String) async throws -> AgentProfileRecord? { try await read { db in try AgentProfileRecord.find(db, id: id) } }107108    /// Runs of a deleted profile are kept for the audit trail.109    func deleteAgentProfile(id: String) async throws { try await write { db in _ = try AgentProfileRecord.remove(db, id: id) } }110111    // MARK: Runs112113    @discardableResult114    func startAgentRun(profile: AgentProfileRecord, goal: String, at date: Date = Date()) async throws -> AgentRunRecord {115        let run = AgentRunRecord(id: AstraID.new(), profileID: profile.id, profileName: profile.name, model: profile.model,116                                 goal: Redactor.redact(goal), status: .running, startedAt: date, finishedAt: nil, stepCount: 0, toolCallCount: 0,117                                 usage: TokenUsage(), costUSD: nil, result: nil, error: nil)118        return try await write { db in119            var record = run120            // A profile that was never saved, or was deleted meanwhile, must not block the run.121            if try AgentProfileRecord.find(db, id: profile.id) == nil { record.profileID = nil }122            try record.insert(db)123            return record124        }125    }126127    /// Appends one audit event. Ordinals are assigned here, in order of arrival; text, input and output are redacted before storage,128    /// and the run's totals (steps, tool calls, tokens, cost) are updated in the same transaction.129    @discardableResult130    func appendAgentStep(runID: String, _ draft: AgentStepDraft) async throws -> AgentStepRecord {131        try await write { db in132            var run = try AgentRunRecord.require(db, id: runID)133            let ordinal = (try Int.fetchOne(db, sql: "SELECT MAX(ordinal) FROM agentStep WHERE runID = ?", arguments: [runID]) ?? -1) + 1134            let step = AgentStepRecord(id: AstraID.new(), runID: runID, ordinal: ordinal, kind: draft.kind, toolName: draft.toolName,135                                       text: Redactor.redact(draft.text), inputJSON: draft.input.map(Self.redactedJSON),136                                       outputJSON: draft.output.map(Self.redactedJSON), approval: draft.approval, createdAt: draft.createdAt,137                                       finishedAt: draft.finishedAt, usage: draft.usage, costUSD: draft.costUSD)138            try step.insert(db)139            run.stepCount += 1140            if draft.kind == .toolCall { run.toolCallCount += 1 }141            if let usage = draft.usage { run.usage = Self.sum(run.usage, usage) }142            if let cost = draft.costUSD { run.costUSD = (run.costUSD ?? 0) + cost }143            try run.updateByID(db)144            return step145        }146    }147148    /// Completes a step that was recorded before its outcome was known (a tool call's result, an approval's decision).149    func completeAgentStep(id: String, output: JSONValue? = nil, approval: ApprovalDecision? = nil, text: String? = nil,150                           at date: Date = Date()) async throws {151        try await write { db in152            var step = try AgentStepRecord.require(db, id: id)153            if let output { step.outputJSON = Self.redactedJSON(output) }154            if let approval { step.approval = approval }155            if let text { step.text = Redactor.redact(text) }156            step.finishedAt = date157            try step.updateByID(db)158        }159    }160161    func setAgentRunStatus(id: String, _ status: AgentRunStatus, result: String? = nil, error: String? = nil, at date: Date = Date()) async throws {162        try await write { db in163            var run = try AgentRunRecord.require(db, id: id)164            run.status = status165            if let result { run.result = Redactor.redact(result) }166            if let error { run.error = Redactor.redact(error) }167            run.finishedAt = status.isFinished ? date : nil168            try run.updateByID(db)169        }170    }171172    /// Runs left `running` or `awaitingApproval` by a process that died are closed as cancelled. Call once at launch.173    @discardableResult174    func recoverInterruptedAgentRuns(at date: Date = Date()) async throws -> Int {175        try await write { db in176            try db.execute(sql: "UPDATE agentRun SET status = 'cancelled', finishedAt = ? WHERE status IN ('running', 'awaitingApproval')",177                           arguments: [date.dbValue])178            return db.changesCount179        }180    }181182    func agentRun(id: String) async throws -> AgentRunRecord? { try await read { db in try AgentRunRecord.find(db, id: id) } }183184    /// Most recent first, for one profile or all.185    func agentRuns(profileID: String? = nil, limit: Int? = nil) async throws -> [AgentRunRecord] {186        try await read { db in187            if let profileID {188                return try AgentRunRecord.fetchAll(db, sql: "SELECT * FROM agentRun WHERE profileID = ? ORDER BY startedAt DESC, id LIMIT ?",189                                                   arguments: [profileID, limit ?? -1])190            }191            return try AgentRunRecord.fetchAll(db, sql: "SELECT * FROM agentRun ORDER BY startedAt DESC, id LIMIT ?", arguments: [limit ?? -1])192        }193    }194195    func agentSteps(runID: String) async throws -> [AgentStepRecord] {196        try await read { db in try AgentStepRecord.fetchAll(db, sql: "SELECT * FROM agentStep WHERE runID = ? ORDER BY ordinal", arguments: [runID]) }197    }198199    func deleteAgentRun(id: String) async throws { try await write { db in _ = try AgentRunRecord.remove(db, id: id) } }200201    /// Writes a usage ledger row for a finished run from its totals.202    func recordAgentRunUsage(runID: String, at date: Date = Date()) async throws {203        try await write { db in204            let run = try AgentRunRecord.require(db, id: runID)205            guard let model = run.model else { return }206            let cost = run.costUSD.map { CostEstimate(amountUSD: $0, basis: .estimatedFromUsage) }207            try UsageRecord(id: AstraID.new(), date: date, model: model, usage: run.usage, cost: cost, origin: .agent, originID: run.id).insert(db)208        }209    }210}211212extension AstraStore {213    /// Serializes then redacts, so secrets in keys' values (`"api_key": "…"`), bearer tokens and provider keys never reach the disk.214    static func redactedJSON(_ value: JSONValue) -> String { Redactor.redact(redactSensitiveKeys(value).serialized()) }215216    private static let sensitiveKeyFragments = ["password", "passwd", "secret", "token", "apikey", "api_key", "api-key", "authorization", "cookie", "credential"]217218    /// Values under keys that name a credential are dropped whatever their length (the pattern-based redactor needs six characters).219    static func redactSensitiveKeys(_ value: JSONValue) -> JSONValue {220        switch value {221        case .object(let object):222            var out: [String: JSONValue] = [:]223            for (key, item) in object {224                let lower = key.lowercased()225                let scalar = item.arrayValue == nil && item.objectValue == nil && !item.isNull226                if scalar, item.boolValue == nil, sensitiveKeyFragments.contains(where: lower.contains), !lower.hasSuffix("tokens") {227                    out[key] = "•••"228                } else {229                    out[key] = redactSensitiveKeys(item)230                }231            }232            return .object(out)233        case .array(let array): return .array(array.map(redactSensitiveKeys))234        default: return value235        }236    }237238    static func sum(_ a: TokenUsage, _ b: TokenUsage) -> TokenUsage {239        func add(_ x: Int?, _ y: Int?) -> Int? { x == nil && y == nil ? nil : (x ?? 0) + (y ?? 0) }240        let cost: Double? = a.reportedCostUSD == nil && b.reportedCostUSD == nil ? nil : (a.reportedCostUSD ?? 0) + (b.reportedCostUSD ?? 0)241        return TokenUsage(inputTokens: add(a.inputTokens, b.inputTokens), outputTokens: add(a.outputTokens, b.outputTokens),242                          cachedInputTokens: add(a.cachedInputTokens, b.cachedInputTokens), cacheWriteTokens: add(a.cacheWriteTokens, b.cacheWriteTokens),243                          reasoningTokens: add(a.reasoningTokens, b.reasoningTokens), reportedCostUSD: cost)244    }245}246
Files main
Menu

Theme