Repository Public
1// SP Notes Core2// File: Sources/SPNotesAPI/AIModels.swift3// Description: Requests and stream events of the AI routes (inline actions on a selection, chat). The server only4// returns text: nothing is written to a note by these routes.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910/// The inline actions of `POST /api/ai/action`.11public enum AIActionKind: String, Codable, Sendable, CaseIterable {12 case rewrite, fix13 /// Needs `language` (fr, en, es, de, it, pt).14 case translate15 case summarize, expand, explain16 case toList = "to_list"17 case toTasks = "to_tasks"18 case table, shorten, formal, simplify19 case translateFR = "translate_fr"20 case translateEN = "translate_en"21 case explainMath = "explain_math"22 case `continue`23 case outline24 case studyNotes = "study_notes"25 case actionItems = "action_items"26 case contradictions27 /// Needs `instruction`.28 case custom29}3031/// Body of `POST /api/ai/action`.32public struct AIActionRequest: Encodable, Sendable, Equatable {33 public var action: AIActionKind34 /// The selection (≤ 120 000 characters).35 public var text: String36 public var instruction: String?37 public var model: String?38 public var language: String?39 /// Accept a request the server announced as expensive (`409 confirm_expensive`).40 public var confirmExpensive: Bool?4142 public init(action: AIActionKind, text: String, instruction: String? = nil, model: String? = nil, language: String? = nil, confirmExpensive: Bool? = nil) {43 self.action = action44 self.text = text45 self.instruction = instruction46 self.model = model47 self.language = language48 self.confirmExpensive = confirmExpensive49 }50}5152public enum AIChatMode: String, Codable, Sendable, CaseIterable {53 case notes, summarise, actions, contradictions, draft, general54}5556/// Body of `POST /api/ai/chat`.57public struct AIChatRequest: Encodable, Sendable, Equatable {58 public var conversationId: String?59 /// Identifies one send (`[A-Za-z0-9_-]{8,64}`): repeating it after a lost connection replays the stored answer60 /// instead of calling the provider again.61 public var clientId: String?62 public var message: String63 public var mode: AIChatMode?64 public var pageId: String?65 public var model: String?66 /// Task class (`chat`, `quick`, `write`, `reason`, `deep`, `code`, `extract`, `longctx`, `agent`, `judge`).67 public var task: String?68 public var useWorkspace: Bool?69 public var confirmExpensive: Bool?70 public var scopePageIds: [String]?71 /// 3.0 — where the evidence may come from: `AIChatScope.all | page | project | selection` (server default `all`).72 public var scope: String?73 /// 3.0 — with `scope: "project"`: that page and all its descendants (default: the root ancestor of `pageId`).74 public var projectId: String?75 /// 3.0 — with `scope: "selection"`: the only text the model may use (≤ 20 000 characters).76 public var selection: String?77 /// 3.0 — the block the selection was made in (echoed as the citation's `blockId` when it exists in `pageId`).78 public var selectionBlockId: String?7980 public init(message: String, conversationId: String? = nil, clientId: String? = nil, mode: AIChatMode? = nil, pageId: String? = nil, model: String? = nil, task: String? = nil, useWorkspace: Bool? = nil, confirmExpensive: Bool? = nil, scopePageIds: [String]? = nil,81 scope: String? = nil, projectId: String? = nil, selection: String? = nil, selectionBlockId: String? = nil) {82 self.scope = scope83 self.projectId = projectId84 self.selection = selection85 self.selectionBlockId = selectionBlockId86 self.message = message87 self.conversationId = conversationId88 self.clientId = clientId89 self.mode = mode90 self.pageId = pageId91 self.model = model92 self.task = task93 self.useWorkspace = useWorkspace94 self.confirmExpensive = confirmExpensive95 self.scopePageIds = scopePageIds96 }97}9899/// First event of a stream: which model answers and why.100public struct AIMeta: Sendable, Equatable {101 public var model: String?102 public var provider: String?103 public var reason: String?104 public var budgetNote: String?105 /// Chat only.106 public var conversationId: String?107 /// The complete event (chat adds `mode`, `task`, `sources`, `weak`, `evidence`…).108 public var raw: RawJSON109}110111/// Last event of a successful stream.112public struct AIDone: Sendable, Equatable {113 public var costUsd: Double?114 public var latencyMs: Double?115 /// Token usage as reported by the provider.116 public var usage: RawJSON?117 /// Chat only: the stored assistant message.118 public var messageId: String?119 /// Chat only: the final text (after citation checks).120 public var content: String?121 /// The complete event (chat adds `sources`, `evidence`, `invalidCitations`…).122 public var raw: RawJSON123}124125/// An error reported inside the stream (the HTTP status was already 200).126public struct AIStreamError: Error, Sendable, Equatable {127 /// `provider_error`, `refused`, `not_configured`, `no_model`, `page_required`, `server_error`…128 public var code: String?129 public var retryable: Bool130 public var message: String131 public var raw: RawJSON132}133134/// Chat only: the request is expensive; nothing was sent to a provider. Send again with `confirmExpensive: true`.135public struct AIConfirmation: Sendable, Equatable {136 public var reason: String?137 public var plan: RawJSON138}139140/// One event of an AI stream.141public enum AIEvent: Sendable, Equatable {142 case meta(AIMeta)143 /// A piece of the answer (Markdown).144 case text(String)145 case done(AIDone)146 case error(AIStreamError)147 case needsConfirmation(AIConfirmation)148 /// An event type this client does not know (forward compatibility).149 case other(type: String, raw: RawJSON)150151 /// Decodes the JSON of one `data:` line. Returns `nil` when it is not a JSON object with a `type`.152 public init?(json data: Data) {153 guard let value = try? JSONValue(parsing: data), let type = value["type"]?.stringValue else { return nil }154 let raw = RawJSON(data: data)155 switch type {156 case "meta":157 self = .meta(AIMeta(model: value["model"]?.stringValue, provider: value["provider"]?.stringValue, reason: value["reason"]?.stringValue,158 budgetNote: value["budgetNote"]?.stringValue, conversationId: value["conversationId"]?.stringValue, raw: raw))159 case "text":160 self = .text(value["delta"]?.stringValue ?? "")161 case "done":162 let usage = value["usage"].flatMap { $0.isNull ? nil : $0.raw() }163 self = .done(AIDone(costUsd: value["costUsd"]?.doubleValue, latencyMs: value["latencyMs"]?.doubleValue, usage: usage,164 messageId: value["messageId"]?.stringValue, content: value["content"]?.stringValue, raw: raw))165 case "error":166 self = .error(AIStreamError(code: value["code"]?.stringValue, retryable: value["retryable"]?.boolValue ?? false,167 message: value["message"]?.stringValue ?? "The AI request failed.", raw: raw))168 case "needs_confirmation":169 self = .needsConfirmation(AIConfirmation(reason: value["reason"]?.stringValue, plan: value["plan"]?.raw() ?? .null))170 default:171 self = .other(type: type, raw: raw)172 }173 }174}175