Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraUI/Sources/Agents/AgentsController.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 AstraCore91import AstraAgents92import AstraPersistence93import AstraDesign9495/// A run the app was closed in the middle of, with the checkpoint that can continue it.96struct AgentResumableRun: Identifiable, Sendable {97 let run: AgentRunRecord98 let checkpoint: AgentCheckpoint99 /// Nil when the profile was deleted since: the run can then only be discarded.100 let profile: AgentProfile?101 var id: String { run.id }102}103104/// State of the Agents tab: profiles, the run in progress, runs that can be resumed. One instance per app model, kept for the105/// life of the process so a run keeps going while the person looks at another screen.106@MainActor @Observable final class AgentsController {107 private static var instances: [ObjectIdentifier: AgentsController] = [:]108109 static func shared(for app: AppModel) -> AgentsController {110 let key = ObjectIdentifier(app)111 if let existing = instances[key] { return existing }112 let created = AgentsController(app: app)113 instances[key] = created114 return created115 }116117 static let seededKey = "agents.starters.seeded"118119 let app: AppModel120 let approvals = AgentApprovalBroker()121 let files = AgentFileAccess()122123 private(set) var profiles: [AgentProfile] = []124 private(set) var recentRuns: [AgentRunRecord] = []125 private(set) var resumable: [AgentResumableRun] = []126 /// The run in progress, or the last one finished in this session (kept so its result stays readable).127 private(set) var session: AgentRunSession?128 private(set) var isLoaded = false129 private(set) var isStarting = false130 var loadError: String?131132 @ObservationIgnored private var createdAt: [String: Date] = [:]133 @ObservationIgnored private var didRecover = false134 @ObservationIgnored private var filesOwner: String?135136 private var store: AstraStore { app.store }137138 private init(app: AppModel) {139 self.app = app140 approvals.onRequest = { [weak app] request in141 guard let app, app.tab != .agents else { return }142 app.show("An agent is waiting for your approval in Agents.", .info)143 }144 }145146 var activeSession: AgentRunSession? { session?.isRunning == true ? session : nil }147148 func profile(id: String) -> AgentProfile? { profiles.first { $0.id == id } }149150 // MARK: Loading151152 func load() async {153 do {154 if !didRecover {155 // Runs left open by a process that died are closed here, once; those with a checkpoint are offered for resuming.156 didRecover = true157 if activeSession == nil { _ = try await store.recoverInterruptedAgentRuns() }158 }159 try await reloadProfiles()160 try await seedStartersIfNeeded()161 try await seedResearcherIfNeeded()162 try await reloadRuns()163 loadError = nil164 } catch {165 loadError = AstraError.wrap(error).message166 }167 isLoaded = true168 }169170 private func reloadProfiles() async throws {171 let records = try await store.agentProfiles()172 var loaded: [AgentProfile] = []173 for record in records {174 let extras: AgentProfileExtras = (try await store.setting(AgentProfileExtras.key(record.id))) ?? AgentProfileExtras()175 loaded.append(AgentProfile(record: record, extras: extras))176 createdAt[record.id] = record.createdAt177 }178 profiles = loaded179 }180181 func reloadRuns() async throws {182 recentRuns = try await store.agentRuns(limit: 6)183 var found: [AgentResumableRun] = []184 let prefix = AgentRunSession.checkpointKey("")185 for key in try await store.settingKeys() where key.hasPrefix(prefix) {186 let runID = String(key.dropFirst(prefix.count))187 if activeSession?.recordID == runID { continue }188 guard let run = try await store.agentRun(id: runID), let data: Data = try await store.setting(key),189 let checkpoint = try? AgentCheckpoint.decode(data) else {190 // The run was deleted, or the checkpoint comes from a newer version: nothing can continue it.191 try await store.removeSetting(key)192 continue193 }194 found.append(AgentResumableRun(run: run, checkpoint: checkpoint, profile: run.profileID.flatMap(profile(id:))))195 }196 resumable = found.sorted { $0.run.startedAt > $1.run.startedAt }197 }198199 // MARK: Profiles200201 /// The model a new agent starts with: one that declares tool support when there is one, otherwise the usual default.202 func preferredModel() -> ModelRef? {203 let library = app.library204 let candidates = library.recentModels + library.favoriteModels + library.selectable205 return candidates.first { $0.capabilities.contains(.tools) && library.availability(of: $0.ref) == nil }?.ref ?? library.defaultModel()206 }207208 func newProfileDraft() -> AgentProfile? {209 guard let model = preferredModel() else { return nil }210 return AgentProfile(name: "", model: model, allowedTools: ["calculator", "datetime"])211 }212213 func save(_ profile: AgentProfile) async throws {214 var clean = profile215 clean.name = profile.name.trimmingCharacters(in: .whitespacesAndNewlines)216 clean.preApprovedWebHosts = clean.usesWeb ? profile.preApprovedWebHosts : []217 try await store.saveAgentProfile(clean.record(createdAt: createdAt[clean.id] ?? Date()))218 try await store.setSetting(AgentProfileExtras.key(clean.id), clean.extras)219 try await reloadProfiles()220 }221222 @discardableResult func duplicate(_ profile: AgentProfile) async throws -> AgentProfile {223 var copy = profile224 copy.id = UUID().uuidString225 copy.name = profile.name + " copy"226 try await save(copy)227 return copy228 }229230 /// Deletes the profile. Its runs stay in the history under the profile's name.231 func delete(_ profile: AgentProfile) async throws {232 try await store.deleteAgentProfile(id: profile.id)233 try await store.removeSetting(AgentProfileExtras.key(profile.id))234 createdAt[profile.id] = nil235 if let session, !session.isRunning, session.profile.id == profile.id { self.session = nil }236 try await reloadProfiles()237 try await reloadRuns()238 }239240 /// Three working agents on first use. They are ordinary profiles: edit, duplicate or delete them freely.241 private func seedStartersIfNeeded() async throws {242 guard try await store.setting(Self.seededKey, default: false) == false else { return }243 guard profiles.isEmpty else { try await store.setSetting(Self.seededKey, true); return }244 guard let model = preferredModel() else { return } // retried on the next visit, once a model exists245 for starter in Self.starters(model: model) {246 try await store.saveAgentProfile(starter.record())247 try await store.setSetting(AgentProfileExtras.key(starter.id), starter.extras)248 }249 try await store.setSetting(Self.seededKey, true)250 try await reloadProfiles()251 }252253 static let researcherSeededKey = "agents.starters.researcher.seeded"254255 /// The research agent added in 2.0, offered once to everyone (new installs and people who already had the first three).256 private func seedResearcherIfNeeded() async throws {257 guard try await store.setting(Self.researcherSeededKey, default: false) == false else { return }258 guard let model = preferredModel() else { return }259 let starter = Self.researcher(model: model)260 if !profiles.contains(where: { $0.name == starter.name }) {261 try await store.saveAgentProfile(starter.record())262 try await store.setSetting(AgentProfileExtras.key(starter.id), starter.extras)263 }264 try await store.setSetting(Self.researcherSeededKey, true)265 try await reloadProfiles()266 }267268 /// Research mode: search, read the sources, compare them, report with provenance. Sub-agents for independent threads.269 static func researcher(model: ModelRef) -> AgentProfile {270 AgentProfile(name: "Web researcher", instructions: """271 You research a question on the web and report what the sources say. Work like this: plan the angles to cover; search each one; \272 fetch the most relevant pages and read them (a search excerpt is a lead, not a source); note for every fact the address it \273 comes from; look for sources that disagree and say so. For a broad question, hand independent angles to research sub-agents and \274 have a verification sub-agent check the key claims.275 Write the report with these parts: a short answer; the findings, each followed by the address it comes from; where the sources \276 contradict each other; what you could not verify. Cite only pages you actually fetched in this run. Never invent a source, a \277 quotation or an address, and never present a guess as a finding.278 """, model: model, allowedTools: ["web_search", "web_fetch", "document_search", "text_stats", "datetime"],279 budgets: AgentBudgets(maxSteps: 16, maxToolCalls: 40, maxOutputTokensPerTurn: 4_096, wallClockLimit: 1_200),280 autonomy: .balanced, delegation: DelegationPolicy(enabled: true, maxParallel: 2, maxStepsPerDelegate: 5))281 }282283 static func starters(model: ModelRef) -> [AgentProfile] {284 [285 AgentProfile(name: "Research assistant", instructions: """286 You are a careful research assistant. Search the user's imported documents before answering, and search again with different \287 words when the first passages do not answer the question. Quote the passages you rely on and cite them as [1], [2]. \288 When the documents do not contain the answer, say so plainly instead of guessing. End with what you could not verify.289 """, model: model, allowedTools: ["document_search", "text_stats", "regex_extract", "datetime"],290 budgets: AgentBudgets(maxSteps: 12, maxToolCalls: 24, maxOutputTokensPerTurn: 2_048, wallClockLimit: 600)),291 AgentProfile(name: "Analyst", instructions: """292 You are a quantitative analyst. Never do arithmetic in your head: use calculator for every figure and data_transform for tables. \293 State the units of each number, show the expressions you evaluated, and separate what the data shows from your interpretation. \294 If the data given is not enough to answer, say exactly what is missing.295 """, model: model, allowedTools: ["calculator", "data_transform", "unit_convert", "text_stats", "datetime"],296 budgets: AgentBudgets(maxSteps: 12, maxToolCalls: 30, maxOutputTokensPerTurn: 2_048, wallClockLimit: 600)),297 AgentProfile(name: "Writing helper", instructions: """298 You help with writing. Read the files the user shared before proposing changes, keep the author's voice, and explain your main \299 edits in a few lines. Propose saving a file only when the user asked for a document, with a plain file name such as draft.md.300 """, model: model, allowedTools: ["read_file", "write_file", "text_stats", "regex_extract"],301 budgets: AgentBudgets(maxSteps: 10, maxToolCalls: 20, maxOutputTokensPerTurn: 4_096, wallClockLimit: 900)),302 ]303 }304305 // MARK: Runs306307 /// Why a profile cannot run right now, or nil.308 func blocker(for profile: AgentProfile) -> AstraError? { app.library.availability(of: profile.model) }309310 private func runner(for profile: AgentProfile) -> AgentRunner {311 // A tool exists in a run only when the profile lists it: no file service without a file tool, no network without web_fetch.312 let credentials = app.credentials313 let registry = ToolRegistry.standard(documents: AgentDocumentSearch(store: store), files: profile.usesFiles ? files : nil,314 web: profile.usesWeb ? AgentWebFetcher() : nil,315 conversations: profile.allowedTools.contains("conversation_search") ? AgentConversationSearch(store: store) : nil,316 memory: profile.usesMemory ? AgentMemoryStore(store: store) : nil,317 search: profile.usesSearch ? TavilySearch(transport: app.transport, key: { try credentials.secret(for: TavilySearch.account) }) : nil)318 return AgentRunner(orchestrator: app.orchestrator, registry: registry, approvals: approvals)319 }320321 /// The profile as it runs: the model's real limits are applied on top of what the person set.322 private func effective(_ profile: AgentProfile) -> AgentProfile {323 var out = profile324 let info = app.library.info(for: profile.model)325 out.contextWindow = info?.contextLength326 if let cap = info?.maxOutputTokens, let wanted = out.budgets.maxOutputTokensPerTurn, wanted > cap { out.budgets.maxOutputTokensPerTurn = cap }327 // A model known to have no tool calling runs without tools (the run screen says so) rather than fail at the provider.328 if let info, !info.capabilities.contains(.tools) { out.allowedTools = []; out.planningEnabled = false; out.delegation.enabled = false }329 return out330 }331332 /// What is known about the profile's model, for the pre-run check. Unknown stays unknown.333 func modelFacts(for profile: AgentProfile) -> AgentModelFacts {334 let info = app.library.info(for: profile.model)335 return AgentModelFacts(isOnDevice: profile.model.provider.isLocal, supportsTools: info.map { $0.capabilities.contains(.tools) },336 contextLength: info?.contextLength, supportsVision: info.map { $0.capabilities.contains(.vision) },337 supportsReasoning: info.map { $0.capabilities.contains(.reasoning) })338 }339340 /// What this model can and cannot do for this agent, before a run starts.341 func compatibility(for profile: AgentProfile) -> AgentCompatibility {342 let running = effective(profile)343 return AgentCompatibility.check(profile: running, facts: modelFacts(for: profile), offered: runner(for: running).offeredTools(for: running))344 }345346 var hasSearchKey: Bool { ((try? app.credentials.secret(for: TavilySearch.account)) ?? nil)?.isEmpty == false }347348 func setSearchKey(_ key: String?) throws {349 let clean = key?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""350 if clean.isEmpty { try app.credentials.removeSecret(for: TavilySearch.account) } else { try app.credentials.setSecret(clean, for: TavilySearch.account) }351 }352353 /// Starts a run. Returns false (with a message on screen) when it could not start.354 @discardableResult func start(profile: AgentProfile, goal: String) async -> Bool {355 let goal = goal.trimmingCharacters(in: .whitespacesAndNewlines)356 guard !goal.isEmpty, !isStarting else { return false }357 guard activeSession == nil else { app.show("Another agent is still running. Stop it or wait for it to finish.", .error); return false }358 if let blocker = blocker(for: profile) { app.show(blocker.message, .error); return false }359 if let blocking = compatibility(for: profile).issues.first(where: { $0.severity == .blocking }) { app.show(blocking.message, .error); return false }360 if profile.usesSearch, !hasSearchKey { app.show("Web search needs a Tavily key. Add it in this agent's settings, or turn the tool off.", .error); return false }361 isStarting = true362 defer { isStarting = false }363 do {364 let record = try await store.startAgentRun(profile: profile.record(createdAt: createdAt[profile.id] ?? Date()), goal: goal)365 let running = effective(profile)366 let session = AgentRunSession(profile: running, goal: goal, recordID: record.id, store: store)367 filesOwner = profile.id368 launch(session, run: runner(for: running).start(profile: running, goal: goal, pricing: app.library.info(for: running.model)?.pricing))369 return true370 } catch {371 app.show(AstraError.wrap(error).message, .error)372 return false373 }374 }375376 /// Continues an interrupted run from its checkpoint, under the profile as it is now.377 @discardableResult func resume(_ item: AgentResumableRun) async -> Bool {378 guard !isStarting else { return false }379 guard let profile = item.profile else { app.show("This agent was deleted, so its run cannot continue.", .error); return false }380 guard activeSession == nil else { app.show("Another agent is still running. Stop it or wait for it to finish.", .error); return false }381 if let blocker = blocker(for: profile) { app.show(blocker.message, .error); return false }382 isStarting = true383 defer { isStarting = false }384 do {385 try await store.setAgentRunStatus(id: item.run.id, .running)386 files.releaseAll()387 filesOwner = profile.id388 let running = effective(profile)389 let session = AgentRunSession(profile: running, goal: item.checkpoint.goal, recordID: item.run.id, store: store, resumedFrom: item.checkpoint)390 launch(session, run: runner(for: running).start(profile: running, goal: item.checkpoint.goal,391 pricing: app.library.info(for: running.model)?.pricing, resumeFrom: item.checkpoint))392 resumable.removeAll { $0.id == item.id }393 return true394 } catch {395 app.show(AstraError.wrap(error).message, .error)396 return false397 }398 }399400 private func launch(_ session: AgentRunSession, run: AgentRun) {401 self.session = session402 app.library.noteUsed(session.profile.model)403 session.begin(run) { [weak self] finished in404 guard let self else { return }405 // Access to the shared files ends with the run.406 self.files.releaseAll()407 self.filesOwner = nil408 self.approvals.resolve(.deny(reason: nil))409 try? await self.reloadRuns()410 if self.app.tab != .agents, let outcome = finished.outcome {411 self.app.show("\(finished.profile.name): \(outcome.stored.label.lowercased()).", outcome == .completed ? .success : .info)412 }413 }414 }415416 func stopActiveRun() { activeSession?.stop() }417418 /// Files are shared with one agent's next run. Opening another agent's screen while nothing runs ends the earlier sharing.419 func prepareFiles(for profileID: String) {420 guard activeSession == nil, filesOwner != profileID else { return }421 files.releaseAll()422 filesOwner = profileID423 }424425 /// Clears a finished run from the run screen so a new goal can be entered.426 func clearFinishedSession() {427 guard let session, !session.isRunning else { return }428 self.session = nil429 }430431 /// Gives up an interrupted run: its checkpoint is erased, the audit trail stays in the history.432 func discard(_ item: AgentResumableRun) async {433 do {434 try await store.removeSetting(AgentRunSession.checkpointKey(item.run.id))435 resumable.removeAll { $0.id == item.id }436 } catch { app.show(AstraError.wrap(error).message, .error) }437 }438439 func runs(profileID: String?) async throws -> [AgentRunRecord] { try await store.agentRuns(profileID: profileID, limit: 200) }440441 func deleteRun(id: String) async throws {442 guard activeSession?.recordID != id else { throw AstraError.invalidRequest("Stop this run before deleting it.") }443 try await store.deleteAgentRun(id: id)444 try await store.removeSetting(AgentRunSession.checkpointKey(id))445 if session?.recordID == id { session = nil }446 try await reloadRuns()447 }448}449