Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet for macOS9// File : Features/TradingAgents/AgentsStore.swift10// Description : The shared read state of the agents section: the list of11// agents, the runtime of the agent engine (workers, leases,12// loops, queue), the kill switch as the server states it,13// the templates and the server locks. It only reads; the one14// operation it carries is the emergency stop (engage: no15// passkey; release: the Core's verified passkey approval).16// Module : Features17// Repository : https://git.spboucher.ai/sp-wallet-macos18// Created : 2026-11-1819// Last Modified : 2026-11-1820//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author : Simon-Pierre Boucher26// Position : Professor of Finance27// Institution : Université du Québec en Outaouais (UQO)28// Department : Département des sciences administratives29// Organization : SP Boucher30//31// Website : https://spboucher.ai32// Git : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General : info@spboucher.ai39// Professional : contact@spboucher.ai40// Direct : simon@spboucher.ai41// Research : research@spboucher.ai42// Development : dev@spboucher.ai43// Support : support@spboucher.ai44// Security/Admin : admin@spboucher.ai45// Notifications : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification : Public72// Distribution : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License : None specified (no license file in this repository)86// Maintainer : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import Foundation94import SPWalletCore9596@MainActor @Observable final class AgentsStore {97 let model: AppModel98 let api: AgentsAPI99 let risk: RiskAPI100 let developer: DeveloperAPI101102 private(set) var agents: [Agent]?103 private(set) var agentsAt: Date?104 private(set) var agentsFromCache = false105 private(set) var agentsError: String?106 private(set) var runtime: AgentRuntimeStatus?107 private(set) var runtimeError: String?108 private(set) var templates: AgentTemplates?109 private(set) var templatesError: String?110 /// Every server lock with its state and the server's sentence (from the developer status route).111 private(set) var locks: [ExecutionLock]?112 private(set) var locksError: String?113 private(set) var loading = false114115 // emergency stop116 private(set) var killBusy = false117 var killError: String?118 private(set) var release: RiskSwitchReleaseApproval?119 private(set) var releasing = false120121 init(model: AppModel) {122 self.model = model123 api = AgentsAPI(model.client); risk = RiskAPI(model.client); developer = DeveloperAPI(model.client)124 }125126 /// The kill switch as last stated by the server; nil = unknown (never assumed released).127 var killSwitch: AgentKillSwitchState? { runtime?.killSwitch }128129 func lock(_ id: String) -> ExecutionLock? { locks?.first { $0.id == id } }130131 func loadCache() async {132 guard agents == nil, let s: Snapshot<[Agent]> = await SnapshotStore.shared.load("agents.list") else { return }133 if agents == nil { agents = s.value; agentsAt = s.savedAt; agentsFromCache = true }134 }135136 func refresh() async {137 guard model.phase == .signedIn, !loading else { return }138 loading = true; defer { loading = false }139 let api = api, developer = developer140 async let a = Result.catching { try await api.list() }141 async let r = Result.catching { try await api.runtimeStatus() }142 async let l = Result.catching { try await developer.status() }143 switch await a {144 case .success(let v): agents = v; agentsAt = Date(); agentsFromCache = false; agentsError = nil; await SnapshotStore.shared.save(v, as: "agents.list")145 case .failure(let e): agentsError = model.describe(e); if agents != nil { agentsFromCache = true }146 }147 switch await r {148 case .success(let v): runtime = v; runtimeError = nil149 case .failure(let e): runtimeError = model.describe(e)150 }151 switch await l {152 case .success(let v): locks = v.capabilities; locksError = v.capabilities == nil ? "Le serveur n’a pas publié l’état de ses verrous." : nil153 case .failure(let e): locksError = model.describe(e)154 }155 if templates == nil { await loadTemplates() }156 }157158 func loadTemplates() async {159 do { templates = try await api.templates(); templatesError = nil } catch { templatesError = model.describe(error) }160 }161162 /// Reads while the screen is visible and the app is active; nothing is fetched in the background.163 func poll() async {164 await loadCache()165 await refresh()166 while !Task.isCancelled {167 try? await Task.sleep(for: .seconds(20))168 guard !Task.isCancelled else { return }169 if AppActivity.isActive, !model.isOffline { await refresh() }170 }171 }172173 // MARK: emergency stop174175 /// One click + confirmation, no passkey: no agent, key or mandate can add risk until the owner releases it.176 func engageKillSwitch() async {177 guard !killBusy else { return }178 killBusy = true; killError = nil; defer { killBusy = false }179 do {180 let s = try await api.engageKillSwitch(reason: "engagé par le propriétaire depuis l’app macOS")181 if !s.engaged { killError = "Le serveur n’a PAS confirmé l’arrêt d’urgence. Vérifiez l’état ci-dessous et réessayez." }182 else { Notifier.post(title: "Arrêt d’urgence des agents engagé", body: "Aucun agent, clé ou mandat ne peut ajouter de risque tant qu’il n’est pas levé.") }183 } catch { killError = model.describe(error) }184 await refresh()185 }186187 /// Step 1 of a release: the switch as displayed is read from the risk engine, and the release intent must name that very engagement.188 func prepareRelease() async {189 guard model.canOperate, !killBusy else { return }190 killBusy = true; killError = nil; defer { killBusy = false }191 do {192 let state = try await risk.state()193 switch try await risk.prepareRelease(.killSwitch, displayed: state.switches.killSwitch) {194 case .notEngaged: killError = "L’arrêt d’urgence n’est pas engagé : il n’y a rien à lever."; await refresh()195 case .approval(let a): release = a196 }197 } catch { killError = model.describe(error) }198 }199200 func cancelRelease() { release = nil; killError = nil }201202 func approveRelease() async {203 guard let a = release, !releasing else { return }204 releasing = true; killError = nil; defer { releasing = false }205 do {206 let s = try await risk.release(a, with: model.authenticator)207 release = nil208 if s.killSwitch.on { killError = "Le serveur indique que l’arrêt d’urgence est toujours engagé." }209 else { Notifier.post(title: "Arrêt d’urgence levé", body: "Les agents ne reprennent pas seuls : chaque agent se relance explicitement.") }210 await refresh()211 } catch PasskeyError.cancelled {212 } catch {213 killError = model.describe(error)214 // the answer may have been lost: read the real state instead of signing again215 await refresh()216 if killSwitch?.engaged == false { release = nil; killError = nil }217 }218 }219}220221extension Result where Failure == Error {222 /// Runs an async throwing read and keeps its outcome, so that several reads can fail independently.223 static func catching(_ body: @Sendable () async throws -> Success) async -> Result<Success, Error> where Success: Sendable {224 do { return .success(try await body()) } catch { return .failure(error) }225 }226}227