Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraUI/Sources/Agents/AgentServices.swift10// Module : Agents11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2113// Last Modified : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import Observation90import SwiftUI91import UniformTypeIdentifiers92import AstraCore93import AstraAgents94import AstraPersistence95#if canImport(PDFKit)96import PDFKit97#endif9899// MARK: - Documents100101/// `document_search` over the store's on-device full-text index: the same query the Knowledge screen runs.102struct AgentDocumentSearch: DocumentSearching {103 let store: AstraStore104105 func search(_ query: String, limit: Int) async throws -> [DocumentHit] {106 try await store.searchChunks(query, limit: limit).map(Self.hit)107 }108109 static func hit(_ hit: ChunkHit) -> DocumentHit {110 DocumentHit(id: hit.chunk.id, title: hit.documentName, text: hit.chunk.text, location: "passage \(hit.chunk.ordinal + 1)", score: hit.score)111 }112}113114// MARK: - Conversations and memory115116/// Earlier conversations, through the store's full-text search. Excerpts only: the best matching message of each hit.117struct AgentConversationSearch: ConversationSearching {118 let store: AstraStore119120 func search(_ query: String, limit: Int) async throws -> [ConversationHit] {121 try await store.searchConversations(query, limit: limit).map { hit in122 let title = hit.conversation.title.isEmpty ? "Untitled conversation" : hit.conversation.title123 return ConversationHit(conversationTitle: title, date: hit.conversation.updatedAt, speaker: hit.matchedTitle ? "Title" : "Conversation",124 excerpt: hit.snippet.isEmpty ? title : hit.snippet)125 }126 }127}128129/// Saved memories. A memory proposed by an agent is stored with that origin, after the person approved its exact text.130struct AgentMemoryStore: MemoryStoring {131 let store: AstraStore132133 func memories(matching query: String?, limit: Int) async throws -> [MemoryItem] {134 try await store.searchMemories(query, limit: limit).map { MemoryItem(text: $0.text, savedAt: $0.createdAt, origin: $0.origin.label) }135 }136137 func save(_ text: String, runID: UUID) async throws {138 _ = try await store.addMemory(text: text, origin: .agent)139 }140}141142// MARK: - Web search143144/// Web search through Tavily, with the person's own key (Keychain account `search.tavily`). The query is the only thing sent.145struct TavilySearch: WebSearching {146 static let name = "Tavily"147 static let host = "api.tavily.com"148 static let account = "search.tavily"149 var serviceName: String { Self.name }150 var serviceHost: String { Self.host }151 let transport: any HTTPTransport152 let key: @Sendable () throws -> String?153154 func search(_ query: String, limit: Int) async throws -> [WebSearchResult] {155 guard let key = try key()?.trimmingCharacters(in: .whitespacesAndNewlines), !key.isEmpty else {156 throw ToolError("Web search has no key. Add a Tavily key in the agent's settings.")157 }158 var request = URLRequest(url: URL(string: "https://\(Self.host)/search")!)159 request.httpMethod = "POST"160 request.timeoutInterval = 20161 request.setValue("application/json", forHTTPHeaderField: "Content-Type")162 request.setValue("Bearer " + key, forHTTPHeaderField: "Authorization")163 let body: JSONValue = ["query": .string(query), "max_results": .number(Double(limit)), "search_depth": "basic", "include_answer": false]164 request.httpBody = body.data165 let data: Data, response: HTTPURLResponse166 do { (data, response) = try await transport.send(request) }167 catch { throw ToolError("The search service could not be reached: \(Redactor.redact(AstraError.wrap(error).message).replacingOccurrences(of: key, with: "•••"))", isTransient: true) }168 guard (200..<300).contains(response.statusCode) else {169 switch response.statusCode {170 case 401, 403: throw ToolError("The search service rejected the key. Check the Tavily key in the agent's settings.")171 case 429: throw ToolError("The search service is rate limiting this key. Try again later or search less often.")172 case 500...: throw ToolError("The search service answered HTTP \(response.statusCode).", isTransient: true)173 default: throw ToolError("The search service answered HTTP \(response.statusCode).")174 }175 }176 guard let json = JSONValue.parse(data), let results = json["results"]?.arrayValue else { throw ToolError("The search service returned an unreadable answer.") }177 return results.compactMap { item in178 guard let url = item["url"]?.stringValue, !url.isEmpty else { return nil }179 return WebSearchResult(title: item["title"]?.stringValue ?? url, url: url, snippet: item["content"]?.stringValue ?? "")180 }181 }182}183184// MARK: - Files185186/// The text handed to the system exporter when an agent proposes a file.187struct AgentTextDocument: FileDocument {188 static let readableContentTypes: [UTType] = [.data]189 static let writableContentTypes: [UTType] = [.data]190 var data: Data191192 init(text: String) { data = Data(text.utf8) }193 init(configuration: ReadConfiguration) throws { data = configuration.file.regularFileContents ?? Data() }194 func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { FileWrapper(regularFileWithContents: data) }195}196197/// Files of one run. Reads go only to items the person picked in the system importer, whose security-scoped access is held198/// until the run ends; writes go only through the system exporter, where the person chooses the destination.199@MainActor @Observable final class AgentFileAccess: FileAccessing {200 struct Granted: Identifiable, Hashable, Sendable {201 let id: String202 let name: String203 let byteCount: Int?204 let kind: String?205 let url: URL206 let scoped: Bool207 }208209 struct ExportProposal: Identifiable {210 let id = UUID()211 let fileName: String212 let document: AgentTextDocument213 }214215 static let maxItems = 20216217 private(set) var granted: [Granted] = []218 /// The file waiting in the system exporter, if any.219 private(set) var export: ExportProposal?220 var isExporterPresented = false221 @ObservationIgnored private var exportContinuation: CheckedContinuation<FileWriteResult, Error>?222 @ObservationIgnored private var counter = 0223224 /// Starts access to the picked files and lists them for the run. Returns one message per file that could not be shared.225 func grant(_ urls: [URL]) async -> [String] {226 var problems: [String] = []227 for url in urls {228 if granted.contains(where: { $0.url.standardizedFileURL == url.standardizedFileURL }) { continue }229 guard granted.count < Self.maxItems else {230 problems.append("Only \(Self.maxItems) files can be shared with one run.")231 break232 }233 let facts = await Task.detached(priority: .userInitiated) { () -> (scoped: Bool, regular: Bool, size: Int?, kind: String?) in234 let scoped = url.startAccessingSecurityScopedResource()235 let values = try? url.resourceValues(forKeys: [.fileSizeKey, .contentTypeKey, .isRegularFileKey])236 let type = values?.contentType ?? UTType(filenameExtension: url.pathExtension)237 return (scoped, values?.isRegularFile ?? true, values?.fileSize, type?.localizedDescription)238 }.value239 guard facts.regular else {240 if facts.scoped { url.stopAccessingSecurityScopedResource() }241 problems.append("“\(url.lastPathComponent)” is a folder. Share individual files.")242 continue243 }244 counter += 1245 granted.append(Granted(id: "file-\(counter)", name: url.lastPathComponent, byteCount: facts.size, kind: facts.kind, url: url, scoped: facts.scoped))246 }247 return problems248 }249250 func revoke(_ id: String) {251 guard let index = granted.firstIndex(where: { $0.id == id }) else { return }252 let item = granted.remove(at: index)253 if item.scoped { item.url.stopAccessingSecurityScopedResource() }254 }255256 /// Ends every access held for the run and closes a pending save dialog as cancelled.257 func releaseAll() {258 for item in granted where item.scoped { item.url.stopAccessingSecurityScopedResource() }259 granted = []260 finishExport(.success(.cancelled))261 }262263 // MARK: FileAccessing264265 func grantedItems() async throws -> [GrantedItem] {266 granted.map { GrantedItem(id: $0.id, name: $0.name, byteCount: $0.byteCount, kind: $0.kind) }267 }268269 func readText(itemID: String, maxBytes: Int) async throws -> FileText {270 guard let item = granted.first(where: { $0.id == itemID }) else { throw ToolError("That file is not shared with this run.") }271 let url = item.url, name = item.name272 return try await Task.detached(priority: .userInitiated) { try AgentFileReader.read(url: url, name: name, maxBytes: maxBytes) }.value273 }274275 func proposeWrite(fileName: String, text: String) async throws -> FileWriteResult {276 finishExport(.success(.cancelled))277 // The approval sheet is still closing when the tool starts; a second presentation would be dropped.278 try await Task.sleep(nanoseconds: 650_000_000)279 return try await withTaskCancellationHandler {280 try await withCheckedThrowingContinuation { continuation in281 if Task.isCancelled { continuation.resume(returning: .cancelled); return }282 exportContinuation = continuation283 export = ExportProposal(fileName: fileName, document: AgentTextDocument(text: text))284 isExporterPresented = true285 }286 } onCancel: {287 Task { @MainActor in self.finishExport(.success(.cancelled)) }288 }289 }290291 /// Called by the exporter's completion and cancellation handlers, and when the run stops.292 func finishExport(_ result: Result<FileWriteResult, Error>) {293 guard let continuation = exportContinuation else { return }294 exportContinuation = nil295 export = nil296 isExporterPresented = false297 continuation.resume(with: result)298 }299}300301/// Bounded reads of a granted file, coordinated with other processes that may be writing it.302enum AgentFileReader {303 static let maxPDFBytes = 20 * 1024 * 1024304305 static func read(url: URL, name: String, maxBytes: Int) throws -> FileText {306 var outcome: Result<FileText, Error> = .failure(ToolError("“\(name)” could not be read."))307 var coordinationError: NSError?308 NSFileCoordinator().coordinate(readingItemAt: url, options: [.withoutChanges], error: &coordinationError) { readable in309 outcome = Result { try readCoordinated(url: readable, name: name, maxBytes: maxBytes) }310 }311 if coordinationError != nil { throw ToolError("“\(name)” could not be opened. It may have been moved or deleted.") }312 return try outcome.get()313 }314315 private static func readCoordinated(url: URL, name: String, maxBytes: Int) throws -> FileText {316 let cap = max(1, maxBytes)317 let type = (try? url.resourceValues(forKeys: [.contentTypeKey]))?.contentType ?? UTType(filenameExtension: url.pathExtension)318 if type?.conforms(to: .pdf) ?? false { return try readPDF(url: url, name: name, maxBytes: cap) }319 if let type, type.conforms(to: .image) || type.conforms(to: .audiovisualContent) || type.conforms(to: .archive) {320 throw ToolError("“\(name)” is not a text file. Only text, Markdown, source files and PDFs with a text layer can be read.")321 }322 let handle: FileHandle323 do { handle = try FileHandle(forReadingFrom: url) } catch { throw ToolError("“\(name)” could not be opened.") }324 defer { try? handle.close() }325 guard var data = try? handle.read(upToCount: cap + 1) else { throw ToolError("“\(name)” could not be read.") }326 let truncated = data.count > cap327 if truncated { data = data.prefix(cap) }328 if data.prefix(4_096).contains(0) {329 throw ToolError("“\(name)” looks like a binary file. Only text, Markdown, source files and PDFs with a text layer can be read.")330 }331 return FileText(text: decode(data, cutMidCharacter: truncated), truncated: truncated)332 }333334 /// UTF-8 first; a cut at the byte cap may end inside a character, so up to three trailing bytes are dropped before falling back to Latin-1.335 static func decode(_ data: Data, cutMidCharacter: Bool) -> String {336 if let text = String(data: data, encoding: .utf8) { return text }337 if cutMidCharacter {338 for drop in 1...3 where data.count > drop {339 if let text = String(data: data.dropLast(drop), encoding: .utf8) { return text }340 }341 }342 return String(data: data, encoding: .isoLatin1) ?? String(decoding: data, as: UTF8.self)343 }344345 private static func readPDF(url: URL, name: String, maxBytes: Int) throws -> FileText {346 #if canImport(PDFKit)347 if let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize, size > maxPDFBytes {348 throw ToolError("“\(name)” is larger than 20 MB, which is more than this tool reads from a PDF.")349 }350 guard let document = PDFDocument(url: url) else { throw ToolError("“\(name)” could not be read as a PDF.") }351 if document.isLocked { throw ToolError("“\(name)” is password-protected. Remove the password in Files and share it again.") }352 var text = ""353 var bytes = 0354 var truncated = false355 for index in 0..<document.pageCount {356 guard let page = document.page(at: index)?.string, !page.isEmpty else { continue }357 let piece = page + "\n\n"358 let size = piece.utf8.count359 if bytes + size > maxBytes {360 let room = maxBytes - bytes361 if room > 0 { text += decode(Data(piece.utf8.prefix(room)), cutMidCharacter: true) }362 truncated = true363 break364 }365 text += piece366 bytes += size367 }368 guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {369 throw ToolError("“\(name)” has no text layer: it is probably a scan. This tool does not recognise text in images.")370 }371 return FileText(text: text, truncated: truncated)372 #else373 throw ToolError("PDF files cannot be read on this platform.")374 #endif375 }376}377378// MARK: - Web379380/// `web_fetch` transport. One ephemeral session per request: no cookies, no credential storage, no cache; every redirect is381/// re-validated with the tool's policy before it is followed (5 at most), resolved addresses are checked, the body stops at the byte cap.382struct AgentWebFetcher: WebFetching {383 static let maxRedirects = 5384 static let blockedAddressMessage = "This address resolves to a private or local network address, which cannot be fetched."385386 func fetch(_ request: WebFetchRequest) async throws -> WebFetchResponse {387 if let reason = request.validate(request.url) { throw ToolError(reason) }388 if let host = WebHostPolicy.normalisedHost(request.url), await AgentHostResolver.resolvesToBlockedAddress(host) {389 throw ToolError(Self.blockedAddressMessage)390 }391 try Task.checkCancellation()392393 let configuration = URLSessionConfiguration.ephemeral394 configuration.httpCookieStorage = nil395 configuration.httpShouldSetCookies = false396 configuration.httpCookieAcceptPolicy = .never397 configuration.urlCredentialStorage = nil398 configuration.urlCache = nil399 configuration.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData400 configuration.timeoutIntervalForRequest = request.timeout401 configuration.timeoutIntervalForResource = request.timeout402 configuration.waitsForConnectivity = false403 configuration.tlsMinimumSupportedProtocolVersion = .TLSv12404 configuration.httpAdditionalHeaders = ["Accept": "text/html, text/plain, application/json;q=0.9, application/xml;q=0.8, */*;q=0.1"]405406 let loader = Loader(request: request)407 let session = URLSession(configuration: configuration, delegate: loader, delegateQueue: nil)408 let task = session.dataTask(with: Self.plainGET(request.url, timeout: request.timeout))409 // The session releases its delegate once the task is over.410 defer { session.finishTasksAndInvalidate() }411 return try await withTaskCancellationHandler {412 try await withCheckedThrowingContinuation { continuation in loader.begin(continuation, task: task) }413 } onCancel: {414 task.cancel()415 }416 }417418 /// A GET that carries nothing about the person: no cookies, no credentials, no referrer, no custom identifying header.419 static func plainGET(_ url: URL, timeout: TimeInterval) -> URLRequest {420 var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: timeout)421 request.httpMethod = "GET"422 request.httpShouldHandleCookies = false423 return request424 }425426 private final class Loader: NSObject, URLSessionDataDelegate, @unchecked Sendable {427 private let request: WebFetchRequest428 private let lock = NSLock()429 private var continuation: CheckedContinuation<WebFetchResponse, Error>?430 private var body = Data()431 private var response: HTTPURLResponse?432 private var redirects = 0433 private var refusal: ToolError?434 private var truncated = false435436 init(request: WebFetchRequest) { self.request = request }437438 func begin(_ continuation: CheckedContinuation<WebFetchResponse, Error>, task: URLSessionDataTask) {439 lock.withLock { self.continuation = continuation }440 task.resume()441 }442443 private func refuse(_ message: String) {444 lock.withLock { if refusal == nil { refusal = ToolError(message) } }445 }446447 func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,448 newRequest: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) {449 guard let target = newRequest.url else {450 refuse("The page redirected without giving an address.")451 completionHandler(nil); task.cancel(); return452 }453 let count = lock.withLock { () -> Int in redirects += 1; return redirects }454 guard count <= AgentWebFetcher.maxRedirects else {455 refuse("The page redirected more than \(AgentWebFetcher.maxRedirects) times.")456 completionHandler(nil); task.cancel(); return457 }458 if let reason = request.validate(target) {459 refuse("The page redirected to an address that is not allowed. \(reason)")460 completionHandler(nil); task.cancel(); return461 }462 let timeout = request.timeout463 Task {464 if let host = WebHostPolicy.normalisedHost(target), await AgentHostResolver.resolvesToBlockedAddress(host) {465 self.refuse("The page redirected to a private or local network address.")466 completionHandler(nil); task.cancel(); return467 }468 // A fresh request: nothing from the previous hop (headers, body) travels to the next host.469 completionHandler(AgentWebFetcher.plainGET(target, timeout: timeout))470 }471 }472473 func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse,474 completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {475 lock.withLock { self.response = response as? HTTPURLResponse }476 completionHandler(.allow)477 }478479 func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {480 let full = lock.withLock { () -> Bool in481 let room = request.maxBytes - body.count482 if data.count > room {483 if room > 0 { body.append(data.prefix(room)) }484 truncated = true485 return true486 }487 body.append(data)488 return false489 }490 if full { dataTask.cancel() }491 }492493 func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {494 // A public name can resolve to a private address after the pre-flight lookup; what answered is checked here.495 for transaction in metrics.transactionMetrics where !transaction.isProxyConnection {496 if let address = transaction.remoteAddress, WebHostPolicy.isBlockedAddress(address) {497 refuse(AgentWebFetcher.blockedAddressMessage)498 }499 }500 }501502 func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {503 let (continuation, result) = lock.withLock { () -> (CheckedContinuation<WebFetchResponse, Error>?, Result<WebFetchResponse, Error>) in504 let waiting = self.continuation505 self.continuation = nil506 return (waiting, outcome(error: error))507 }508 continuation?.resume(with: result)509 }510511 /// Called with the lock held.512 private func outcome(error: Error?) -> Result<WebFetchResponse, Error> {513 if let refusal { return .failure(refusal) }514 if let error, !truncated {515 switch (error as? URLError)?.code {516 case .cancelled: return .failure(CancellationError())517 case .timedOut: return .failure(ToolError("The website took too long to answer."))518 case .notConnectedToInternet, .networkConnectionLost, .dataNotAllowed: return .failure(ToolError("This iPhone is not connected to the internet."))519 case .cannotFindHost, .dnsLookupFailed: return .failure(ToolError("That website could not be found."))520 case .secureConnectionFailed, .serverCertificateUntrusted, .serverCertificateHasBadDate, .serverCertificateHasUnknownRoot,521 .serverCertificateNotYetValid, .clientCertificateRejected, .clientCertificateRequired:522 return .failure(ToolError("A secure connection to that website could not be established."))523 case .appTransportSecurityRequiresSecureConnection: return .failure(ToolError("Only https pages can be fetched."))524 default: return .failure(ToolError("The page could not be loaded."))525 }526 }527 guard let response else { return .failure(ToolError("The website did not answer over HTTP.")) }528 let finalURL = response.url ?? request.url529 if let reason = request.validate(finalURL) { return .failure(ToolError("The page redirected to an address that is not allowed. \(reason)")) }530 return .success(WebFetchResponse(status: response.statusCode, contentType: response.value(forHTTPHeaderField: "Content-Type") ?? "",531 body: body, finalURL: finalURL, truncated: truncated))532 }533 }534}535536/// Resolves a host name off the caller's actor and reports whether any of its addresses is private, loopback or link-local.537enum AgentHostResolver {538 static func resolvesToBlockedAddress(_ host: String) async -> Bool {539 await Task.detached(priority: .userInitiated) { addresses(of: host).contains(where: WebHostPolicy.isBlockedAddress) }.value540 }541542 /// Numeric addresses of `host`; empty when the lookup fails (the request itself then reports the failure).543 static func addresses(of host: String) -> [String] {544 var hints = addrinfo()545 hints.ai_family = AF_UNSPEC546 hints.ai_socktype = SOCK_STREAM547 var list: UnsafeMutablePointer<addrinfo>?548 guard getaddrinfo(host, "443", &hints, &list) == 0, let first = list else { return [] }549 defer { freeaddrinfo(first) }550 var out: [String] = []551 var node: UnsafeMutablePointer<addrinfo>? = first552 while let current = node {553 var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))554 if getnameinfo(current.pointee.ai_addr, current.pointee.ai_addrlen, &buffer, socklen_t(buffer.count), nil, 0, NI_NUMERICHOST) == 0 {555 out.append(String(decoding: buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self))556 }557 node = current.pointee.ai_next558 }559 return out560 }561}562