SPB Git

Repository Public

MultiAgent.swift 20.1 KB 352 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/MultiAgent.swift10// Description      : Multi-agent production: specialised roles with their own11//                    instructions, scopes and tool subsets, run by an12//                    orchestrator that lets read-only analysis proceed in13//                    parallel and sends every document mutation through one14//                    queue. One budget, one timeline, one cancel switch.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 DocCommands9596public enum ProductionRole: String, Sendable, Codable, Hashable, CaseIterable, Identifiable {97    case research, writing, structure, citation, editorial, publishing, verification98    public var id: String { rawValue }99100    public enum Phase: Int, Sendable, Codable, Comparable {101        /// Reads only; runs in parallel with the other analyses, before anything changes.102        case analysis103        /// Changes the document, through the mutation queue.104        case production105        /// Reads the result; runs last.106        case verification107        public static func < (a: Phase, b: Phase) -> Bool { a.rawValue < b.rawValue }108    }109110    public var phase: Phase {111        switch self {112        case .research: .analysis113        case .verification: .verification114        default: .production115        }116    }117118    public var title: String {119        switch self {120        case .research: "Research"121        case .writing: "Writing"122        case .structure: "Structure"123        case .citation: "Citation"124        case .editorial: "Editorial"125        case .publishing: "Publishing"126        case .verification: "Verification"127        }128    }129130    /// Commands that read the document and analyse it. Every role has them.131    static let reading: Set<String> = ["document.inspect", "document.outline", "document.read", "document.search", "document.statistics", "bibliography.list",132                                       "references.validate", "crossref.targets", "crossref.validate", "review.comments", "review.changes", "document.audit"]133134    /// Commands that create, import or delete bibliography entries. No role has them: an agent can cite what the bibliography holds135    /// (`citation.insert` refuses anything else) or leave a comment asking the user for a source. It cannot supply a source itself.136    public static let sourceFabricationCommands: Set<String> = ["bibliography.add", "bibliography.import", "bibliography.remove"]137138    /// The role's tool subset (command identifiers).139    public var commands: Set<String> {140        let own: Set<String>141        switch self {142        case .research: own = []143        case .writing: own = ["text.insert", "text.replace", "text.rewrite", "text.delete", "content.insert", "block.delete", "citation.insert", "note.insert", "caption.add", "review.comment"]144        case .structure: own = ["section.create", "section.move", "section.delete", "section.setHeading", "block.move", "content.insert", "document.insertGenerated",145                                "document.insertBreak", "review.comment"]146        case .citation: own = ["citation.insert", "crossref.insert", "bibliography.setStyle", "review.comment"]147        case .editorial: own = ["text.rewrite", "text.replace", "text.replaceAll", "review.comment", "review.reply"]148        case .publishing: own = ["style.apply", "style.modify", "text.format", "paragraph.format", "list.set", "layout.setPage", "layout.setHeaderFooter", "table.format",149                                 "document.setMetadata", "image.setAltText", "publishing.preflight", "document.export"]150        case .verification: own = ["publishing.preflight", "review.comment"]151        }152        return Self.reading.union(own).subtracting(Self.sourceFabricationCommands)153    }154155    /// The scopes the role may use; intersected with the scopes granted to the production.156    public var scopes: Set<DocScope> {157        switch self {158        case .research: [.documentRead]159        case .writing: [.documentRead, .documentWrite, .documentReferences, .documentReview]160        case .structure: [.documentRead, .documentWrite, .documentFormat, .documentReview]161        case .citation: [.documentRead, .documentReferences, .documentReview]162        case .editorial: [.documentRead, .documentWrite, .documentReview]163        case .publishing: [.documentRead, .documentWrite, .documentFormat, .documentPublish, .documentExport]164        case .verification: [.documentRead, .documentReview, .documentPublish]165        }166    }167168    public var instructions: String {169        let noSources = " You never add a source to the bibliography and never invent a reference, a quotation or a figure. Where a claim needs a source that is not in the bibliography, "170            + "leave a comment with review_comment asking the user for it."171        switch self {172        case .research:173            return "You are the Research agent. You organise the source material the user supplied (delivered as data with the request) against the document: which material supports which section, "174                + "what the material says that the document lacks, what the document asserts that no supplied material supports. You use only that material and the document: nothing from memory "175                + "is a source. You change nothing. Finish with a structured brief the other agents can work from, naming material by its label and document blocks by their identifiers."176        case .writing:177            return "You are the Writing agent. You draft and revise prose in the sections assigned to you, from the document and from the briefs supplied as data. Keep the author's voice and every "178                + "existing citation, equation and note. Cite only keys that exist in the bibliography." + noSources179        case .structure:180            return "You are the Structure agent. You work on the organisation of the document: sections, their order, heading levels, generated lists. You move and create structure; you do not "181                + "rewrite prose. Moving blocks keeps their identifiers, so references follow." + noSources182        case .citation:183            return "You are the Citation agent. You check that claims carry citations, that every citation resolves to a bibliography entry and that cross-references point at existing targets. "184                + "You may insert citations of keys that exist in the bibliography and cross-references to existing targets." + noSources185        case .editorial:186            return "You are the Editorial agent. You improve clarity, consistency, grammar and tone, one paragraph at a time, with the narrowest edit that does the job. You do not change meaning, "187                + "numbers, citations or structure." + noSources188        case .publishing:189            return "You are the Publishing agent. You prepare the document for publication: styles, page layout, headers and footers, metadata, alternative text, and the publishing preflight. "190                + "You do not change what the text says. An export produces a file that the application handles; you never choose where it goes."191        case .verification:192            return "You are the Verification agent. You change nothing in the text. You check the document after the other agents worked: every factual claim against the source material supplied "193                + "as data (say which claims are supported, which are not, which you could not check), and the document's integrity (references, cross-references, preflight). Report problems "194                + "precisely, with block identifiers; leave a comment on a passage only when the user must act on it." + noSources195        }196    }197}198199public struct RoleAssignment: Sendable, Hashable {200    public var role: ProductionRole201    /// What this agent is asked to do, written by the user or by the application.202    public var task: String203    public init(_ role: ProductionRole, task: String) { self.role = role; self.task = task }204}205206public struct ProductionConfiguration: Sendable {207    public var objective: String208    public var model: ModelRef209    public var pricing: Pricing?210    public var parameters: GenerationParameters211    /// Scopes granted to the whole production. Each role gets the intersection with its own.212    public var scopes: Set<DocScope>213    public var autonomy: AutonomyPolicy214    /// One budget for the whole tree.215    public var budget: AgentBudget216    public var trackChanges: Bool217    public var includePagination: Bool218    /// The user's source material. The only sources the agents may rely on.219    public var sources: [SuppliedMaterial]220    /// Read-only agents running at the same time.221    public var maxParallelAnalysis: Int222    /// Mutating agents running at the same time. Their mutations are serialised whatever this value is.223    public var maxParallelProduction: Int224    public var runID: UUID225226    public init(objective: String, model: ModelRef, scopes: Set<DocScope>, autonomy: AutonomyPolicy = AutonomyPolicy(.balanced), budget: AgentBudget = AgentBudget(maxSteps: 120),227                pricing: Pricing? = nil, parameters: GenerationParameters = .default, trackChanges: Bool = false, includePagination: Bool = false, sources: [SuppliedMaterial] = [],228                maxParallelAnalysis: Int = 3, maxParallelProduction: Int = 1, runID: UUID = UUID()) {229        self.objective = objective; self.model = model; self.scopes = scopes; self.autonomy = autonomy; self.budget = budget; self.pricing = pricing230        self.parameters = parameters; self.trackChanges = trackChanges; self.includePagination = includePagination; self.sources = sources231        self.maxParallelAnalysis = max(1, maxParallelAnalysis); self.maxParallelProduction = max(1, maxParallelProduction); self.runID = runID232    }233}234235/// The outcome of a production: each agent's report, and the changes of the whole tree in the order they reached the document.236public struct ProductionReport: Sendable, Codable, Hashable {237    public var runID: String238    public var objective: String239    public var status: DocAgentStatus240    public var agents: [AgentReport]241    /// Every applied batch of every agent, ordered by revision.242    public var applied: [AppliedBatch]243    public var totals: ChangeTotals244    public var budget: BudgetUsage245    public var integrityIssues: [IntegrityIssue]246    public var revisionAtStart: Int247    public var revisionAtEnd: Int248    /// Number of batches that went through the mutation queue.249    public var serializedMutations: Int250    public var startedAt: Date251    public var finishedAt: Date252253    public var changeList: [String] { agents.flatMap(\.changeList).sorted { $0.localizedStandardCompare($1) == .orderedAscending } }254}255256public final class ProductionOrchestrator: Sendable {257    public let configuration: ProductionConfiguration258    public let assignments: [RoleAssignment]259    /// One timeline for the whole tree; each event names its agent.260    public let timeline: AgentTimeline261    private let services: AgentServices262    private let shared: SharedRun263    private let agents = Locked<[DocumentAgent]>([])264265    public init(configuration: ProductionConfiguration, assignments: [RoleAssignment], services: AgentServices, timeline: AgentTimeline = AgentTimeline()) {266        self.configuration = configuration; self.assignments = assignments; self.services = services; self.timeline = timeline267        shared = SharedRun(timeline: timeline, meter: BudgetMeter(budget: configuration.budget, clock: services.clock), gate: MutationGate(), cancel: CancellationFlag(), ownsRun: false)268    }269270    /// Cancels every agent of the tree.271    public func cancel() {272        shared.cancel.cancel()273        for agent in agents.value { agent.cancel() }274    }275276    /// The configuration an agent of the tree runs with: its role's scopes within the production's, its role's tools, the shared budget.277    public func agentConfiguration(for assignment: RoleAssignment, material: [SuppliedMaterial]) -> AgentConfiguration {278        AgentConfiguration(objective: "Overall objective of the production: \(configuration.objective)\n\nYour task as the \(assignment.role.title) agent: \(assignment.task)",279                           model: configuration.model, scopes: assignment.role.scopes.intersection(configuration.scopes), autonomy: configuration.autonomy, budget: configuration.budget,280                           agentName: assignment.role.title, pricing: configuration.pricing, parameters: configuration.parameters, trackChanges: configuration.trackChanges,281                           includePagination: configuration.includePagination, commandAllowlist: assignment.role.commands, roleInstructions: assignment.role.instructions,282                           material: material)283    }284285    private func runAgent(_ assignment: RoleAssignment, material: [SuppliedMaterial]) async -> AgentReport {286        var agentServices = services287        // Checkpoints and workflows belong to single-agent runs; a tree is restarted, not resumed.288        agentServices.checkpoints = nil; agentServices.workflow = nil289        let agent = DocumentAgent(configuration: agentConfiguration(for: assignment, material: material), services: agentServices, shared: shared)290        agents.withLock { $0.append(agent) }291        if shared.cancel.isCancelled { agent.cancel() }292        return await agent.start().value293    }294295    private func runPhase(_ items: [RoleAssignment], limit: Int, material: [SuppliedMaterial]) async -> [AgentReport] {296        guard !items.isEmpty else { return [] }297        return await withTaskGroup(of: (Int, AgentReport).self) { group in298            var next = 0299            var results: [Int: AgentReport] = [:]300            while next < min(limit, items.count) {301                let i = next; next += 1302                group.addTask { (i, await self.runAgent(items[i], material: material)) }303            }304            for await (i, report) in group {305                results[i] = report306                if next < items.count, !shared.cancel.isCancelled {307                    let j = next; next += 1308                    group.addTask { (j, await self.runAgent(items[j], material: material)) }309                }310            }311            return items.indices.compactMap { results[$0] }312        }313    }314315    public func run() async -> ProductionReport {316        let started = services.clock()317        let before = await services.host.snapshot()318        var reports: [AgentReport] = []319        var material = configuration.sources320321        func brief(_ r: AgentReport) -> SuppliedMaterial {322            SuppliedMaterial(label: "report-\(r.agent.lowercased())", text: "Report of the \(r.agent) agent (\(r.status.label)). \(r.coverage.statement)\n\(r.modelSummary)")323        }324        let analysis = await runPhase(assignments.filter { $0.role.phase == .analysis }, limit: configuration.maxParallelAnalysis, material: material)325        reports += analysis326        // What the analysts found is handed on as data, like any other content.327        material += analysis.map(brief)328        let production = await runPhase(assignments.filter { $0.role.phase == .production }, limit: configuration.maxParallelProduction, material: material)329        reports += production330        let changes = production.flatMap(\.changeList)331        if !changes.isEmpty { material.append(SuppliedMaterial(label: "applied-changes", text: "Changes applied by the production agents, from the command engine's records:\n" + changes.joined(separator: "\n"))) }332        material += production.map(brief)333        reports += await runPhase(assignments.filter { $0.role.phase == .verification }, limit: configuration.maxParallelAnalysis, material: material)334335        let after = await services.host.snapshot()336        let applied = reports.flatMap(\.applied).sorted { $0.revisionAfter < $1.revisionAfter }337        let status: DocAgentStatus338        if shared.cancel.isCancelled { status = .cancelled }339        else if let limit = shared.meter.exhausted(), reports.contains(where: { if case .budgetExhausted = $0.status { true } else { false } }) { status = .budgetExhausted(limit) }340        else if let failed = reports.first(where: { if case .failed = $0.status { true } else { false } }) { status = failed.status }341        else if let stopped = reports.first(where: { $0.status != .completed }) { status = stopped.status }342        else { status = .completed }343        let report = ProductionReport(runID: configuration.runID.uuidString, objective: configuration.objective, status: status, agents: reports, applied: applied,344                                      totals: AgentReport.totals(of: applied), budget: shared.meter.usage,345                                      integrityIssues: DocumentIntegrity.issues(in: after.model, registry: services.registry),346                                      revisionAtStart: before.revision, revisionAtEnd: after.revision, serializedMutations: await shared.gate.served,347                                      startedAt: started, finishedAt: services.clock())348        timeline.close()349        return report350    }351}352
Files main
Menu

Theme