Repository Public
1// SP Notes Core2// File: Sources/SPNotesAPI/AIConversationModels.swift3// Description: Models of the AI bookkeeping routes that never call a provider: stored conversations and their4// messages, usage and budget, and the dry-run plan of a chat turn or an inline action.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910// MARK: - Conversations1112/// A stored assistant conversation (`GET /api/ai/conversations`). Conversations are created by `aiChat`.13///14/// Not observed on the scratch server (creating one needs a paid chat turn): fields follow the server's table and15/// all but `id` are optional.16public struct AIConversation: Codable, Sendable, Equatable, Identifiable {17 public var id: String18 public var title: String?19 /// The page the conversation was opened on.20 public var pageId: String?21 /// The model pinned by the user, if any.22 public var model: String?23 /// `auto`…24 public var routing: String?25 public var pinned: Bool?26 public var createdAt: Date?27 public var updatedAt: Date?28 public var deletedAt: Date?29}3031/// A passage the assistant used for an answer (citation chip).32public struct AIMessageSource: Codable, Sendable, Equatable {33 /// The citation number `[n]` used in the answer (present on the sources of a streamed answer; a stored message may34 /// lack it).35 public var n: Int?36 public var chunkId: String?37 public var pageId: String?38 public var blockId: String?39 public var title: String?40 public var excerpt: String?41 public var score: Double?42}4344/// A message of a conversation. Same caveat as `AIConversation`: not observed, everything but `id` optional.45public struct AIMessage: Codable, Sendable, Equatable, Identifiable {46 public var id: String47 public var conversationId: String?48 /// `user` or `assistant`.49 public var role: String?50 public var content: String?51 public var model: String?52 public var provider: String?53 public var sources: [AIMessageSource]?54 /// Token usage as the provider reported it (free-form JSON).55 public var usage: RawJSON?56 public var costUsd: Double?57 public var latencyMs: Double?58 public var ttftMs: Double?59 /// Free-form JSON (mode, routing reason…).60 public var meta: RawJSON?61 public var createdAt: Date?62}6364/// `GET /api/ai/conversations?id=` — a conversation with its messages, oldest first.65public struct AIConversationDetail: Decodable, Sendable, Equatable {66 public var conversation: AIConversation67 public var messages: [AIMessage]6869 enum CodingKeys: String, CodingKey { case messages }7071 public init(from decoder: Decoder) throws {72 conversation = try AIConversation(from: decoder)73 messages = (try decoder.container(keyedBy: CodingKeys.self).decodeIfPresent([AIMessage].self, forKey: .messages)) ?? []74 }75}7677/// Body of `PATCH /api/ai/conversations`. Only what is set is sent.78public struct AIConversationChanges: Sendable, Equatable {79 /// ≤ 200 characters.80 public var title: String?81 public var pinned: Bool?82 /// `.null` goes back to automatic routing.83 public var model: PatchValue<String>?8485 public init(title: String? = nil, pinned: Bool? = nil, model: PatchValue<String>? = nil) {86 self.title = title87 self.pinned = pinned88 self.model = model89 }90}9192// MARK: - Usage9394/// Usage of one model over the period. The counters arrive as text (`"calls": "4"`): read from either form.95public struct AIUsageByModel: Codable, Sendable, Equatable {96 public var model: String97 public var provider: String?98 public var calls: Int?99 public var errors: Int?100 public var inputTokens: Int?101 public var outputTokens: Int?102 public var costUsd: Double?103 /// Median latency, ms.104 public var latency: Double?105 /// Median time to first token, ms.106 public var ttft: Double?107108 enum CodingKeys: String, CodingKey { case model, provider, calls, errors, inputTokens, outputTokens, costUsd, latency, ttft }109110 public init(from decoder: Decoder) throws {111 let c = try decoder.container(keyedBy: CodingKeys.self)112 model = try c.decode(String.self, forKey: .model)113 provider = try? c.decodeIfPresent(String.self, forKey: .provider)114 calls = c.lenientInt(.calls)115 errors = c.lenientInt(.errors)116 inputTokens = c.lenientInt(.inputTokens)117 outputTokens = c.lenientInt(.outputTokens)118 costUsd = c.lenientDouble(.costUsd)119 latency = c.lenientDouble(.latency)120 ttft = c.lenientDouble(.ttft)121 }122}123124public struct AIUsageByDay: Codable, Sendable, Equatable {125 /// `YYYY-MM-DD`.126 public var day: String127 public var costUsd: Double?128 public var calls: Int?129130 enum CodingKeys: String, CodingKey { case day, costUsd, calls }131132 public init(from decoder: Decoder) throws {133 let c = try decoder.container(keyedBy: CodingKeys.self)134 day = try c.decode(String.self, forKey: .day)135 costUsd = c.lenientDouble(.costUsd)136 calls = c.lenientInt(.calls)137 }138}139140public struct AIUsageByTask: Codable, Sendable, Equatable {141 /// `chat`, `write`, `quick`, `embed`, `agent`…142 public var task: String143 public var calls: Int?144 public var costUsd: Double?145146 enum CodingKeys: String, CodingKey { case task, calls, costUsd }147148 public init(from decoder: Decoder) throws {149 let c = try decoder.container(keyedBy: CodingKeys.self)150 task = try c.decode(String.self, forKey: .task)151 calls = c.lenientInt(.calls)152 costUsd = c.lenientDouble(.costUsd)153 }154}155156/// One provider call of the usage log.157public struct AIUsageEntry: Codable, Sendable, Equatable, Identifiable {158 public var id: String159 public var provider: String?160 public var model: String?161 public var task: String?162 public var inputTokens: Int?163 public var outputTokens: Int?164 public var cachedTokens: Int?165 public var reasoningTokens: Int?166 public var costUsd: Double?167 public var latencyMs: Double?168 public var ttftMs: Double?169 public var ok: Bool?170 public var error: String?171 /// What the call was for (a page, an execution…).172 public var refId: String?173 public var createdAt: Date?174}175176/// `GET /api/ai/usage[?days=]`.177public struct AIUsageReport: Codable, Sendable, Equatable {178 public var days: Int179 /// Most expensive first.180 public var byModel: [AIUsageByModel]181 public var byDay: [AIUsageByDay]182 public var byTask: [AIUsageByTask]183 /// The 50 most recent calls (not limited to the period).184 public var recent: [AIUsageEntry]185186 /// Total cost of the period.187 public var totalCostUsd: Double { byModel.reduce(0) { $0 + ($1.costUsd ?? 0) } }188 public var totalCalls: Int { byModel.reduce(0) { $0 + ($1.calls ?? 0) } }189}190191/// The daily budget and what was spent today.192public struct AIBudget: Codable, Sendable, Equatable {193 public var budgetUsd: Double?194 public var spentUsd: Double?195 public var over: Bool?196}197198// MARK: - Plan (dry run)199200/// Which providers have a key on the server.201public struct AIProvidersConfigured: Codable, Sendable, Equatable {202 public var openai: Bool?203 public var anthropic: Bool?204 public var any: Bool?205}206207/// `GET /api/ai/chat/plan` — where a request would be sent and what it would cost, before anything is sent. Reads208/// the routing tables only: no provider is called and no note text is received.209public struct AIPlan: Codable, Sendable, Equatable {210 public var configured: AIProvidersConfigured?211 /// Chat plans only.212 public var mode: String?213 /// The routing class: `chat`, `write`, `quick`…214 public var task: String?215 public var provider: String?216 public var model: String?217 /// Why this model ("primary route for chat").218 public var reason: String?219 public var estTokens: Int?220 public var estCostUsd: Double?221 /// Chat plans only.222 public var budget: AIBudget?223 /// A sentence to show when the budget is close or exceeded.224 public var budgetNote: String?225 /// Chat plans only: what would leave the server (page characters, excerpts, embedding and ranking providers). Raw.226 public var sends: RawJSON?227 /// Not null when the request is an expensive class that needs `confirmExpensive`. Raw (only `null` was observed).228 public var expensive: RawJSON?229 /// Not null when no model can take the request. Raw (only `null` was observed).230 public var error: RawJSON?231232 /// The request would need `confirmExpensive: true`.233 public var needsConfirmation: Bool { expensive != nil }234235 enum CodingKeys: String, CodingKey { case configured, mode, task, provider, model, reason, estTokens, estCostUsd, budget, budgetNote, sends, expensive, error }236237 public init(from decoder: Decoder) throws {238 let c = try decoder.container(keyedBy: CodingKeys.self)239 configured = try? c.decodeIfPresent(AIProvidersConfigured.self, forKey: .configured)240 mode = try? c.decodeIfPresent(String.self, forKey: .mode)241 task = try? c.decodeIfPresent(String.self, forKey: .task)242 provider = try? c.decodeIfPresent(String.self, forKey: .provider)243 model = try? c.decodeIfPresent(String.self, forKey: .model)244 reason = try? c.decodeIfPresent(String.self, forKey: .reason)245 estTokens = c.lenientInt(.estTokens)246 estCostUsd = c.lenientDouble(.estCostUsd)247 budget = try? c.decodeIfPresent(AIBudget.self, forKey: .budget)248 budgetNote = try? c.decodeIfPresent(String.self, forKey: .budgetNote)249 sends = c.rawIfPresent(.sends)250 expensive = c.rawIfPresent(.expensive)251 error = c.rawIfPresent(.error)252 }253}254