Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Core/Networking/Endpoints.swift3// Description: Typed calls for every backend route used by the native app (conversations, models, library, account, exports).4import Foundation56public enum ConversationFilter: String, Sendable, CaseIterable, Hashable {7 case all, favorites, pinned, archived8 public var label: String { switch self { case .all: "Toutes"; case .favorites: "Favoris"; case .pinned: "Épinglées"; case .archived: "Archives" } }9}1011public struct ConversationPatch: Sendable {12 public var title: String?13 public var projectId: String??14 public var modelId: String?15 public var pinned: Bool?16 public var favorite: Bool?17 public var archived: Bool?18 /// Name of the branch (`.some(nil)` clears it).19 public var branchLabel: String??20 public init(title: String? = nil, projectId: String?? = nil, modelId: String? = nil, pinned: Bool? = nil, favorite: Bool? = nil, archived: Bool? = nil, branchLabel: String?? = nil) {21 self.title = title; self.projectId = projectId; self.modelId = modelId; self.pinned = pinned; self.favorite = favorite; self.archived = archived; self.branchLabel = branchLabel22 }23 var json: JSONValue {24 var o: [String: JSONValue] = [:]25 if let title { o["title"] = .string(title) }26 if let projectId { o["projectId"] = projectId.map(JSONValue.string) ?? .null }27 if let modelId { o["modelId"] = .string(modelId) }28 if let pinned { o["pinned"] = .bool(pinned) }29 if let favorite { o["favorite"] = .bool(favorite) }30 if let archived { o["archived"] = .bool(archived) }31 if let branchLabel { o["branchLabel"] = branchLabel.map(JSONValue.string) ?? .null }32 return .object(o)33 }34}3536/// Options of one assistant turn (`turnOptions` in src/lib/chat/launch.ts). Unset values are left to the server / preset.37public struct TurnOptions: Sendable, Equatable {38 public var modelId: String?39 public var routingMode: RoutingMode?40 public var presetId: String?41 public var effort: Effort?42 public var maxOutputTokens: Int?43 public var temperature: Double?44 public var reasoningSummary: Bool?45 public var toolsEnabled: Bool?46 public var toolNames: [String]?47 /// « Recherche web » toggle: the model must search (Tavily) before answering.48 public var webSearch: Bool?49 public init(modelId: String? = nil, routingMode: RoutingMode? = nil, presetId: String? = nil, effort: Effort? = nil, maxOutputTokens: Int? = nil, temperature: Double? = nil,50 reasoningSummary: Bool? = nil, toolsEnabled: Bool? = nil, toolNames: [String]? = nil, webSearch: Bool? = nil) {51 self.modelId = modelId; self.routingMode = routingMode; self.presetId = presetId; self.effort = effort; self.maxOutputTokens = maxOutputTokens; self.temperature = temperature52 self.reasoningSummary = reasoningSummary; self.toolsEnabled = toolsEnabled; self.toolNames = toolNames; self.webSearch = webSearch53 }54 public var payload: [String: JSONValue] {55 var o: [String: JSONValue] = [:]56 if let routingMode { o["routingMode"] = .string(routingMode.rawValue) }57 // a model id is only meaningful in manual routing; the router picks otherwise58 if let modelId, routingMode == nil || routingMode == .manual { o["modelId"] = .string(modelId) }59 if let presetId { o["presetId"] = .string(presetId) }60 var s: [String: JSONValue] = [:]61 if let effort { s["effort"] = .string(effort.rawValue) }62 if let maxOutputTokens { s["maxOutputTokens"] = .number(Double(min(max(maxOutputTokens, 256), 128_000))) }63 if let temperature { s["temperature"] = .number(min(max(temperature, 0), 2)) }64 if let reasoningSummary { s["reasoningSummary"] = .bool(reasoningSummary) }65 if webSearch == true { s["webSearch"] = .bool(true) }66 if !s.isEmpty { o["settings"] = .object(s) }67 if let toolsEnabled { o["toolsEnabled"] = .bool(toolsEnabled) }68 if let toolNames { o["toolNames"] = .array(toolNames.map(JSONValue.string)) }69 return o70 }71}7273public struct UploadFile: Sendable {74 public var filename: String75 public var mime: String76 public var data: Data77 public init(filename: String, mime: String, data: Data) { self.filename = filename; self.mime = mime; self.data = data }78}7980public extension APIClient {81 // MARK: Conversations8283 func conversations(filter: ConversationFilter = .all, query: String? = nil, projectId: String?? = nil, limit: Int = 300) async throws -> [Conversation] {84 var q: [String: String?] = ["limit": String(limit)]85 if let query, !query.isEmpty { q["q"] = query }86 switch filter { case .all: break; case .favorites: q["favorite"] = "1"; case .pinned: q["pinned"] = "1"; case .archived: q["archived"] = "1" }87 if let projectId { q["project"] = projectId ?? "" }88 return try await decode([Conversation].self, .get, "/api/conversations", query: q, key: "conversations")89 }90 func conversation(_ id: String) async throws -> ConversationDetail { try await decode(ConversationDetail.self, .get, "/api/conversations/\(id)", query: ["all": "1"]) }91 func createConversation(title: String? = nil, modelId: String? = nil, projectId: String? = nil) async throws -> Conversation {92 var o: [String: JSONValue] = [:]93 if let title { o["title"] = .string(title) }; if let modelId { o["modelId"] = .string(modelId) }; if let projectId { o["projectId"] = .string(projectId) }94 return try await decode(Conversation.self, .post, "/api/conversations", body: .object(o), key: "conversation")95 }96 @discardableResult func updateConversation(_ id: String, _ patch: ConversationPatch) async throws -> Conversation {97 try await decode(Conversation.self, .patch, "/api/conversations/\(id)", body: patch.json, key: "conversation")98 }99 func deleteConversation(_ id: String) async throws { _ = try await raw(.delete, "/api/conversations/\(id)") }100 /// Switches the displayed version of a turn (◀ ▶).101 func activateBranch(conversationId: String, messageId: String) async throws { _ = try await raw(.post, "/api/conversations/\(conversationId)/branch", json: ["activate": .string(messageId)]) }102 /// Forks the thread up to `messageId` into a new conversation.103 func forkConversation(_ id: String, at messageId: String, label: String? = nil) async throws -> Conversation {104 var o: [String: JSONValue] = ["messageId": .string(messageId)]105 if let label = label?.trimmingCharacters(in: .whitespacesAndNewlines), !label.isEmpty { o["label"] = .string(label) }106 return try await decode(Conversation.self, .post, "/api/conversations/\(id)/branch", body: .object(o), key: "conversation")107 }108 func exportConversation(_ id: String, format: String, tree: Bool = false) async throws -> DownloadedFile {109 try await download("/api/conversations/\(id)/export", query: ["format": format, "tree": tree ? "1" : nil])110 }111 func cancelGeneration(runId: String?, messageId: String?) async throws {112 var o: [String: JSONValue] = [:]113 if let runId { o["runId"] = .string(runId) }; if let messageId { o["messageId"] = .string(messageId) }114 _ = try await raw(.post, "/api/chat/cancel", json: .object(o))115 }116 func search(_ q: String, semantic: Bool = true, modelId: String? = nil, projectId: String? = nil) async throws -> [SearchHit] {117 try await search(q, filters: SearchFilters(semantic: semantic, modelId: modelId, projectId: projectId))118 }119 /// Advanced search (`provider`, `favorite`, `role`, `fileType`, dates…): every filter is applied by the server.120 func search(_ q: String, filters: SearchFilters) async throws -> [SearchHit] {121 try await decode([SearchHit].self, .get, "/api/search", query: filters.query(q), key: "results")122 }123124 // MARK: Drafts125126 func draft(scope: String) async throws -> (text: String, attachments: [Attachment])? {127 let j = try await json(.get, "/api/drafts", query: ["scope": scope])128 guard let d = j["draft"], !d.isNull else { return nil }129 let atts = (try? JSONDecoder.api().decode([Attachment].self, from: Data((d["attachments"] ?? .array([])).jsonString().utf8))) ?? []130 return (d["text"]?.stringValue ?? "", atts)131 }132 func saveDraft(scope: String, text: String, attachmentIds: [String] = []) async throws {133 _ = try await raw(.put, "/api/drafts", json: ["scope": .string(scope), "text": .string(text), "attachmentIds": .array(attachmentIds.map(JSONValue.string))])134 }135136 // MARK: Models, presets, prompts, settings137138 /// `routes`: nil → direct, benchmarked models only (0.3 contract) · `all` → + the whole OpenRouter catalogue · `openrouter` → the catalogue alone.139 func models(includeHidden: Bool = false, routes: String? = nil) async throws -> ModelCatalog {140 try await decode(ModelCatalog.self, .get, "/api/models", query: ["all": includeHidden ? "1" : nil, "routes": routes], timeout: 60)141 }142 /// Model Favorites Dock (max 8 ids), synced between the three apps.143 func setDock(_ ids: [String]) async throws { _ = try await raw(.patch, "/api/models", json: ["dock": .array(ids.prefix(8).map(JSONValue.string))]) }144 func updateModel(_ id: String, hidden: Bool? = nil, favorite: Bool? = nil, makeDefault: Bool? = nil) async throws {145 var o: [String: JSONValue] = ["id": .string(id)]146 if let hidden { o["hidden"] = .bool(hidden) }; if let favorite { o["favorite"] = .bool(favorite) }; if let makeDefault { o["default"] = .bool(makeDefault) }147 _ = try await raw(.patch, "/api/models", json: .object(o))148 }149 func refreshModels() async throws { _ = try await raw(.post, "/api/models/refresh", timeout: 125) }150 func presets() async throws -> [Preset] { try await decode([Preset].self, .get, "/api/presets", key: "presets") }151 func createPreset(_ p: Preset) async throws -> Preset { try await decode(Preset.self, .post, "/api/presets", body: p.requestBody, key: "preset") }152 func updatePreset(_ p: Preset) async throws -> Preset { try await decode(Preset.self, .patch, "/api/presets/\(p.id)", body: p.requestBody, key: "preset") }153 func deletePreset(_ id: String) async throws { _ = try await raw(.delete, "/api/presets/\(id)") }154 func prompts(query: String? = nil, tag: String? = nil) async throws -> [Prompt] { try await decode([Prompt].self, .get, "/api/prompts", query: ["q": query, "tag": tag], key: "prompts") }155 func createPrompt(title: String, body: String, tags: [String], favorite: Bool = false) async throws -> Prompt {156 try await decode(Prompt.self, .post, "/api/prompts", body: ["title": .string(title), "body": .string(body), "tags": .array(tags.map(JSONValue.string)), "favorite": .bool(favorite)], key: "prompt")157 }158 func updatePrompt(_ id: String, title: String? = nil, body: String? = nil, tags: [String]? = nil, favorite: Bool? = nil, used: Bool? = nil) async throws {159 var o: [String: JSONValue] = [:]160 if let title { o["title"] = .string(title) }; if let body { o["body"] = .string(body) }; if let tags { o["tags"] = .array(tags.map(JSONValue.string)) }161 if let favorite { o["favorite"] = .bool(favorite) }; if let used { o["used"] = .bool(used) }162 _ = try await raw(.patch, "/api/prompts/\(id)", json: .object(o))163 }164 func deletePrompt(_ id: String) async throws { _ = try await raw(.delete, "/api/prompts/\(id)") }165 func serverSettings() async throws -> ServerSettings { try await decode(ServerSettings.self, .get, "/api/settings") }166 /// `key` is one of memory · spending · routing · appearance · audio · language · assistant · instructions · client.167 func updateSetting(key: String, value: [String: JSONValue]) async throws { _ = try await raw(.patch, "/api/settings", json: ["key": .string(key), "value": .object(value)]) }168 func usage(from: Date? = nil, to: Date? = nil, provider: String? = nil, modelId: String? = nil) async throws -> UsageReport {169 try await decode(UsageReport.self, .get, "/api/usage", query: ["from": from.map(ServerDate.string), "to": to.map(ServerDate.string), "provider": provider, "model": modelId])170 }171 func health() async throws -> HealthReport { try await decode(HealthReport.self, .get, "/api/health") }172173 // MARK: Projects & memories174175 func projects() async throws -> [Project] { try await decode([Project].self, .get, "/api/projects", key: "projects") }176 func createProject(name: String, description: String? = nil, instructions: String? = nil, defaultModel: String? = nil, color: String? = nil) async throws -> Project {177 var o: [String: JSONValue] = ["name": .string(name)]178 if let description, !description.isEmpty { o["description"] = .string(description) }; if let instructions, !instructions.isEmpty { o["instructions"] = .string(instructions) }179 if let defaultModel { o["defaultModel"] = .string(defaultModel) }; if let color { o["color"] = .string(color) }180 return try await decode(Project.self, .post, "/api/projects", body: .object(o), key: "project")181 }182 func updateProject(_ id: String, fields: [String: JSONValue]) async throws -> Project { try await decode(Project.self, .patch, "/api/projects/\(id)", body: .object(fields), key: "project") }183 func deleteProject(_ id: String) async throws { _ = try await raw(.delete, "/api/projects/\(id)") }184 func exportProject(_ id: String, format: String) async throws -> DownloadedFile { try await download("/api/projects/\(id)/export", query: ["format": format]) }185 func memories(status: String? = nil, query: String? = nil) async throws -> [Memory] { try await decode([Memory].self, .get, "/api/memories", query: ["status": status, "q": query], key: "memories") }186 func createMemory(content: String, category: String, projectId: String? = nil) async throws {187 var o: [String: JSONValue] = ["content": .string(content), "category": .string(category)]188 if let projectId { o["projectId"] = .string(projectId) }189 _ = try await raw(.post, "/api/memories", json: .object(o))190 }191 func updateMemory(_ id: String, content: String? = nil, category: String? = nil, status: String? = nil) async throws {192 var o: [String: JSONValue] = [:]193 if let content { o["content"] = .string(content) }; if let category { o["category"] = .string(category) }; if let status { o["status"] = .string(status) }194 _ = try await raw(.patch, "/api/memories/\(id)", json: .object(o))195 }196 func deleteMemory(_ id: String) async throws { _ = try await raw(.delete, "/api/memories/\(id)") }197 func exportMemories(format: String) async throws -> DownloadedFile { try await download("/api/memories/export", query: ["format": format]) }198199 // MARK: Attachments & artefacts200201 func uploadAttachments(_ files: [UploadFile], conversationId: String? = nil, projectId: String? = nil, progress: @escaping @Sendable (Double) -> Void = { _ in }) async throws -> [Attachment] {202 var form = MultipartForm()203 for f in files { form.add(file: "file", filename: FileValidator.sanitizedName(f.filename), mime: f.mime, data: f.data) }204 if let conversationId { form.add(field: "conversationId", value: conversationId) }205 if let projectId { form.add(field: "projectId", value: projectId) }206 let j = try await upload("/api/attachments", form: form, progress: progress)207 guard let list = j["attachments"], let atts = try? JSONDecoder.api().decode([Attachment].self, from: Data(list.jsonString().utf8)) else { throw APIError(.decoding, message: "Réponse inattendue du serveur (pièces jointes).") }208 return atts209 }210 func attachments(projectId: String? = nil, conversationId: String? = nil, query: String? = nil) async throws -> (files: [Attachment], usedBytes: Int, quotaMb: Int) {211 let (data, _) = try await raw(.get, "/api/attachments", query: ["project": projectId, "conversation": conversationId, "q": query])212 let j = JSONValue.parse(data) ?? .null213 let files = (try? JSONDecoder.api().decode([Attachment].self, from: Data((j["attachments"] ?? .array([])).jsonString().utf8))) ?? []214 return (files, j["storage"]?["usedBytes"]?.intValue ?? 0, j["storage"]?["quotaMb"]?.intValue ?? 0)215 }216 func attachmentData(_ id: String) async throws -> DownloadedFile { try await download("/api/attachments/\(id)") }217 func deleteAttachment(_ id: String) async throws { _ = try await raw(.delete, "/api/attachments/\(id)") }218 func reindexAttachment(_ id: String) async throws { _ = try await raw(.post, "/api/attachments/\(id)/reindex", timeout: 125) }219 func artifact(_ id: String) async throws -> Artifact { try await decode(Artifact.self, .get, "/api/artifacts/\(id)", key: "artifact") }220 func updateArtifact(_ id: String, saved: Bool? = nil, title: String? = nil) async throws {221 var o: [String: JSONValue] = [:]222 if let saved { o["saved"] = .bool(saved) }; if let title { o["title"] = .string(title) }223 _ = try await raw(.patch, "/api/artifacts/\(id)", json: .object(o))224 }225226 // MARK: Audio & images227228 func speech(text: String, voice: String = "alloy") async throws -> Data {229 try await download("/api/tts", method: .post, body: ["text": .string(String(text.prefix(4000))), "voice": .string(voice)]).data230 }231 func transcribe(audio: Data, filename: String, mime: String, language: String? = nil, durationSec: Double? = nil) async throws -> String {232 var form = MultipartForm(); form.add(file: "audio", filename: filename, mime: mime, data: audio)233 if let language, !language.isEmpty { form.add(field: "language", value: language) }234 if let durationSec { form.add(field: "durationSec", value: String(durationSec)) }235 return try await upload("/api/stt", form: form)["text"]?.stringValue ?? ""236 }237 func generateImage(prompt: String, size: String? = nil, quality: String? = nil, conversationId: String? = nil) async throws -> String {238 var o: [String: JSONValue] = ["prompt": .string(prompt)]239 if let size { o["size"] = .string(size) }; if let quality { o["quality"] = .string(quality) }; if let conversationId { o["conversationId"] = .string(conversationId) }240 let j = try await json(.post, "/api/images", body: .object(o), timeout: 300)241 guard let id = j["attachmentId"]?.stringValue else { throw APIError(.decoding, message: j["error"]?.stringValue ?? "Image non générée.") }242 return id243 }244 func generatedImages() async throws -> [JSONValue] { try await json(.get, "/api/images")["images"]?.arrayValue ?? [] }245246 // MARK: Owner data247248 func ownerSummary() async throws -> OwnerSummary { try await decode(OwnerSummary.self, .get, "/api/owner", query: ["summary": "1"], key: "summary") }249 func fullExport() async throws -> DownloadedFile { try await download("/api/owner") }250 /// Complete deletion of the owner's content. The server demands a passkey verification younger than 10 minutes.251 func wipeAllData(includeUsage: Bool) async throws { _ = try await raw(.delete, "/api/owner", json: ["confirm": "SUPPRIMER TOUT", "usage": .bool(includeUsage)]) }252}253