Repository Public
1// SP Notes iOS2// File: Features/AI/AssistantProvider.swift3// Description: The assistant's source of answers: a small protocol (a stream of events for an action or a chat request) and its4// MacLustr backend implementation. The server chooses the provider (OpenAI, Anthropic) and holds the keys: the app has5// none. Also the catalogue of actions and the wording of failures.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import SPNotesCore1112enum AssistantRequest: Sendable, Equatable {13 case action(AIActionRequest)14 case chat(AIChatRequest)15}1617/// Anything that can answer an assistant request with a stream of events (`meta`, `text`, `done`, `error`, `needsConfirmation`).18/// Errors raised before the stream starts are thrown by `events(for:)`.19protocol AssistantProvider: Sendable {20 func events(for request: AssistantRequest) async throws -> AsyncThrowingStream<AIEvent, Error>21}2223/// The SP Notes backend (`/api/ai/action`, `/api/ai/chat`), which routes to the configured provider.24struct BackendAssistantProvider: AssistantProvider {25 let api: NotesAPI2627 func events(for request: AssistantRequest) async throws -> AsyncThrowingStream<AIEvent, Error> {28 switch request {29 case .action(let body): return try await api.aiAction(body)30 case .chat(let body): return try await api.aiChat(body)31 }32 }33}3435// MARK: - Failures3637struct AssistantFailure: Error, Equatable {38 enum Kind: Equatable { case offline, sessionExpired, notConfigured, provider, emptyText, tooLong, pageNotSynced, other }39 var kind: Kind40 /// Technical detail from the server, shown under the explanation when there is one.41 var detail: String?42 var retryable: Bool4344 init(_ kind: Kind, detail: String? = nil, retryable: Bool? = nil) {45 self.kind = kind46 self.detail = detail47 self.retryable = retryable ?? (kind == .offline || kind == .provider || kind == .other)48 }4950 var title: String {51 switch kind {52 case .offline: String(localized: "Tu es hors ligne")53 case .sessionExpired: String(localized: "Session terminée")54 case .notConfigured: String(localized: "Assistant non configuré")55 case .provider: String(localized: "Le fournisseur n’a pas répondu")56 case .emptyText: String(localized: "Rien à traiter")57 case .tooLong: String(localized: "Texte trop long")58 case .pageNotSynced: String(localized: "Note pas encore synchronisée")59 case .other: String(localized: "La demande a échoué")60 }61 }6263 var message: String {64 switch kind {65 case .offline: String(localized: "L’assistant a besoin du réseau. Tes notes restent modifiables ; réessaie une fois connecté.")66 case .sessionExpired: String(localized: "Connecte-toi de nouveau pour utiliser l’assistant. Tes notes restent sur l’appareil.")67 case .notConfigured: String(localized: "Aucun modèle n’est configuré sur le serveur. Il n’y a rien à régler dans l’app.")68 case .provider: String(localized: "Le service d’IA a renvoyé une erreur. Rien n’a été modifié dans ta note.")69 case .emptyText: String(localized: "La note est vide : écris ou sélectionne du texte, ou donne une instruction libre.")70 case .tooLong: String(localized: "Le texte dépasse 120 000 caractères. Sélectionne un passage plus court.")71 case .pageNotSynced: String(localized: "Ce mode travaille sur la copie du serveur, et cette note n’y est pas encore. Réessaie après la synchronisation.")72 case .other: String(localized: "Rien n’a été modifié dans ta note.")73 }74 }7576 var symbol: String {77 switch kind {78 case .offline: "wifi.slash"79 case .sessionExpired: "person.crop.circle.badge.exclamationmark"80 case .notConfigured: "gearshape.2"81 case .emptyText, .tooLong, .pageNotSynced: "text.badge.xmark"82 case .provider, .other: "exclamationmark.triangle"83 }84 }8586 /// Maps what the provider throws before or during the stream.87 static func from(_ error: Error) -> AssistantFailure {88 if let failure = error as? AssistantFailure { return failure }89 if let stream = error as? AIStreamError { return from(stream) }90 guard let api = error as? APIError else { return AssistantFailure(.other, detail: error.localizedDescription) }91 switch api {92 case .offline: return AssistantFailure(.offline)93 case .transport, .timeout: return AssistantFailure(.offline, detail: api.message)94 default: break95 }96 if api.isUnauthenticated { return AssistantFailure(.sessionExpired) }97 if api.code == APIError.Code.notConfigured || api.code == APIError.Code.noModel { return AssistantFailure(.notConfigured, detail: api.message) }98 if let status = api.status, status >= 500 || status == 429 { return AssistantFailure(.provider, detail: api.message, retryable: true) }99 return AssistantFailure(.other, detail: api.message, retryable: api.isRetryable)100 }101102 /// Maps an `error` event of the stream.103 static func from(_ error: AIStreamError) -> AssistantFailure {104 switch error.code {105 case "not_configured", "no_model": return AssistantFailure(.notConfigured, detail: error.message)106 case "page_required": return AssistantFailure(.pageNotSynced, detail: error.message)107 default: return AssistantFailure(.provider, detail: error.message, retryable: true)108 }109 }110}111112/// What the server says about a request it considers expensive.113struct AssistantCostPlan: Decodable, Equatable {114 var expensive: String?115 var estCostUsd: Double?116 var model: String?117 var provider: String?118119 /// The sentence shown before asking to continue: the server's own explanation, with the model when it is known.120 static func message(plan: RawJSON, fallback: String?) -> String {121 let decoded = try? plan.decode(AssistantCostPlan.self)122 var parts: [String] = []123 if let text = decoded?.expensive ?? fallback, !text.isEmpty { parts.append(text) }124 if let cost = decoded?.estCostUsd, parts.isEmpty { parts.append(String(localized: "Coût estimé : \(cost.formatted(.currency(code: "USD")))")) }125 if let model = decoded?.model, !model.isEmpty { parts.append(String(localized: "Modèle : \(model)")) }126 return parts.isEmpty ? String(localized: "Cette demande est coûteuse.") : parts.joined(separator: "\n")127 }128}129130enum AssistantText {131 /// "claude-haiku · anthropic" — which model answers, as reported by the server.132 static func modelLine(_ meta: AIMeta) -> String? {133 let parts = [meta.model, meta.provider].compactMap { $0 }.filter { !$0.isEmpty }134 return parts.isEmpty ? nil : parts.joined(separator: " · ")135 }136137 static let maxActionCharacters = 120_000138}139140// MARK: - Catalogue of actions141142struct AssistantAction: Identifiable, Hashable {143 var kind: AIActionKind144 var title: String145 var symbol: String146 var id: String { kind.rawValue }147}148149struct AssistantActionGroup: Identifiable {150 var title: String151 var actions: [AssistantAction]152 var id: String { title }153}154155struct AssistantLanguage: Identifiable, Hashable {156 var code: String157 var name: String158 var id: String { code }159}160161enum AssistantCatalog {162 static var groups: [AssistantActionGroup] {163 [164 AssistantActionGroup(title: String(localized: "Comprendre"), actions: [165 AssistantAction(kind: .summarize, title: String(localized: "Résumer"), symbol: "text.redaction"),166 AssistantAction(kind: .explain, title: String(localized: "Expliquer"), symbol: "lightbulb"),167 AssistantAction(kind: .toList, title: String(localized: "Idées principales"), symbol: "list.bullet"),168 AssistantAction(kind: .actionItems, title: String(localized: "Actions à faire"), symbol: "checkmark.circle"),169 ]),170 AssistantActionGroup(title: String(localized: "Réécrire"), actions: [171 AssistantAction(kind: .rewrite, title: String(localized: "Reformuler"), symbol: "arrow.triangle.2.circlepath"),172 AssistantAction(kind: .fix, title: String(localized: "Corriger"), symbol: "textformat.abc.dottedunderline"),173 AssistantAction(kind: .simplify, title: String(localized: "Simplifier"), symbol: "wand.and.stars"),174 AssistantAction(kind: .expand, title: String(localized: "Développer"), symbol: "arrow.up.left.and.arrow.down.right"),175 AssistantAction(kind: .shorten, title: String(localized: "Raccourcir"), symbol: "arrow.down.right.and.arrow.up.left"),176 AssistantAction(kind: .formal, title: String(localized: "Ton soutenu"), symbol: "briefcase"),177 AssistantAction(kind: .translate, title: String(localized: "Traduire"), symbol: "globe"),178 ]),179 AssistantActionGroup(title: String(localized: "Structurer"), actions: [180 AssistantAction(kind: .outline, title: String(localized: "Générer un plan"), symbol: "list.number"),181 AssistantAction(kind: .toTasks, title: String(localized: "Liste de tâches"), symbol: "checklist"),182 AssistantAction(kind: .table, title: String(localized: "Tableau"), symbol: "tablecells"),183 AssistantAction(kind: .continue, title: String(localized: "Continuer"), symbol: "text.append"),184 ]),185 ]186 }187188 static var languages: [AssistantLanguage] {189 [190 AssistantLanguage(code: "fr", name: String(localized: "Français")),191 AssistantLanguage(code: "en", name: String(localized: "Anglais")),192 AssistantLanguage(code: "es", name: String(localized: "Espagnol")),193 AssistantLanguage(code: "de", name: String(localized: "Allemand")),194 AssistantLanguage(code: "it", name: String(localized: "Italien")),195 AssistantLanguage(code: "pt", name: String(localized: "Portugais")),196 ]197 }198199 static func title(for kind: AIActionKind) -> String {200 if kind == .custom { return String(localized: "Instruction libre") }201 return groups.flatMap(\.actions).first { $0.kind == kind }?.title ?? kind.rawValue202 }203}204