Repository Public
1// SP Notes Core2// File: Sources/SPNotesAPI/AICatalogModels.swift3// Description: Models of the 3.0 AI workstream (API-NEXT-AI §1–§3, §7, §9): the model catalogue with creators and4// routes, the scope of a chat turn and its verified citations, the new inline actions and the link5// suggestions of `links`, the smart database properties, and the error codes.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation1011// MARK: - Model catalogue1213/// `routeKind` of a model / `kind` of a provider: the API family the call goes through.14public enum AIRouteKind {15 public static let openAI = "openai"16 public static let anthropic = "anthropic"17 public static let openAICompatible = "openai_compatible"18}1920/// `unavailableReason` of a model.21public enum AIUnavailableReason {22 public static let noKey = "no_key"23 public static let providerDisabled = "provider_disabled"24 public static let notListed = "not_listed"25 public static let disabled = "disabled"26}2728/// The normalised booleans of `capabilities` (`nil` = unknown) and where they come from.29public struct AIModelCapabilities: Codable, Sendable, Equatable {30 public var text: Bool?31 public var streaming: Bool?32 public var tools: Bool?33 public var structuredOutput: Bool?34 public var jsonMode: Bool?35 public var vision: Bool?36 public var reasoning: Bool?37 /// `measured` (probed against the real API), `declared` (provider catalogue) or `unknown`.38 public var source: String?39}4041/// One model of `GET /api/ai/models`. The historical 2.x fields come first; the 3.0 fields (`creator` … `autoRoutable`)42/// are absent on a server without the AI workstream. Send back exactly `id` as `model`.43public struct AIModelInfo: Codable, Sendable, Equatable, Identifiable {44 /// Opaque (≤ 200 characters): `claude-haiku-5-5`, or `<provider>:<remote id>` for OpenAI-compatible providers.45 public var id: String46 public var provider: String?47 public var displayName: String?48 /// `text`, `embedding`, `image`, `audio`, `search`, `realtime`…49 public var category: String?50 /// Usable now. `false` = cannot be selected (`unavailableReason`).51 public var available: Bool?52 public var enabled: Bool?53 public var contextWindow: Int?54 public var maxOutput: Int?55 /// USD per 1M tokens (historical names of `priceIn` / `priceCached` / `priceOut`).56 public var inputPrice: Double?57 public var cachedPrice: Double?58 public var outputPrice: Double?59 public var pricingSource: String?60 /// Free-form: the measured probes.61 public var probes: RawJSON?62 /// Free-form: the benchmark aggregate.63 public var benchmark: RawJSON?64 /// Free-form: the provider-declared object plus the normalised booleans (`normalizedCapabilities`).65 public var capabilities: RawJSON?66 public var notes: [String]?67 public var discoveredAt: Date?68 public var probedAt: Date?69 public var benchmarkedAt: Date?70 public var createdAt: Date?71 public var updatedAt: Date?7273 // 3.074 /// Who made the model (group the picker by it).75 public var creator: String?76 public var creatorName: String?77 /// `/model-logos/<creator>.svg`, or `/model-logos/generic.svg` (then show `monogram`). Single-colour SVG: tint it.78 public var logo: String?79 public var monogram: String?80 /// The API the call goes through (= provider id): show it as a badge distinct from the creator.81 public var route: String?82 public var routeLabel: String?83 /// `AIRouteKind`.84 public var routeKind: String?85 public var routeLogo: String?86 public var remoteId: String?87 /// Context window in tokens (`nil` = not published).88 public var context: Int?89 /// USD per 1M tokens (`nil` = not published, 0 = free).90 public var priceIn: Double?91 public var priceOut: Double?92 public var priceCached: Double?93 public var priceUnit: String?94 /// The provider still lists it.95 public var listed: Bool?96 /// `AIUnavailableReason`.97 public var unavailableReason: String?98 public var benchmarked: Bool?99 /// Takes part in automatic routing. `false` = manual selection only.100 public var autoRoutable: Bool?101102 /// The normalised capability booleans (all `nil` on a 2.x server, which only has the provider-declared keys).103 public var normalizedCapabilities: AIModelCapabilities? { try? capabilities?.decode(AIModelCapabilities.self) }104105 /// Whether a picker may offer the model (`available`; a 2.x server always sends it).106 public var isSelectable: Bool { available ?? false }107}108109/// One provider of `GET /api/ai/models`. `keyEnv` is the **name** of an environment variable, never a key.110public struct AIProviderInfo: Codable, Sendable, Equatable, Identifiable {111 public var id: String112 public var name: String?113 public var enabled: Bool?114 public var lastDiscoveryAt: Date?115 /// `unknown`, `no_key`…116 public var status: String?117 public var statusDetail: String?118 /// The key variable is set on the server.119 public var configured: Bool?120121 // 3.0122 /// `AIRouteKind`.123 public var kind: String?124 public var baseUrl: String?125 public var keyEnv: String?126 public var label: String?127 /// Configured and enabled. A provider without key is listed and never routed to.128 public var available: Bool?129 public var logo: String?130}131132/// One creator of `GET /api/ai/models` (3.0).133public struct AIModelCreator: Codable, Sendable, Equatable, Identifiable {134 public var id: String135 public var name: String?136 public var logo: String?137 public var monogram: String?138 /// `true` when `logo` is the generic one: show `monogram`.139 public var generic: Bool?140}141142/// `GET /api/ai/models`.143public struct AIModelCatalog: Codable, Sendable, Equatable {144 public var models: [AIModelInfo]145 public var providers: [AIProviderInfo]146 /// 3.0.147 public var creators: [AIModelCreator]?148 /// 3.0: models of key-less OpenAI-compatible providers left out of `models` (ask with `includeUnavailable`).149 public var hiddenUnavailable: Int?150 /// Free-form (unchanged from 2.x): the route of each task class.151 public var routes: RawJSON?152 public var defaultRoutes: RawJSON?153 /// Task class → label.154 public var taskLabels: [String: String]?155 public var benchmark: RawJSON?156}157158/// Parameters of `GET /api/ai/models` (the filters are 3.0: a 2.x server ignores them).159public struct AIModelQuery: Sendable, Equatable {160 /// `all=1`: also disabled, unlisted and embedding models.161 public var all: Bool162 public var provider: String?163 public var creator: String?164 /// `available=1`: only the models usable now.165 public var availableOnly: Bool166 /// `q=`: free text.167 public var text: String?168 /// `unavailable=1`: include the models of providers that have no key (several hundred for OpenRouter).169 public var includeUnavailable: Bool170171 public init(all: Bool = false, provider: String? = nil, creator: String? = nil, availableOnly: Bool = false, text: String? = nil, includeUnavailable: Bool = false) {172 self.all = all173 self.provider = provider174 self.creator = creator175 self.availableOnly = availableOnly176 self.text = text177 self.includeUnavailable = includeUnavailable178 }179}180181// MARK: - Chat scope and citations182183/// `scope` of `AIChatRequest`: where the evidence may come from.184public enum AIChatScope {185 public static let all = "all"186 /// Needs `pageId`.187 public static let page = "page"188 /// `projectId`, or the root ancestor of `pageId`, and all its descendants.189 public static let project = "project"190 /// Needs `selection`; mode `notes` only; no search is run.191 public static let selection = "selection"192}193194/// `anchor` of a source: what the citation was verified against.195public enum AISourceAnchor {196 /// The block exists in the current page content.197 public static let block = "block"198 /// Verified text, block without id.199 public static let page = "page"200 /// Attachment text: no block.201 public static let file = "file"202 public static let selection = "selection"203}204205/// One source of a chat answer (`sources` / `weak` of `meta`, `sources` of `done`). Open it by scrolling to the block206/// whose `id` attr is `blockId`.207public struct AISourceRef: Codable, Sendable, Equatable {208 /// The number of the citation marker `[n]`.209 public var n: Int210 /// A chunk id, or `selection`.211 public var chunkId: String?212 public var pageId: String?213 public var title: String?214 public var icon: String?215 public var heading: String?216 /// The block that best supports the citation (`nil` when the anchor is not a block).217 public var blockId: String?218 public var excerpt: String?219 public var score: Double?220 public var semantic: Double?221 /// `page`, `selection`…222 public var sourceType: String?223 /// 3.0: every block of the passage.224 public var blockIds: [String]?225 /// 3.0: `AISourceAnchor`.226 public var anchor: String?227 /// 3.0: the first 300 characters of the anchored block as it is in the page now.228 public var quote: String?229}230231private struct AIMetaFields: Decodable {232 var mode: String?233 var task: String?234 var clientId: String?235 var sources: [AISourceRef]?236 var weak: [AISourceRef]?237 var evidence: String?238 var replayed: Bool?239 var scope: String?240 var scopePages: Int?241 var staleDropped: Int?242}243244private struct AIDoneFields: Decodable {245 var sources: [AISourceRef]?246 var evidence: String?247 var invalidCitations: [Int]?248 var uncited: Bool?249 var replayed: Bool?250 var ttftMs: Double?251}252253extension AIMeta {254 private var fields: AIMetaFields? { try? raw.decode(AIMetaFields.self) }255256 /// Chat: the retrieved passages the model may cite.257 public var sources: [AISourceRef] { fields?.sources ?? [] }258 /// Chat: passages retrieved but too weak to be sent.259 public var weakSources: [AISourceRef] { fields?.weak ?? [] }260 /// Chat: `ok`, `none` (no supporting source: no answering provider is called), `insufficient`…261 public var evidence: String? { fields?.evidence }262 public var mode: String? { fields?.mode }263 public var task: String? { fields?.task }264 public var clientId: String? { fields?.clientId }265 /// Chat: the stored answer of an earlier send with the same `clientId`.266 public var replayed: Bool? { fields?.replayed }267 /// 3.0 — `AIChatScope` the server applied.268 public var scope: String? { fields?.scope }269 /// 3.0 — number of pages in the scope (`nil` = unrestricted).270 public var scopePages: Int? { fields?.scopePages }271 /// 3.0 — retrieved passages discarded because their text is no longer in the page.272 public var staleDropped: Int? { fields?.staleDropped }273}274275extension AIDone {276 private var fields: AIDoneFields? { try? raw.decode(AIDoneFields.self) }277278 /// Chat: only the sources the answer cites, anchored to the block closest to the citing sentence.279 public var sources: [AISourceRef] { fields?.sources ?? [] }280 public var evidence: String? { fields?.evidence }281 /// 3.0 — citation markers removed from `content` because they matched no retrieved source.282 public var invalidCitations: [Int]? { fields?.invalidCitations }283 /// 3.0 — the answer cited none of its sources and was withheld.284 public var uncited: Bool? { fields?.uncited }285 public var replayed: Bool? { fields?.replayed }286 /// Time to the first token, in milliseconds.287 public var ttftMs: Double? { fields?.ttftMs }288}289290// MARK: - Inline actions (3.0)291292/// The ids of `POST /api/ai/action`: the 21 historical ones (`AIActionKind`) and the five of 3.0.293public enum AIActionID {294 public static let coherence = "coherence"295 public static let questions = "questions"296 public static let synthesis = "synthesis"297 public static let structure = "structure"298 /// Suggested internal links, returned as data in a `result` event (`AIEvent.linkSuggestions`); no `text` events.299 public static let links = "links"300 /// The ids added by 3.0.301 public static let next = [coherence, questions, synthesis, structure, links]302 /// Every id the server accepts.303 public static let all = AIActionKind.allCases.map(\.rawValue) + next304}305306/// Body of `POST /api/ai/action` with any action id (3.0). `AIActionRequest` keeps working for the historical ones.307public struct AIActionCall: Encodable, Sendable, Equatable {308 /// `AIActionKind.rawValue` or `AIActionID`.309 public var action: String310 /// The selection (≤ 120 000 characters). `links` refuses an empty text (`400 no_text`).311 public var text: String312 /// ≤ 4 000 characters.313 public var instruction: String?314 public var model: String?315 public var language: String?316 public var confirmExpensive: Bool?317 /// 3.0 — the page the text comes from (`links` never suggests it, nor a page it already links to).318 public var pageId: String?319320 public init(action: String, text: String, pageId: String? = nil, instruction: String? = nil, model: String? = nil, language: String? = nil, confirmExpensive: Bool? = nil) {321 self.action = action322 self.text = text323 self.pageId = pageId324 self.instruction = instruction325 self.model = model326 self.language = language327 self.confirmExpensive = confirmExpensive328 }329330 /// A historical request, optionally tied to a page.331 public init(_ request: AIActionRequest, pageId: String? = nil) {332 self.init(action: request.action.rawValue, text: request.text, pageId: pageId, instruction: request.instruction, model: request.model,333 language: request.language, confirmExpensive: request.confirmExpensive)334 }335}336337/// One suggested internal link (`links` action). Nothing is written by the server: the client turns an accepted338/// suggestion into a link on `anchorText` (or inserts a mention) through a normal page save.339public struct AILinkSuggestion: Codable, Sendable, Equatable {340 public var pageId: String341 public var title: String?342 public var icon: String?343 public var blockId: String?344 public var excerpt: String?345 public var score: Double?346 /// Literally present in the text sent, or `nil`.347 public var anchorText: String?348 public var reason: String?349}350351/// `data` of the `result` event of the `links` action.352public struct AILinkSuggestions: Codable, Sendable, Equatable {353 public var ai: Bool?354 /// `nil` when no candidate page existed (no provider was called).355 public var model: String?356 public var links: [AILinkSuggestion]357 /// Candidate pages the server retrieved.358 public var candidates: Int?359}360361private struct AIResultEnvelope<Payload: Decodable>: Decodable { var data: Payload }362363extension AIEvent {364 /// The type of a `result` event (delivered as `.other(type: "result", raw:)`).365 public static let resultType = "result"366367 /// The payload (`data`) of a `result` event, decoded.368 public func result<Payload: Decodable>(_ type: Payload.Type = Payload.self) -> Payload? {369 guard case .other(AIEvent.resultType, let raw) = self else { return nil }370 return (try? raw.decode(AIResultEnvelope<Payload>.self))?.data371 }372373 /// The link suggestions of the `links` action (its `result` event).374 public var linkSuggestions: AILinkSuggestions? { result(AILinkSuggestions.self) }375}376377// MARK: - Smart database properties378379/// `task` of an AI property.380public enum DatabaseAITask {381 /// Free prompt (the 2.x behaviour).382 public static let custom = "custom"383 public static let summarize = "summarize"384 /// Exactly one of `choices`.385 public static let classify = "classify"386 public static let extract = "extract"387 /// ISO `YYYY-MM-DD`.388 public static let detectDate = "detect-date"389 public static let categorize = "categorize"390}391392/// `ai` of an AI property (`config.ai` of the database property).393public struct DatabaseAISettings: Codable, Sendable, Equatable {394 /// `DatabaseAITask`.395 public var task: String?396 /// Required for `custom` and `extract` (≤ 4 000 characters; `{{Property name}}` placeholders).397 public var prompt: String?398 /// Allowed values for `classify` (≥ 2) / `categorize` (≤ 40).399 public var choices: [String]?400 /// A model id of the catalogue; `nil` = the measured route.401 public var model: String?402 /// Recompute the cell when another value of the row changes.403 public var autoRun: Bool?404 /// The AI may overwrite a value typed by hand.405 public var managed: Bool?406}407408/// Partial `ai` of `PUT /api/databases/<id>/ai/config` (merged by the server). `model: .null` clears the override.409public struct DatabaseAISettingsPatch: Encodable, Sendable, Equatable {410 public var task: String?411 public var prompt: String?412 public var choices: [String]?413 public var model: PatchValue<String>?414 public var autoRun: Bool?415 public var managed: Bool?416417 public init(task: String? = nil, prompt: String? = nil, choices: [String]? = nil, model: PatchValue<String>? = nil, autoRun: Bool? = nil, managed: Bool? = nil) {418 self.task = task419 self.prompt = prompt420 self.choices = choices421 self.model = model422 self.autoRun = autoRun423 self.managed = managed424 }425426 enum CodingKeys: String, CodingKey { case task, prompt, choices, model, autoRun, managed }427428 public func encode(to encoder: Encoder) throws {429 var c = encoder.container(keyedBy: CodingKeys.self)430 try c.encodeIfPresent(task, forKey: .task)431 try c.encodeIfPresent(prompt, forKey: .prompt)432 try c.encodeIfPresent(choices, forKey: .choices)433 try c.encodePatch(model, forKey: .model)434 try c.encodeIfPresent(autoRun, forKey: .autoRun)435 try c.encodeIfPresent(managed, forKey: .managed)436 }437}438439/// Run counters of one AI property.440public struct DatabaseAIRunStats: Codable, Sendable, Equatable {441 public var queued: Int?442 public var done: Int?443 public var failed: Int?444 public var skipped: Int?445 public var costUsd: Double?446 public var lastAt: Date?447}448449/// One AI property of a database (`properties` of the configuration, answer of the `PUT`).450public struct DatabaseAIProperty: Codable, Sendable, Equatable {451 public var propertyId: String452 public var name: String?453 public var ai: DatabaseAISettings454 /// Why the configuration cannot run (`"No prompt configured"`…), or `nil`.455 public var problem: String?456 /// `GET` only.457 public var runs: DatabaseAIRunStats?458}459460/// `GET /api/databases/<id>/ai/config`.461public struct DatabaseAIConfig: Codable, Sendable, Equatable {462 /// The task ids the server supports.463 public var tasks: [String]464 public var properties: [DatabaseAIProperty]465}466467/// Why a cell was left exactly as it was.468public enum DatabaseAISkipReason {469 /// A value typed by hand (the property is not `managed` and `force` was not sent).470 public static let userEdited = "user_edited"471 public static let badConfig = "bad_config"472 /// Pending for less than 5 minutes.473 public static let alreadyQueued = "already_queued"474 /// Auto-run only.475 public static let overBudget = "over_budget"476 public static let queueUnavailable = "queue_unavailable"477}478479/// One row of the answer of `POST /api/databases/<id>/ai`.480public struct DatabaseAIRowRun: Codable, Sendable, Equatable {481 public var rowId: String482 public var runId: String?483 public var queued: Bool?484 /// `DatabaseAISkipReason` when the cell was skipped.485 public var skipped: String?486}487488/// One skipped cell.489public struct DatabaseAISkip: Codable, Sendable, Equatable {490 public var rowId: String491 /// `DatabaseAISkipReason`.492 public var reason: String?493 public var runId: String?494}495496/// `POST /api/databases/<id>/ai` (`runs` and `skipped` are 3.0).497public struct DatabaseAIRunResult: Codable, Sendable, Equatable {498 public var ok: Bool?499 /// Number of cells queued.500 public var queued: Int?501 public var runs: [DatabaseAIRowRun]?502 public var skipped: [DatabaseAISkip]?503}504505/// One entry of the run log (`GET /api/databases/<id>/ai/runs`).506public struct DatabaseAIRun: Codable, Sendable, Equatable, Identifiable {507 public var id: String508 public var databaseId: String?509 public var propertyId: String?510 public var rowId: String?511 /// `queued`, `running`, `done`, `failed`, `skipped`.512 public var status: String513 /// `manual` or `auto`.514 public var trigger: String?515 public var task: String?516 public var model: String?517 public var provider: String?518 public var inputTokens: Int?519 public var outputTokens: Int?520 public var costUsd: Double?521 public var error: String?522 public var createdAt: Date?523 public var startedAt: Date?524 public var finishedAt: Date?525}526527/// Filters of `GET /api/databases/<id>/ai/runs` (newest first, ≤ 500).528public struct DatabaseAIRunFilter: Sendable, Equatable {529 public var propertyId: String?530 public var rowId: String?531 public var status: String?532 public var limit: Int?533534 public init(propertyId: String? = nil, rowId: String? = nil, status: String? = nil, limit: Int? = nil) {535 self.propertyId = propertyId536 self.rowId = rowId537 self.status = status538 self.limit = limit539 }540}541542// MARK: - Error codes543544extension APIError {545 /// The codes introduced by the AI workstream (API-NEXT-AI §9), HTTP errors and `AIStreamError.code` alike.546 public enum AICode {547 // Chat (SSE `error`).548 public static let badScope = "bad_scope"549 public static let selectionRequired = "selection_required"550 public static let pageRequired = "page_required"551 // Actions.552 public static let badLanguage = "bad_language"553 public static let noInstruction = "no_instruction"554 /// `400`: `links` with an empty text.555 public static let noText = "no_text"556 /// SSE `error` / `502`: the model answered outside the JSON schema.557 public static let badOutput = "bad_output"558 // Zoom, suggestions.559 public static let providerError = "provider_error"560 public static let refused = "refused"561 public static let serverError = "server_error"562 // Transcription.563 /// `415`.564 public static let notAudio = "not_audio"565 /// `413`: more than 25 MB.566 public static let tooLarge = "too_large"567 /// `503`.568 public static let queueUnavailable = "queue_unavailable"569 // Smart database properties.570 public static let notAIProperty = "not_ai_property"571 /// `400`: a malformed id on the routes of the AI workstream.572 public static let badID = "bad_id"573 }574575 /// The route does not exist on this server: `501`, or a `404` that is not a JSON error of the API (a server576 /// without the feature answers its HTML "not found" page). A `404` with a JSON body is a missing object instead.577 public var isRouteMissing: Bool {578 guard case .http(let status, let code, _, let body) = self else { return false }579 if status == 501 { return true }580 guard status == 404 || status == 405, code == nil else { return false }581 return (try? JSONValue(parsing: body))?["error"] == nil582 }583584 /// The server has no usable model or provider for the request (`503 no_model | not_configured`).585 public var isAIUnavailable: Bool { status == 503 && (code == Code.noModel || code == Code.notConfigured) }586}587