Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Core/API/ChatAPI.swift4// Description: Typed endpoints of the SP Chat backend (the same REST + SSE API used by the web app).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import Foundation1112/// Options of one assistant turn (`turnOptions` on the server). Unset fields are omitted from the request.13struct SendOptions: Codable, Hashable, Sendable {14 var modelId: String?15 var routingMode: RoutingMode?16 var presetId: String?17 var effort: Effort?18 var toolsEnabled: Bool?19 /// Restricts the turn to a subset of the server tools (composer tool picker). Nil = every tool.20 var toolNames: [String]?21 /// « Recherche web » toggle: the model must search (Tavily) before answering.22 var webSearch: Bool?23 var temperature: Double?24 var maxOutputTokens: Int?25 var reasoningSummary: Bool?2627 func payload() -> [String: JSONValue] {28 var o: [String: JSONValue] = [:]29 if let routingMode { o["routingMode"] = .string(routingMode.rawValue) }30 // a model is only meaningful in manual routing; the routers pick among verified models themselves31 if let modelId, routingMode == nil || routingMode == .manual { o["modelId"] = .string(modelId) }32 if let presetId { o["presetId"] = .string(presetId) }33 var settings: [String: JSONValue] = [:]34 if let effort { settings["effort"] = .string(effort.rawValue) }35 if webSearch == true { settings["webSearch"] = .bool(true) }36 if let temperature { settings["temperature"] = .number(temperature) }37 if let maxOutputTokens { settings["maxOutputTokens"] = .number(Double(maxOutputTokens)) }38 if let reasoningSummary { settings["reasoningSummary"] = .bool(reasoningSummary) }39 if !settings.isEmpty { o["settings"] = .object(settings) }40 // a web search needs the tools: asking for it turns them on for this turn41 if let toolsEnabled { o["toolsEnabled"] = .bool(toolsEnabled || webSearch == true) }42 if let toolNames, !toolNames.isEmpty, toolsEnabled != false || webSearch == true {43 o["toolNames"] = .array((webSearch == true && !toolNames.contains("web_search") ? toolNames + ["web_search"] : toolNames).map(JSONValue.string))44 }45 return o46 }47}4849struct ConversationFilter: Hashable, Sendable {50 var archived = false51 var favorite = false52 var pinned = false53 var projectId: String?54 var query: String?55}5657struct ConversationPatch: Sendable {58 var title: String?59 var pinned: Bool?60 var favorite: Bool?61 var archived: Bool?62 var modelId: String?63 /// Names the branch (a conversation forked from another one).64 var branchLabel: String?65 /// `.some(nil)` detaches the conversation from its project.66 var projectId: String??67}6869struct AuthState: Decodable, Sendable { var rpId: String; var configOk: Bool; var signedIn: Bool; var enrolment: String? }70struct StorageInfo: Decodable, Sendable { var usedBytes: Double; var files: Int; var quotaMb: Double; var maxUploadMb: Double }7172struct ChatAPI: Sendable {73 let http: HTTPClient7475 static func requestId() -> String {76 var bytes = [UInt8](repeating: 0, count: 18)77 _ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)78 return Data(bytes).base64URLEncodedString()79 }8081 // MARK: conversations8283 func conversations(_ f: ConversationFilter = ConversationFilter(), limit: Int = 300) async throws -> [Conversation] {84 struct R: Decodable { var conversations: [Conversation] }85 var q = [URLQueryItem(name: "limit", value: String(limit))]86 if f.archived { q.append(.init(name: "archived", value: "1")) }87 if f.favorite { q.append(.init(name: "favorite", value: "1")) }88 if f.pinned { q.append(.init(name: "pinned", value: "1")) }89 if let p = f.projectId { q.append(.init(name: "project", value: p)) }90 if let s = f.query, !s.isEmpty { q.append(.init(name: "q", value: s)) }91 return try await http.decode(R.self, .get("/api/conversations", query: q)).conversations92 }9394 func conversation(_ id: String) async throws -> ConversationDetail {95 try await http.decode(ConversationDetail.self, .get("/api/conversations/\(id)", query: [.init(name: "all", value: "1")]))96 }9798 func updateConversation(_ id: String, _ patch: ConversationPatch) async throws -> Conversation {99 struct R: Decodable { var conversation: Conversation }100 var o: [String: JSONValue] = [:]101 if let v = patch.title { o["title"] = .string(v) }102 if let v = patch.pinned { o["pinned"] = .bool(v) }103 if let v = patch.favorite { o["favorite"] = .bool(v) }104 if let v = patch.archived { o["archived"] = .bool(v) }105 if let v = patch.modelId { o["modelId"] = .string(v) }106 if let v = patch.branchLabel { o["branchLabel"] = .string(v) }107 if let v = patch.projectId { o["projectId"] = v.map(JSONValue.string) ?? .null }108 return try await http.decode(R.self, .json("PATCH", "/api/conversations/\(id)", object: o)).conversation109 }110111 func deleteConversation(_ id: String) async throws { _ = try await http.data(HTTPRequest(method: "DELETE", path: "/api/conversations/\(id)")) }112113 func activateBranch(conversation id: String, messageId: String) async throws {114 _ = try await http.data(.json("POST", "/api/conversations/\(id)/branch", object: ["activate": .string(messageId)]))115 }116 func fork(conversation id: String, at messageId: String) async throws -> Conversation {117 struct R: Decodable { var conversation: Conversation }118 return try await http.decode(R.self, .json("POST", "/api/conversations/\(id)/branch", object: ["messageId": .string(messageId)])).conversation119 }120 func export(conversation id: String, format: String) async throws -> Data {121 try await http.data(HTTPRequest(path: "/api/conversations/\(id)/export", query: [.init(name: "format", value: format)], accept: "*/*"))122 }123 func search(_ query: String) async throws -> [SearchHit] {124 struct R: Decodable { var results: [SearchHit] }125 return try await http.decode(R.self, .get("/api/search", query: [.init(name: "q", value: query)])).results126 }127128 // MARK: generation129130 func cancel(runId: String?, messageId: String?) async throws {131 var o: [String: JSONValue] = [:]132 if let runId { o["runId"] = .string(runId) }133 if let messageId { o["messageId"] = .string(messageId) }134 _ = try await http.data(.json("POST", "/api/chat/cancel", object: o))135 }136 /// Starts a turn (`/api/chat`, `/api/chat/regenerate`, `/api/chat/edit`, `/api/chat/approve`). The body carries the idempotency key.137 func openTurn(path: String, payload: [String: JSONValue]) async throws -> HTTPClient.StreamOpening {138 var r = HTTPRequest.json("POST", path, object: payload); r.timeout = 120139 return try await http.openStream(r)140 }141 func attach(runId: String, after: Int) async throws -> HTTPClient.StreamOpening {142 var r = HTTPRequest.get("/api/chat/stream", query: [.init(name: "run", value: runId), .init(name: "after", value: String(after))]); r.timeout = 120143 return try await http.openStream(r)144 }145146 // MARK: models, presets, settings147148 func models() async throws -> (models: [AIModel], defaultModel: String?) {149 struct R: Decodable { var models: [AIModel]; var defaultModel: String? }150 let r = try await http.decode(R.self, .get("/api/models"))151 return (r.models, r.defaultModel)152 }153 func setModel(_ id: String, favorite: Bool? = nil, makeDefault: Bool? = nil) async throws {154 var o: [String: JSONValue] = ["id": .string(id)]155 if let favorite { o["favorite"] = .bool(favorite) }156 if let makeDefault { o["default"] = .bool(makeDefault) }157 _ = try await http.data(.json("PATCH", "/api/models", object: o))158 }159 func presets() async throws -> [Preset] {160 struct R: Decodable { var presets: [Preset] }161 return try await http.decode(R.self, .get("/api/presets")).presets162 }163 func projects() async throws -> [Project] {164 struct R: Decodable { var projects: [Project] }165 return try await http.decode(R.self, .get("/api/projects")).projects166 }167 func createProject(name: String) async throws -> Project {168 struct R: Decodable { var project: Project }169 return try await http.decode(R.self, .json("POST", "/api/projects", object: ["name": .string(name)])).project170 }171 func settings() async throws -> JSONValue { try await http.decode(JSONValue.self, .get("/api/settings")) }172 func updateSetting(key: String, value: [String: JSONValue]) async throws {173 _ = try await http.data(.json("PATCH", "/api/settings", object: ["key": .string(key), "value": .object(value)]))174 }175 func usage(days: Int = 30) async throws -> UsageReport {176 let from = ISO8601.string(Date().addingTimeInterval(-Double(days) * 86_400))177 return try await http.decode(UsageReport.self, .get("/api/usage", query: [.init(name: "from", value: from)]))178 }179180 // MARK: drafts181182 func draft(scope: String) async throws -> String? {183 struct R: Decodable { struct D: Decodable { var text: String }; var draft: D? }184 return try await http.decode(R.self, .get("/api/drafts", query: [.init(name: "scope", value: scope)])).draft?.text185 }186 func saveDraft(scope: String, text: String) async throws {187 _ = try await http.data(.json("PUT", "/api/drafts", object: ["scope": .string(scope), "text": .string(text), "attachmentIds": .array([])]))188 }189190 // MARK: attachments191192 func upload(filename: String, mime: String, data: Data, conversationId: String?, projectId: String?, progress: @escaping @Sendable (Double) -> Void) async throws -> Attachment {193 struct R: Decodable { var attachments: [Attachment] }194 var form = MultipartForm()195 if let conversationId { form.addField("conversationId", conversationId) }196 if let projectId { form.addField("projectId", projectId) }197 form.addFile("file", filename: filename, mime: mime, content: data)198 var req = HTTPRequest(method: "POST", path: "/api/attachments", body: .multipart(data: form.finalized(), boundary: form.boundary)); req.timeout = 180199 let out = try await http.upload(req, progress: progress)200 guard let a = (try? JSONDecoder().decode(R.self, from: out))?.attachments.first else { throw APIError.decoding("attachments") }201 progress(1)202 return a203 }204 func attachmentData(_ id: String) async throws -> Data {205 var r = HTTPRequest(path: "/api/attachments/\(id)", accept: "*/*"); r.timeout = 120206 return try await http.data(r)207 }208 func deleteAttachment(_ id: String) async throws { _ = try await http.data(HTTPRequest(method: "DELETE", path: "/api/attachments/\(id)")) }209 func files(query: String? = nil) async throws -> (files: [Attachment], storage: StorageInfo?) {210 struct R: Decodable { var attachments: [Attachment]; var storage: StorageInfo? }211 let r = try await http.decode(R.self, .get("/api/attachments", query: query.map { [.init(name: "q", value: $0)] } ?? []))212 return (r.attachments, r.storage)213 }214 func artifact(_ id: String) async throws -> Artifact {215 struct R: Decodable { var artifact: Artifact }216 return try await http.decode(R.self, .get("/api/artifacts/\(id)")).artifact217 }218219 // MARK: voice220221 func transcribe(audio: Data, filename: String, mime: String, language: String?, durationSec: Double) async throws -> String {222 struct R: Decodable { var text: String }223 var form = MultipartForm()224 if let language, !language.isEmpty { form.addField("language", language) }225 form.addField("durationSec", String(Int(durationSec.rounded())))226 form.addFile("audio", filename: filename, mime: mime, content: audio)227 var req = HTTPRequest(method: "POST", path: "/api/stt", body: .multipart(data: form.finalized(), boundary: form.boundary)); req.timeout = 120228 return try await http.decode(R.self, req).text229 }230 func speech(text: String, voice: String) async throws -> Data {231 var r = HTTPRequest.json("POST", "/api/tts", object: ["text": .string(String(text.prefix(4000))), "voice": .string(voice)]); r.accept = "audio/mpeg"; r.timeout = 120232 return try await http.data(r)233 }234235 // MARK: prompts, memory236237 func prompts(query: String? = nil) async throws -> [SavedPrompt] {238 struct R: Decodable { var prompts: [SavedPrompt] }239 return try await http.decode(R.self, .get("/api/prompts", query: query.map { [.init(name: "q", value: $0)] } ?? [])).prompts240 }241 func createPrompt(title: String, body: String) async throws {242 _ = try await http.data(.json("POST", "/api/prompts", object: ["title": .string(title), "body": .string(body), "tags": .array([])]))243 }244 func markPromptUsed(_ id: String) async throws { _ = try await http.data(.json("PATCH", "/api/prompts/\(id)", object: ["used": .bool(true)])) }245 func deletePrompt(_ id: String) async throws { _ = try await http.data(HTTPRequest(method: "DELETE", path: "/api/prompts/\(id)")) }246247 func memories() async throws -> [Memory] {248 struct R: Decodable { var memories: [Memory] }249 return try await http.decode(R.self, .get("/api/memories")).memories250 }251 func createMemory(content: String) async throws { _ = try await http.data(.json("POST", "/api/memories", object: ["content": .string(content)])) }252 func setMemory(_ id: String, status: String) async throws { _ = try await http.data(.json("PATCH", "/api/memories/\(id)", object: ["status": .string(status)])) }253 func deleteMemory(_ id: String) async throws { _ = try await http.data(HTTPRequest(method: "DELETE", path: "/api/memories/\(id)")) }254255 // MARK: account & security256257 func authState() async throws -> AuthState { try await http.decode(AuthState.self, .get("/api/auth/state")) }258 func logout() async throws { _ = try await http.data(.json("POST", "/api/auth/logout")) }259 func passkeys() async throws -> (passkeys: [Passkey], recoveryRemaining: Int?) {260 struct R: Decodable { var passkeys: [Passkey]; var recovery: JSONValue? }261 let r = try await http.decode(R.self, .get("/api/auth/passkeys"))262 return (r.passkeys, r.recovery?["remaining"]?.intValue)263 }264 func renamePasskey(_ id: String, label: String) async throws { _ = try await http.data(.json("PATCH", "/api/auth/passkeys/\(id)", object: ["label": .string(label)])) }265 func revokePasskey(_ id: String) async throws -> Bool {266 struct R: Decodable { var signedOut: Bool? }267 return try await http.decode(R.self, HTTPRequest(method: "DELETE", path: "/api/auth/passkeys/\(id)")).signedOut ?? false268 }269 func sessions() async throws -> [DeviceSession] {270 struct R: Decodable { var sessions: [DeviceSession] }271 return try await http.decode(R.self, .get("/api/auth/sessions")).sessions272 }273 func revokeSession(_ id: String) async throws -> Bool {274 struct R: Decodable { var signedOut: Bool? }275 return try await http.decode(R.self, HTTPRequest(method: "DELETE", path: "/api/auth/sessions/\(id)")).signedOut ?? false276 }277 func revokeOtherSessions() async throws -> Int {278 struct R: Decodable { var closed: Int? }279 return try await http.decode(R.self, .json("DELETE", "/api/auth/sessions", object: ["includeCurrent": .bool(false)])).closed ?? 0280 }281 func rotateRecoveryCodes() async throws -> [String] {282 struct R: Decodable { var codes: [String] }283 return try await http.decode(R.self, .json("POST", "/api/auth/recovery-codes")).codes284 }285 func fullExport() async throws -> Data {286 var r = HTTPRequest(path: "/api/owner", accept: "*/*"); r.timeout = 180287 return try await http.data(r)288 }289}290291extension Data {292 func base64URLEncodedString() -> String {293 base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")294 }295 init?(base64URLEncoded s: String) {296 var b = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")297 while b.count % 4 != 0 { b.append("=") }298 self.init(base64Encoded: b)299 }300}301