Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : Shared/Sources/AIEngine/AISession.swift10// Description : The SP AI pipeline as an explicit state machine (idle →11// sourcePreview → submitting → resultPreview → applied, plus12// cancelled / offline / failed), one request at a time, and13// the volatile context fingerprint that decides whether14// "Replace" is still safe.15// Module : AIEngine16// Repository : https://git.spboucher.ai/sp-keyboard17// Created : 2026-12-0118// Last Modified : 2026-12-0119//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author : Simon-Pierre Boucher25// Position : Professor of Finance26// Institution : Université du Québec en Outaouais (UQO)27// Department : Département des sciences administratives28// Organization : SP Boucher29//30// Website : https://spboucher.ai31// Git : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General : info@spboucher.ai38// Professional : contact@spboucher.ai39// Direct : simon@spboucher.ai40// Research : research@spboucher.ai41// Development : dev@spboucher.ai42// Support : support@spboucher.ai43// Security/Admin : admin@spboucher.ai44// Notifications : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification : Public71// Distribution : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License : None specified (no license file in this repository)85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Foundation93import CryptoKit9495// MARK: - Context fingerprint9697/// What the keyboard can see of the host field at one instant. Lives in memory only.98public struct TextContextSnapshot: Hashable, Sendable {99 public var before: String100 public var after: String101 public var selected: String102 /// Identity of the host field as far as the extension can tell (document identifier), if any.103 public var documentID: String104105 public init(before: String?, after: String?, selected: String?, documentID: String = "") {106 self.before = before ?? ""107 self.after = after ?? ""108 self.selected = selected ?? ""109 self.documentID = documentID110 }111}112113/// Hash of the context captured when the source was chosen. Holds no text.114public struct ContextFingerprint: Hashable, Sendable {115 let digest: String116 let origin: AISource.Origin117 let sourceLength: Int118119 public init(snapshot: TextContextSnapshot, source: AISource) {120 origin = source.origin121 sourceLength = source.text.count122 digest = Self.makeDigest(snapshot: snapshot, source: source)123 }124125 static func makeDigest(snapshot: TextContextSnapshot, source: AISource) -> String {126 // Only the parts that must be unchanged for a replacement to hit the right text.127 let tail: String128 switch source.origin {129 case .selection: tail = snapshot.selected130 case .contextBeforeCursor: tail = String(snapshot.before.suffix(source.text.count))131 case .provided: tail = ""132 }133 let material = [snapshot.documentID, source.origin.rawValue, tail, String(snapshot.after.prefix(64))].joined(separator: "\u{1F}")134 return SHA256.hash(data: Data(material.utf8)).map { String(format: "%02x", $0) }.joined()135 }136}137138/// How a result may be applied to the host field right now.139public enum ReplacementPlan: Equatable, Sendable {140 /// The selection is intact: inserting replaces it.141 case replaceSelection142 /// The source still sits immediately before the cursor: delete that many characters, then insert.143 case replaceBeforeCursor(deleteCount: Int)144 /// Context changed or the source was provided by hand: insert or copy only, nothing is deleted.145 case insertOnly146147 public var canReplace: Bool { self != .insertOnly }148}149150public enum ReplacementPlanner {151 public static func plan(fingerprint: ContextFingerprint?, source: AISource, current: TextContextSnapshot) -> ReplacementPlan {152 guard let fingerprint, fingerprint.origin == source.origin, fingerprint.sourceLength == source.text.count,153 !source.text.isEmpty else { return .insertOnly }154 switch source.origin {155 case .provided:156 return .insertOnly157 case .selection:158 guard current.selected == source.text else { return .insertOnly }159 case .contextBeforeCursor:160 guard current.selected.isEmpty, current.before.hasSuffix(source.text) else { return .insertOnly }161 }162 guard ContextFingerprint.makeDigest(snapshot: current, source: source) == fingerprint.digest else { return .insertOnly }163 return source.origin == .selection ? .replaceSelection : .replaceBeforeCursor(deleteCount: source.text.count)164 }165166 /// The bounded text immediately before the cursor that SP AI proposes as a source: the current paragraph,167 /// capped. It never walks the document to collect more than the proxy hands over at once.168 public static func boundedContext(_ before: String?, limit: Int = 1200) -> String {169 guard let before, !before.isEmpty else { return "" }170 var text = Substring(before)171 if let lastBreak = text.lastIndex(of: "\n"), text.index(after: lastBreak) < text.endIndex {172 let paragraph = text[text.index(after: lastBreak)...]173 if !paragraph.trimmingCharacters(in: .whitespaces).isEmpty { text = paragraph }174 }175 if text.count > limit { text = text.suffix(limit) }176 return String(text)177 }178}179180// MARK: - Pipeline181182public enum AISessionState: Equatable, Sendable {183 case idle184 case sourcePreview(AISource)185 case submitting(AISource, AIAction)186 case resultPreview(AISource, AIAction, AIResult)187 case applied188 case cancelled(AISource)189 case offline(AISource)190 case failed(AISource?, AIError)191192 public var isSubmitting: Bool {193 if case .submitting = self { return true }194 return false195 }196197 public var source: AISource? {198 switch self {199 case .sourcePreview(let source), .submitting(let source, _), .resultPreview(let source, _, _),200 .cancelled(let source), .offline(let source):201 source202 case .failed(let source, _): source203 case .idle, .applied: nil204 }205 }206}207208/// Drives one SP AI panel. Nothing is ever sent without an explicit `submit`.209@MainActor210public final class AISession {211 public private(set) var state: AISessionState = .idle {212 didSet { if oldValue != state { onChange?(state) } }213 }214 public var onChange: ((AISessionState) -> Void)?215 /// Called once per completed request with token counts only.216 public var onUsage: ((AIUsage?) -> Void)?217 public private(set) var fingerprint: ContextFingerprint?218219 private let service: AIService220 private var task: Task<Void, Never>?221 private var generation = 0222 private var lastAction: AIAction?223224 public init(service: AIService) {225 self.service = service226 }227228 /// Step 1: show the user exactly what would be transmitted.229 public func preview(_ source: AISource, context: TextContextSnapshot) {230 cancelRunningTask()231 let trimmed = AISource(text: source.text, origin: source.origin)232 fingerprint = ContextFingerprint(snapshot: context, source: trimmed)233 state = .sourcePreview(trimmed)234 }235236 /// Replaces the previewed text (the user edited or pasted it in the panel): replacement is then disabled.237 public func updateProvidedSource(_ text: String) {238 guard !state.isSubmitting else { return }239 let source = AISource(text: text, origin: .provided)240 fingerprint = nil241 state = .sourcePreview(source)242 }243244 /// Step 2: explicit send. Refused while another request is running.245 public func submit(_ action: AIAction, settings: AISettings) {246 guard !state.isSubmitting else { return }247 guard let source = state.source else {248 state = .failed(nil, .emptySource)249 return250 }251 let text = source.text.trimmingCharacters(in: .whitespacesAndNewlines)252 guard !text.isEmpty else {253 state = .failed(source, .emptySource)254 return255 }256 guard source.text.count <= AISettings.maxSourceCharacters else {257 state = .failed(source, .sourceTooLong(limit: AISettings.maxSourceCharacters))258 return259 }260 guard let model = settings.selectedModel else {261 state = .failed(source, .noModelSelected)262 return263 }264 lastAction = action265 generation += 1266 let current = generation267 state = .submitting(source, action)268 let prompt = AIPromptBuilder.build(action: action, source: source.text, outputLanguage: settings.outputLanguage)269 let request = AIRequest(model: model, prompt: prompt, maxOutputTokens: settings.maxOutputTokens)270 let service = service271 task = Task { [weak self] in272 let outcome: Result<AIResult, AIError>273 do {274 outcome = .success(try await service.complete(request))275 } catch let error as AIError {276 outcome = .failure(error)277 } catch is CancellationError {278 outcome = .failure(.cancelled)279 } catch {280 outcome = .failure(.malformedResponse)281 }282 self?.finish(outcome, generation: current, source: source, action: action)283 }284 }285286 private func finish(_ outcome: Result<AIResult, AIError>, generation current: Int, source: AISource, action: AIAction) {287 guard current == generation, state.isSubmitting else { return } // a cancelled or superseded request288 task = nil289 switch outcome {290 case .success(let result):291 onUsage?(result.usage)292 state = .resultPreview(source, action, result)293 case .failure(.cancelled):294 state = .cancelled(source)295 case .failure(.offline):296 onUsage?(nil)297 state = .offline(source)298 case .failure(let error):299 onUsage?(nil)300 state = .failed(source, error)301 }302 }303304 /// Explicit regeneration of the last action. Never automatic.305 public func regenerate(settings: AISettings) {306 guard !state.isSubmitting, let action = lastAction, let source = state.source else { return }307 state = .sourcePreview(source)308 submit(action, settings: settings)309 }310311 /// Cancels the local task. The server may already be processing the request.312 public func cancel() {313 guard case .submitting(let source, _) = state else { return }314 cancelRunningTask()315 state = .cancelled(source)316 }317318 /// Back to the source preview (after a failure, a cancellation or to pick another action).319 public func backToSource() {320 guard !state.isSubmitting, let source = state.source else { return }321 state = .sourcePreview(source)322 }323324 /// The user edited the result in the panel before applying it.325 public func editResult(_ text: String) {326 guard case .resultPreview(let source, let action, var result) = state else { return }327 result.text = text328 state = .resultPreview(source, action, result)329 }330331 public func markApplied() {332 guard case .resultPreview = state else { return }333 state = .applied334 }335336 /// Keyboard dismissed or panel closed: drop everything volatile.337 public func reset() {338 cancelRunningTask()339 fingerprint = nil340 lastAction = nil341 state = .idle342 }343344 private func cancelRunningTask() {345 generation += 1346 task?.cancel()347 task = nil348 }349}350