Repository Public
1//2// VQuant iOS3// File: VQuant/Next/NextServices.swift4// Description: Composition of everything VQuant Next adds on top of 1.0: the VQuantKit API, the sync centre, and the5// observable stores of the terminal, the Quant Lab, the model registry, portfolios and the studio.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import Foundation12import Observation13import SwiftUI14import VQuantKit15import VQuantUI1617/// Network first, device copy when the network fails — for kit models, which are decoded tolerantly from raw JSON.18struct NextFetcher: Sendable {19 let client: VQClient20 let cache: DiskCache2122 func load<T: VQJSONDecodable>(_ key: String, _ request: VQRequest, as type: T.Type = T.self) async throws -> Loaded<T> {23 do {24 let data = try await client.data(request)25 let json = try VQJSON.parse(data)26 await cache.save("next:" + key, data)27 return Loaded(value: T(json: json), origin: .network, fetchedAt: Date())28 } catch {29 // Only a transport failure falls back to the device copy: a refusal (401, 404…) is a real answer.30 if let e = error as? VQError, !(e.kind == .network || e.kind == .server || e.kind == .unavailable) { throw e }31 guard let hit: Loaded<T> = await cached(key) else { throw error }32 return hit33 }34 }3536 func cached<T: VQJSONDecodable>(_ key: String, as type: T.Type = T.self) async -> Loaded<T>? {37 guard let (data, savedAt) = await cache.load("next:" + key), let json = try? VQJSON.parse(data) else { return nil }38 return Loaded(value: T(json: json), origin: .cache(savedAt: savedAt), fetchedAt: savedAt)39 }40}4142/// A kit value being loaded for a screen.43struct NextState<Value: Sendable>: Sendable {44 var loaded: Loaded<Value>?45 var isLoading = false46 var error: String?47 var value: Value? { loaded?.value }48 var isUnavailable: Bool { loaded == nil && error != nil && !isLoading }49 var cachedAt: Date? { if case .cache(let t)? = loaded?.origin { return t } else { return nil } }5051 mutating func begin() { isLoading = true }52 mutating func succeed(_ l: Loaded<Value>) { loaded = l; error = nil; isLoading = false }53 mutating func fail(_ e: Error) {54 isLoading = false55 if e is CancellationError { return }56 if let u = e as? URLError, u.code == .cancelled { return }57 error = nextMessage(e)58 }59}6061@MainActor62@Observable63final class NextServices {64 let vq: KitAPI65 let fetcher: NextFetcher66 let sync: SyncCenter67 let terminal: TerminalStore68 let lab: LabStore69 let models: ModelStore70 let studio: StudioStore71 let portfolios: PortfolioStore72 let hub: ResearchHub7374 init(client: APIClient, cache: DiskCache, keys: CacheKeyProvider, defaults: UserDefaults, isTest: Bool) {75 let kit = KitAPI(transport: IOSVQTransport(client: client))76 vq = kit77 fetcher = NextFetcher(client: kit.client, cache: cache)78 sync = SyncCenter(client: kit.client, keys: keys, defaults: defaults, isTest: isTest)79 terminal = TerminalStore(vq: kit, fetcher: fetcher)80 lab = LabStore(vq: kit, fetcher: fetcher)81 models = ModelStore(vq: kit, fetcher: fetcher)82 studio = StudioStore(vq: kit, fetcher: fetcher, sync: sync)83 portfolios = PortfolioStore(sync: sync, defaults: defaults)84 hub = ResearchHub(vq: kit, api: client, fetcher: fetcher)85 }8687 func reset() {88 terminal.reset(); lab.reset(); models.reset(); studio.reset(); hub.reset()89 sync.wipe()90 }91}9293// MARK: - Terminal (market overview, universal search, statements)9495@MainActor96@Observable97final class TerminalStore {98 private let vq: KitAPI99 private let fetcher: NextFetcher100 var overview = NextState<VQMarketOverview>()101 var health = NextState<VQDataHealth>()102103 init(vq: KitAPI, fetcher: NextFetcher) { self.vq = vq; self.fetcher = fetcher }104105 func refreshOverview() async {106 overview.begin()107 do { overview.succeed(try await fetcher.load("overview", .get("/api/v2/market/overview", timeout: 60))) } catch { overview.fail(error) }108 }109 func refreshHealth() async {110 health.begin()111 do { health.succeed(try await fetcher.load("health", .get("/api/v2/data/health", timeout: 60))) } catch { health.fail(error) }112 }113 func statements(_ symbol: String, period: String, limit: Int = 8) async throws -> Loaded<VQStatements> {114 try await fetcher.load("statements:\(symbol):\(period):\(limit)",115 .get("/api/v2/data/statements/\(VQRequest.segment(symbol))", [VQQueryItem("period", period), VQQueryItem("limit", String(limit))], timeout: 60))116 }117 /// Bars with their provenance. `from`/`to` are ISO days.118 func bars(_ symbol: String, interval: String, from: String? = nil, to: String? = nil, limit: Int? = nil) async throws -> Loaded<VQBarSeries> {119 var q = [VQQueryItem("interval", interval)]120 q += VQQueryItem.optional("from", from); q += VQQueryItem.optional("to", to); q += VQQueryItem.optional("limit", limit.map(String.init))121 return try await fetcher.load("bars2:\(symbol):\(interval):\(from ?? "")", .get("/api/v2/data/bars/\(VQRequest.segment(symbol))", q, timeout: 60))122 }123 func search(_ text: String, types: [VQSearchResult.ResultType]? = nil, limit: Int = 24) async throws -> VQSearchResults {124 try await vq.data.search(text, types: types, limit: limit)125 }126 func quotes(_ symbols: [String]) async throws -> VQQuotes { try await vq.data.quotes(symbols) }127 func reset() { overview = NextState(); health = NextState() }128}129130// MARK: - Model registry131132@MainActor133@Observable134final class ModelStore {135 private let vq: KitAPI136 private let fetcher: NextFetcher137 var catalog = NextState<VQModelCatalog>()138 var usage = NextState<VQUsageReport>()139 init(vq: KitAPI, fetcher: NextFetcher) { self.vq = vq; self.fetcher = fetcher }140141 func refresh() async {142 catalog.begin()143 do { catalog.succeed(try await fetcher.load("models", .get("/api/v2/models"))) } catch { catalog.fail(error) }144 }145 func refreshUsage(days: Int = 30) async {146 usage.begin()147 do { usage.succeed(try await fetcher.load("usage:\(days)", .get("/api/v2/usage", [VQQueryItem("days", String(days))]))) } catch { usage.fail(error) }148 }149 func label(_ id: String?) -> String {150 guard let id, !id.isEmpty else { return "Modèle par défaut" }151 if id == "auto" { return catalog.value?.auto.label ?? "Auto" }152 return catalog.value?.model(id)?.label ?? id153 }154 func provider(of id: String?) -> String? { id.flatMap { catalog.value?.model($0)?.provider } }155 func reset() { catalog = NextState(); usage = NextState() }156}157158// MARK: - Quant Lab159160@MainActor161@Observable162final class LabStore {163 private let vq: KitAPI164 private let fetcher: NextFetcher165 var catalog = NextState<VQLabCatalog>()166 var jobs = NextState<VQQuantJobList>()167 /// Called when a job this device saw running is finished (local notification).168 var onJobFinished: (@MainActor (VQQuantJob) -> Void)?169 private var knownRunning: Set<String> = []170 private var pollTask: Task<Void, Never>?171172 init(vq: KitAPI, fetcher: NextFetcher) { self.vq = vq; self.fetcher = fetcher }173174 var running: [VQQuantJob] { (jobs.value?.jobs ?? []).filter(\.isRunning) }175 func tool(_ id: String) -> VQLabTool? { catalog.value?.tool(id) }176 func title(_ id: String) -> String { tool(id)?.title ?? Fmt.label(id) }177178 func refreshCatalog() async {179 catalog.begin()180 do { catalog.succeed(try await fetcher.load("lab:tools", .get("/api/quant/tools"))) } catch { catalog.fail(error) }181 }182183 func refreshJobs() async {184 jobs.begin()185 do {186 let l: Loaded<VQQuantJobList> = try await fetcher.load("lab:jobs", .get("/api/quant/jobs"))187 if !l.isFromCache {188 // Only the jobs started from this device are announced: the account is shared with the Mac and the web.189 let now = Set(l.value.jobs.filter(\.isRunning).map(\.id))190 for id in knownRunning.subtracting(now) { if let j = l.value.jobs.first(where: { $0.id == id }) { onJobFinished?(j) } }191 knownRunning.formIntersection(now)192 }193 jobs.succeed(l)194 } catch { jobs.fail(error) }195 }196197 func start(tool: String, params: VQJSONObject, projectId: String? = nil) async throws -> VQQuantJob {198 let job = try await vq.lab.start(tool: tool, params: params, projectId: projectId)199 knownRunning.insert(job.id)200 await refreshJobs(); startPolling()201 return job202 }203204 /// A job with its result; a finished job never changes, so its device copy is the job.205 func job(_ id: String) async throws -> Loaded<VQQuantJob> {206 if let hit: Loaded<JobEnvelope> = await fetcher.cached("lab:job:\(id)"), hit.value.job.isFinished, hit.value.job.result != nil || hit.value.job.error != nil {207 return Loaded(value: hit.value.job, origin: .network, fetchedAt: hit.fetchedAt)208 }209 let l: Loaded<JobEnvelope> = try await fetcher.load("lab:job:\(id)", .get("/api/quant/jobs/\(VQRequest.segment(id))", timeout: 60))210 return Loaded(value: l.value.job, origin: l.origin, fetchedAt: l.fetchedAt)211 }212 struct JobEnvelope: VQJSONDecodable { var job: VQQuantJob; init(json j: VQJSON) { job = VQQuantJob(json: j["job"] ?? j) } }213214 func cancel(_ id: String) async throws -> VQLabClient.CancelOutcome {215 let o = try await vq.lab.cancel(id)216 await refreshJobs()217 return o218 }219 func delete(_ id: String) async throws { try await vq.lab.delete(id); await refreshJobs() }220221 func startPolling() {222 guard pollTask == nil else { return }223 pollTask = Task { [weak self] in224 while !Task.isCancelled {225 await self?.refreshJobs()226 guard let self, !self.running.isEmpty else { break }227 try? await Task.sleep(for: .seconds(2))228 }229 self?.pollTask = nil230 }231 }232 func stopPolling() { pollTask?.cancel(); pollTask = nil }233 func reset() { stopPolling(); catalog = NextState(); jobs = NextState(); knownRunning = [] }234}235236// MARK: - Portfolios (synced objects; `main` is the one the agent reasons about)237238@MainActor239@Observable240final class PortfolioStore {241 private let sync: SyncCenter242 private let defaults: UserDefaults243 var selectedId: String { didSet { defaults.set(selectedId, forKey: "portfolio.selected") } }244245 init(sync: SyncCenter, defaults: UserDefaults) {246 self.sync = sync; self.defaults = defaults247 selectedId = defaults.string(forKey: "portfolio.selected") ?? sync.defaultPortfolioId248 }249250 /// `main` first, then by name.251 var all: [VQObject<VQPortfolio>] {252 sync.portfolios.items.sorted { a, b in253 if (a.id == VQObjectID.mainPortfolio) != (b.id == VQObjectID.mainPortfolio) { return a.id == VQObjectID.mainPortfolio }254 return a.data.name.localizedCaseInsensitiveCompare(b.data.name) == .orderedAscending255 }256 }257 var selected: VQObject<VQPortfolio>? { sync.portfolios[selectedId] ?? all.first }258 var isLoaded: Bool { sync.portfolios.isLoaded }259 func isPending(_ id: String) -> Bool { sync.portfolios.pendingIDs.contains(id) }260261 /// The selected portfolio's positions in the shape the descriptive maths of 1.0 use.262 var positions: [Position] { Self.positions(of: selected?.data) }263 static func positions(of p: VQPortfolio?) -> [Position] {264 (p?.positions ?? []).filter { !$0.symbol.isEmpty }.map { Position(symbol: $0.symbol, quantity: $0.quantity, costBasis: $0.costBasis, note: $0.note, updatedAt: $0.raw["updatedAt"]?.doubleValue ?? 0) }265 }266 /// Every symbol held in any portfolio (quotes to keep fresh).267 var allSymbols: [String] { Array(Set(sync.portfolios.items.flatMap { $0.data.positions.map(\.symbol) })).sorted() }268269 func create(name: String, baseCurrency: String = "USD") async -> String {270 let id = sync.newId()271 await sync.portfolios.save(VQPortfolio(name: name, baseCurrency: baseCurrency), id: id)272 selectedId = id273 return id274 }275 func rename(_ id: String, to name: String) async { await sync.portfolios.update(id) { $0.name = name } }276 func delete(_ id: String) async {277 await sync.portfolios.delete(id)278 if selectedId == id { selectedId = sync.defaultPortfolioId }279 }280281 /// Writes a position of a portfolio. When the portfolio does not exist yet (`main` of a person with no position),282 /// it is created; the engine merges with the server's copy if one appeared meanwhile.283 func savePosition(in id: String, symbol: String, quantity: Double, costBasis: Double?, note: String?) async -> String? {284 let fresh = VQPortfolio(name: id == VQObjectID.mainPortfolio ? "Portefeuille principal" : "Portefeuille", baseCurrency: "USD")285 let error = await sync.edit(VQPortfolio.self, id: id, create: fresh) { p in286 var pos = p.position(symbol) ?? VQPortfolio.Position(symbol: symbol, quantity: quantity)287 pos.quantity = quantity; pos.costBasis = costBasis; pos.note = note288 p.upsert(pos)289 }290 await sync.portfolios.refresh()291 return error?.userMessage292 }293 func removePosition(in id: String, symbol: String) async -> String? {294 let error = await sync.edit(VQPortfolio.self, id: id) { $0.removePosition(symbol) }295 await sync.portfolios.refresh()296 return error?.userMessage297 }298}299300// MARK: - Research Studio (projects, notes, reviews, exports)301302@MainActor303@Observable304final class StudioStore {305 private let vq: KitAPI306 private let fetcher: NextFetcher307 private let sync: SyncCenter308 init(vq: KitAPI, fetcher: NextFetcher, sync: SyncCenter) { self.vq = vq; self.fetcher = fetcher; self.sync = sync }309310 var projects: [VQObject<VQProject>] { sync.projects.items.sorted { $0.updatedAt > $1.updatedAt } }311 func notes(of projectId: String?) -> [VQObject<VQNote>] { sync.notes.items.filter { $0.data.projectId == projectId }.sorted { $0.updatedAt > $1.updatedAt } }312 func reviews(of projectId: String) -> [VQObject<VQReview>] { sync.reviews.items.filter { $0.data.projectId == projectId }.sorted { $0.updatedAt > $1.updatedAt } }313314 func createProject(title: String, question: String?) async -> String {315 let id = sync.newId()316 var p = VQProject(title: title, question: question?.isEmpty == false ? question : nil)317 p.status = .known(.active)318 await sync.projects.save(p, id: id)319 return id320 }321 func createNote(title: String, body: String, projectId: String?) async -> String {322 let id = sync.newId()323 await sync.notes.save(VQNote(title: title, body: body, projectId: projectId), id: id)324 if let projectId {325 await sync.projects.update(projectId) { p in326 var items = p.items; items.append(VQProject.Item(type: .note, ref: id, title: title, addedAt: Date())); p.items = items327 }328 }329 return id330 }331 func bundle(_ id: String) async throws -> Loaded<VQProjectBundle> {332 try await fetcher.load("bundle:\(id)", .get("/api/v2/projects/\(VQRequest.segment(id))/bundle", timeout: 60))333 }334 func export(_ id: String, format: VQExportFormat) async throws -> VQProjectExport { try await vq.research.export(project: id, format: format) }335 func review(_ target: VQReview.Target, projectId: String?) async throws -> String { try await vq.research.startReview(of: target, projectId: projectId) }336 func run(project id: String, prompt: String, mode: String, model: String?, budget: VQBudget?) async throws -> VQProjectRun {337 try await vq.research.run(project: id, prompt: prompt, mode: mode, model: model, budget: budget)338 }339 func reset() {}340}341