Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Models/Research.swift3// Description: Conversations with the research agent, server-side analysis jobs ("generations") and the events they stream.4import Foundation56public enum ResearchMode: String, Sendable, CaseIterable, Codable, Identifiable {7 case fast, standard, deep, ultra, research8 public var id: String { rawValue }9 public var title: String { switch self { case .fast: "Fast"; case .standard: "Standard"; case .deep: "Deep research"; case .ultra: "Ultra deep"; case .research: "Research" } }10 public var detail: String {11 switch self {12 case .fast: "A short answer in under a minute: one round of data, little reasoning."13 case .standard: "A full research note with data, computations and figures."14 case .deep: "A plan, parallel sub-analysts and an independent audit. Several minutes."15 case .ultra: "Two delegation rounds, a contrarian analyst and primary-source checks. The longest and most expensive."16 case .research: "Autonomous research: the agent writes and runs code in its own workspace, keeps an experiment ledger and checks its numbers before answering."17 }18 }19}2021/// Model identifiers the server accepts (server/routes/validation.ts). An identifier the server no longer knows falls back to its default there.22public enum ResearchModel {23 public static let `default` = "claude-fable-5-2"24 public static let all: [(id: String, name: String)] = [25 ("claude-fable-5-2", "Claude Fable 5.2"), ("claude-opus-5-5", "Claude Opus 5.5"), ("claude-sonnet-5-5", "Claude Sonnet 5.5"), ("claude-haiku-5-5", "Claude Haiku 5.5"),26 ("claude-opus-4-8", "Claude Opus 4.8"), ("claude-sonnet-4-6", "Claude Sonnet 4.6"),27 ("gpt-5.6-sol", "GPT-5.6 Sol"), ("gpt-5.6-terra", "GPT-5.6 Terra"), ("gpt-5.6-luna", "GPT-5.6 Luna"), ("gpt-5.5", "GPT-5.5"), ("gpt-5.4", "GPT-5.4"), ("gpt-5.2", "GPT-5.2"),28 ("gpt-5.1", "GPT-5.1"), ("gpt-5", "GPT-5"), ("gpt-5-mini", "GPT-5 mini"), ("gpt-5-nano", "GPT-5 nano"), ("gpt-4.1", "GPT-4.1"), ("gpt-4.1-mini", "GPT-4.1 mini"),29 ("gemini-3.5-flash", "Gemini 3.5 Flash"), ("gemini-3.1-pro-preview", "Gemini 3.1 Pro"), ("gemini-3-flash-preview", "Gemini 3 Flash"), ("gemini-3.1-flash-lite", "Gemini 3.1 Flash Lite"),30 ]31 public static func name(_ id: String) -> String { all.first { $0.id == id }?.name ?? id }32}3334public struct SessionSummary: Sendable, Equatable, Identifiable, Codable {35 public var sessionId: String36 public var title: String37 public var pinned: Bool38 public var createdAt: String39 public var updatedAt: String40 public var id: String { sessionId }41 public var updated: Date? { ServerDate.parse(updatedAt) }42 public var created: Date? { ServerDate.parse(createdAt) }43}4445public enum ServerDate {46 /// ISO-8601 with or without fractional seconds, or SQLite's "yyyy-MM-dd HH:mm:ss" (UTC).47 public static func parse(_ s: String) -> Date? {48 if let d = try? Date(s, strategy: .iso8601.year().month().day().time(includingFractionalSeconds: true).timeZone(separator: .omitted)) { return d }49 if let d = try? Date(s, strategy: .iso8601) { return d }50 return BarParser.date(s)51 }52}5354public struct WebSource: Sendable, Equatable, Codable, Identifiable, Hashable {55 public var title: String56 public var url: String57 public var snippet: String?58 public var rank: Int?59 public var id: String { url }60 public init(title: String, url: String, snippet: String? = nil, rank: Int? = nil) { self.title = title; self.url = url; self.snippet = snippet; self.rank = rank }61 enum CodingKeys: String, CodingKey { case title, url, snippet, rank }62 public init(from decoder: Decoder) throws {63 let c = try decoder.container(keyedBy: CodingKeys.self)64 url = (try? c.decode(String.self, forKey: .url)) ?? ""65 title = (try? c.decodeIfPresent(String.self, forKey: .title)) ?? url66 snippet = try? c.decodeIfPresent(String.self, forKey: .snippet)67 rank = try? c.decodeIfPresent(Int.self, forKey: .rank)68 }69}7071/// A batch of figures produced by one notebook call. `figureUrls` are server paths (`/figures/…png`) fetched with the session.72public struct FigureBatch: Sendable, Equatable, Codable {73 public var id: String?74 public var figureUrls: [String]75 public var description: String?76 public var output: String?77 public init(id: String?, figureUrls: [String], description: String?, output: String?) { self.id = id; self.figureUrls = figureUrls; self.description = description; self.output = output }78 enum CodingKeys: String, CodingKey { case id, figureId, figureUrls, description, output }79 public init(from decoder: Decoder) throws {80 let c = try decoder.container(keyedBy: CodingKeys.self)81 id = (try? c.decodeIfPresent(String.self, forKey: .id)) ?? (try? c.decodeIfPresent(String.self, forKey: .figureId))82 figureUrls = (try? c.decodeIfPresent([String].self, forKey: .figureUrls)) ?? []83 description = try? c.decodeIfPresent(String.self, forKey: .description)84 output = try? c.decodeIfPresent(String.self, forKey: .output)85 // `figures` (base64 copies of the same images) is deliberately not decoded: the files are fetched by URL when shown.86 }87 public func encode(to encoder: Encoder) throws {88 var c = encoder.container(keyedBy: CodingKeys.self)89 try c.encodeIfPresent(id, forKey: .id); try c.encode(figureUrls, forKey: .figureUrls)90 try c.encodeIfPresent(description, forKey: .description); try c.encodeIfPresent(output, forKey: .output)91 }92}9394public struct ToolRecord: Sendable, Equatable, Codable {95 public var tool: String96 public var result: JSONValue?97}9899/// One saved exchange of a conversation, exactly as the server stored it.100public struct Turn: Sendable, Equatable, Codable {101 public var question: String102 public var answer: String103 public var toolResults: [ToolRecord]104 public var sources: [WebSource]105 public var pythonCode: String?106 public var customPythonFigures: [FigureBatch]107108 public init(question: String, answer: String, toolResults: [ToolRecord] = [], sources: [WebSource] = [], pythonCode: String? = nil, customPythonFigures: [FigureBatch] = []) {109 self.question = question; self.answer = answer; self.toolResults = toolResults; self.sources = sources; self.pythonCode = pythonCode; self.customPythonFigures = customPythonFigures110 }111 enum CodingKeys: String, CodingKey { case question, answer, toolResults, sources, pythonCode, customPythonFigures }112 public init(from decoder: Decoder) throws {113 let c = try decoder.container(keyedBy: CodingKeys.self)114 question = try c.decode(String.self, forKey: .question)115 answer = (try? c.decodeIfPresent(String.self, forKey: .answer)) ?? ""116 toolResults = (try? c.decodeIfPresent([ToolRecord].self, forKey: .toolResults)) ?? []117 sources = (try? c.decodeIfPresent([WebSource].self, forKey: .sources)) ?? []118 pythonCode = try? c.decodeIfPresent(String.self, forKey: .pythonCode)119 customPythonFigures = (try? c.decodeIfPresent([FigureBatch].self, forKey: .customPythonFigures)) ?? []120 }121}122123public struct Conversation: Sendable, Equatable, Codable {124 public var sessionId: String125 public var title: String126 public var turns: [Turn]127 public var createdAt: String128 public var updatedAt: String129130 public init(sessionId: String, title: String, turns: [Turn], createdAt: String, updatedAt: String) { self.sessionId = sessionId; self.title = title; self.turns = turns; self.createdAt = createdAt; self.updatedAt = updatedAt }131 enum CodingKeys: String, CodingKey { case sessionId, title, messages, turns, createdAt, updatedAt }132 public init(from decoder: Decoder) throws {133 let c = try decoder.container(keyedBy: CodingKeys.self)134 sessionId = try c.decode(String.self, forKey: .sessionId)135 title = (try? c.decode(String.self, forKey: .title)) ?? ""136 createdAt = (try? c.decode(String.self, forKey: .createdAt)) ?? ""137 updatedAt = (try? c.decode(String.self, forKey: .updatedAt)) ?? ""138 if let t = try? c.decode([Turn].self, forKey: .turns) { turns = t } // the app's own cache139 else if let s = try? c.decode(String.self, forKey: .messages) { // the server stores the turns as a JSON string140 turns = try JSONDecoder().decode([Turn].self, from: Data(s.utf8))141 } else { turns = try c.decode([Turn].self, forKey: .messages) }142 }143 public func encode(to encoder: Encoder) throws {144 var c = encoder.container(keyedBy: CodingKeys.self)145 try c.encode(sessionId, forKey: .sessionId); try c.encode(title, forKey: .title); try c.encode(turns, forKey: .turns)146 try c.encode(createdAt, forKey: .createdAt); try c.encode(updatedAt, forKey: .updatedAt)147 }148}149150// MARK: - Generations (analysis jobs)151152public struct GenerationSummary: Sendable, Equatable, Identifiable, Codable {153 public enum Status: String, Sendable, Codable { case running, done, error, cancelled }154 public var id: String155 public var sessionId: String156 public var query: String157 public var mode: String158 public var status: Status159 public var step: String160 public var chars: Int161 public var tools: Int162 public var startedAt: Double163 public var finishedAt: Double?164 public var viewers: Int165 public var replayable: Bool166 public var error: String?167 public var started: Date { Date(timeIntervalSince1970: startedAt / 1000) }168 public var finished: Date? { finishedAt.map { Date(timeIntervalSince1970: $0 / 1000) } }169}170171public struct GenerationList: Sendable, Equatable, Codable {172 public var generations: [GenerationSummary]173 public var running: Int174}175176public struct PlanStep: Sendable, Equatable, Codable, Hashable {177 public var title: String178 public var status: String179}180181/// An event of an analysis stream, decoded from the server's JSON. Unknown types are kept, never dropped silently.182public enum GenerationEvent: Sendable, Equatable {183 case job(id: String, sessionId: String, query: String)184 case status(String)185 case text(String)186 case thinking(String)187 case toolStart(tool: String, toolId: String, input: JSONValue?)188 case toolComplete(tool: String, toolId: String, durationMs: Double, empty: Bool)189 case toolError(tool: String, toolId: String, error: String)190 case toolResult(tool: String)191 /// the batch of tool calls the model just decided on (each one is then reported by its own tool_start)192 case toolBatch(count: Int)193 case pythonCode(String)194 case figures(FigureBatch)195 case plan([PlanStep])196 case agentStart(agentId: String, name: String, kind: String)197 case agentTool(agentId: String, tool: String, status: String)198 case agentDone(agentId: String, ok: Bool, tools: Int, durationMs: Double, preview: String)199 case workspace(area: String)200 case sources([WebSource])201 case followups([String])202 case error(message: String, detail: String?)203 case done(sessionId: String?)204 /// An event backend 6 added (routing, usage, provenance, the research workspace of CONTRACT §9.6). Its payload is205 /// consumed from the raw frame (`GenerationRunner.onFrame`) by the app, through the shared kit's reducers.206 case next(type: String)207 case other(type: String)208209 /// Event types of backend 6 this client understands through the kit.210 public static let nextTypes: Set<String> = ["model_routed", "budget", "budget_applied", "quant_job", "provenance", "research_workspace", "dataset", "research_file", "code_execution", "code_execution_start",211 "package_install", "research_run", "experiment", "research_note", "figure_lint", "approval_request", "approval_resolved", "quality_gate"]212213 public init(_ j: JSONValue) {214 let type = j["type"]?.stringValue ?? ""215 func s(_ k: String) -> String { j[k]?.stringValue ?? "" }216 switch type {217 case "job": self = .job(id: s("id"), sessionId: s("sessionId"), query: s("query"))218 case "status": self = .status(s("message"))219 case "text": self = .text(s("content"))220 case "thinking": self = .thinking(s("content"))221 case "tool_start": self = .toolStart(tool: s("tool"), toolId: s("toolId"), input: j["input"])222 case "tool_complete": self = .toolComplete(tool: s("tool"), toolId: s("toolId"), durationMs: j["duration"]?.doubleValue ?? 0, empty: j["empty"]?.boolValue ?? false)223 case "tool_error": self = .toolError(tool: s("tool"), toolId: s("toolId"), error: s("error"))224 case "tool_result": self = .toolResult(tool: s("tool"))225 case "tools": self = .toolBatch(count: j["tools"]?.arrayValue?.count ?? 0)226 case "python_code": self = .pythonCode(s("code"))227 case "custom_python_figures":228 self = .figures(FigureBatch(id: j["figureId"]?.stringValue, figureUrls: (j["figureUrls"]?.arrayValue ?? []).compactMap(\.stringValue), description: j["description"]?.stringValue, output: j["output"]?.stringValue))229 case "plan": self = .plan((j["steps"]?.arrayValue ?? []).map { PlanStep(title: $0["title"]?.stringValue ?? "", status: $0["status"]?.stringValue ?? "pending") })230 case "agent_start": self = .agentStart(agentId: s("agentId"), name: s("name"), kind: s("kind"))231 case "agent_tool": self = .agentTool(agentId: s("agentId"), tool: s("tool"), status: s("status"))232 case "agent_done": self = .agentDone(agentId: s("agentId"), ok: j["ok"]?.boolValue ?? false, tools: j["tools"]?.intValue ?? 0, durationMs: j["durationMs"]?.doubleValue ?? 0, preview: s("preview"))233 case "workspace": self = .workspace(area: s("area"))234 case "sources": self = .sources((j["sources"]?.arrayValue ?? []).compactMap { v in v["url"]?.stringValue.map { WebSource(title: v["title"]?.stringValue ?? $0, url: $0, snippet: v["snippet"]?.stringValue, rank: v["rank"]?.intValue) } })235 case "followups": self = .followups((j["questions"]?.arrayValue ?? []).compactMap(\.stringValue))236 case "error": self = .error(message: s("error"), detail: j["detail"]?.stringValue)237 case "done": self = .done(sessionId: j["sessionId"]?.stringValue)238 default: self = Self.nextTypes.contains(type) ? .next(type: type) : .other(type: type)239 }240 }241}242243// MARK: - Run state (what a viewer has seen of a job)244245public struct ToolActivity: Sendable, Equatable, Identifiable {246 public enum State: Sendable, Equatable { case running, done, empty, failed(String) }247 public var id: String248 public var tool: String249 public var input: JSONValue?250 public var state: State251 public var durationMs: Double?252}253254public struct SubAgent: Sendable, Equatable, Identifiable {255 public var id: String256 public var name: String257 public var kind: String258 public var tools: [String]259 public var finished: Bool260 public var ok: Bool261 public var preview: String262 public var durationMs: Double?263}264265/// Everything a stream has told about a job so far. Applying the same events in the same order always gives the same266/// state, so a viewer that reconnects from event n ends up exactly where an uninterrupted one would be.267public struct RunState: Sendable, Equatable {268 public var jobId: String?269 public var sessionId: String?270 public var query = ""271 public var status = ""272 public var answer = ""273 public var thinking = ""274 public var tools: [ToolActivity] = []275 public var agents: [SubAgent] = []276 public var plan: [PlanStep] = []277 public var figures: [FigureBatch] = []278 public var pythonCode: [String] = []279 public var sources: [WebSource] = []280 public var followups: [String] = []281 public var error: String?282 public var errorDetail: String?283 public var finished = false284 public var workspaceTouched: Set<String> = []285 public var unknownEvents: [String: Int] = [:]286 /// Index of the next event to ask the server for when reconnecting (`?from=`).287 public var nextEventIndex = 0288289 public init() {}290291 public mutating func apply(_ frame: SSEFrame) {292 if let id = frame.id {293 if id < nextEventIndex { return } // already applied (replayed after a reconnection)294 nextEventIndex = id + 1295 }296 apply(GenerationEvent(frame.json))297 }298299 public mutating func apply(_ e: GenerationEvent) {300 switch e {301 case .job(let id, let sid, let q): jobId = id; sessionId = sid; if query.isEmpty { query = q }302 case .status(let m): status = m303 case .text(let t): answer += t304 case .thinking(let t): thinking += t305 case .toolStart(let tool, let id, let input):306 if !tools.contains(where: { $0.id == id }) { tools.append(ToolActivity(id: id, tool: tool, input: input, state: .running)) }307 case .toolComplete(_, let id, let ms, let empty):308 if let i = tools.firstIndex(where: { $0.id == id }) { tools[i].state = empty ? .empty : .done; tools[i].durationMs = ms }309 case .toolError(_, let id, let err):310 if let i = tools.firstIndex(where: { $0.id == id }) { tools[i].state = .failed(err) }311 case .toolResult, .toolBatch, .next: break312 case .pythonCode(let c): if !c.isEmpty { pythonCode.append(c) }313 case .figures(let b): figures.append(b)314 case .plan(let steps): plan = steps315 case .agentStart(let id, let name, let kind):316 if !agents.contains(where: { $0.id == id }) { agents.append(SubAgent(id: id, name: name, kind: kind, tools: [], finished: false, ok: false, preview: "")) }317 case .agentTool(let id, let tool, let st):318 if st == "running", let i = agents.firstIndex(where: { $0.id == id }) { agents[i].tools.append(tool) }319 case .agentDone(let id, let ok, _, let ms, let preview):320 if let i = agents.firstIndex(where: { $0.id == id }) { agents[i].finished = true; agents[i].ok = ok; agents[i].preview = preview; agents[i].durationMs = ms }321 case .workspace(let area): workspaceTouched.insert(area)322 case .sources(let s): sources = s323 case .followups(let f): followups = f324 case .error(let m, let d): error = m; errorDetail = d325 case .done(let sid): finished = true; if let sid, !sid.isEmpty { sessionId = sid }326 case .other(let t): unknownEvents[t, default: 0] += 1327 }328 }329}330