Repository Public
1// SP Notes Core2// File: Sources/SPNotesSync/Repositories/AssistantRepository.swift3// Description: Ask and inline AI actions for the apps: the chat with its scope (all / page / project / selection) and citations that carry the block to scroll to, the action list including the 3.0 ones, link suggestions as data, and the model catalogue (creator, route, logo path). Online only; every result is AI and never applied without a user action.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import SPNotesAPI9import SPNotesStore1011/// A citation of an answer: where to scroll.12public struct AssistantCitation: Sendable, Equatable, Identifiable {13 /// The marker `[n]` in the answer.14 public var n: Int15 public var pageId: String?16 /// The block that best supports the citation (scroll to the node whose `id` attr is this); nil for a file or a selection.17 public var blockId: String?18 public var title: String?19 public var heading: String?20 public var quote: String?21 /// `block | page | file | selection` (`AISourceAnchor`).22 public var anchor: String?23 public var id: Int { n }2425 init(_ source: AISourceRef) {26 n = source.n; pageId = source.pageId; blockId = source.blockId; title = source.title; heading = source.heading27 quote = source.quote ?? source.excerpt; anchor = source.anchor28 }29}3031/// An inline action offered to the user.32public struct AssistantAction: Sendable, Equatable, Identifiable {33 public var id: String34 /// True for the actions added by 3.0 (`coherence, questions, synthesis, structure, links`).35 public var isNew: Bool36 /// `links` answers with data (`AIEvent.linkSuggestions`), not text.37 public var returnsData: Bool38}3940public struct AssistantRepository: Sendable {41 let context: RepositoryContext42 public init(context: RepositoryContext) { self.context = context }4344 /// Every action id the server accepts, the 3.0 ones last.45 public func actions() -> [AssistantAction] {46 AIActionKind.allCases.map { AssistantAction(id: $0.rawValue, isNew: false, returnsData: false) }47 + AIActionID.next.map { AssistantAction(id: $0, isNew: true, returnsData: $0 == AIActionID.links) }48 }4950 /// Ask My Knowledge. `scope`: `AIChatScope.all | page | project | selection` (`page` / `project` need `pageId`51 /// or `projectId`; `selection` needs `selection`). Errors before the stream (offline, `confirm_expensive`,52 /// `not_configured`) are thrown; the rest arrives as events. Citations: `citations(of:)`.53 public func ask(_ message: String, scope: String = AIChatScope.all, pageId: String? = nil, projectId: String? = nil, selection: String? = nil,54 selectionBlockId: String? = nil, conversationId: String? = nil, model: String? = nil, confirmExpensive: Bool? = nil,55 clientId: String = NotesAPI.newID()) async throws -> AsyncThrowingStream<AIEvent, Error> {56 var request = AIChatRequest(message: message, conversationId: conversationId, clientId: clientId, pageId: pageId, model: model, confirmExpensive: confirmExpensive)57 request.scope = scope58 request.projectId = projectId59 request.selection = selection60 request.selectionBlockId = selectionBlockId61 let sent = request62 return try await context.online { try await context.api.aiChat(sent) }63 }6465 /// The citations of a `meta` (retrieved) or `done` (actually cited) event, each with its `blockId`.66 public func citations(of event: AIEvent) -> [AssistantCitation] {67 switch event {68 case .meta(let meta): return meta.sources.map(AssistantCitation.init)69 case .done(let done): return done.sources.map(AssistantCitation.init)70 default: return []71 }72 }7374 /// An inline action on a text (`actions()` lists the ids). `links` yields one `AIEvent.linkSuggestions`.75 public func run(action: String, text: String, pageId: String? = nil, instruction: String? = nil, model: String? = nil, language: String? = nil,76 confirmExpensive: Bool? = nil) async throws -> AsyncThrowingStream<AIEvent, Error> {77 let call = AIActionCall(action: action, text: text, pageId: pageId, instruction: instruction, model: model, language: language, confirmExpensive: confirmExpensive)78 return try await context.online { try await context.api.aiAction(call) }79 }8081 /// The model catalogue (group by `creator`, show the `route` badge, `logo` = path under the server origin, an82 /// unavailable model cannot be selected, "Auto" = `model: nil`). Cached for offline display of past choices.83 public func models(_ query: AIModelQuery = AIModelQuery(), policy: CachePolicy = .cacheFirst(maxAge: Staleness.models)) async throws -> Cached<AIModelCatalog> {84 let key = CacheKey.models + "." + SyncEngine.fingerprint(Data("\(query)".utf8))85 return try await context.read(key, policy: policy) { try await context.api.aiModelCatalog(query) }86 }8788 /// The absolute URL of a logo path of the catalogue (`/model-logos/<creator>.svg`).89 public func logoURL(_ path: String) async -> URL? {90 URL(string: path, relativeTo: await context.api.client.configuration.baseURL)?.absoluteURL91 }92}93