Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Docs9// File : Packages/ORIXDocsAI/Sources/DocAgent/Support.swift10// Description : Shared plumbing of the agent layer: the bridge between the11// two JSON value types (command engine and model runtime),12// content hashing, and a wait that can be abandoned on a13// deadline or on cancellation.14// Module : DocAgent15// Repository : https://git.spboucher.ai/orix-docs16// Created : 2026-11-2217// Last Modified : 2026-11-2218//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation92import CryptoKit93import Synchronization94import AstraCore95import DocCommands9697/// JSON as the command engine speaks it (integers and fractions kept apart).98public typealias DocJSON = DocCommands.JSONValue99/// JSON as the model runtime speaks it (one number type).100public typealias ModelJSON = AstraCore.JSONValue101102public enum JSONBridge {103 /// Model arguments → command arguments. Whole numbers become integers, so identifiers and counts validate as such.104 public static func doc(_ value: ModelJSON) -> DocJSON {105 switch value {106 case .null: return .null107 case .bool(let b): return .bool(b)108 case .number(let n):109 if n.isFinite, n == n.rounded(), abs(n) < 9e15 { return .int(Int(n)) }110 return .double(n.isFinite ? n : 0)111 case .string(let s): return .string(s)112 case .array(let a): return .array(a.map(doc))113 case .object(let o): return .object(o.mapValues(doc))114 }115 }116117 /// Command JSON (schemas, outputs) → model JSON.118 public static func model(_ value: DocJSON) -> ModelJSON {119 switch value {120 case .null: return .null121 case .bool(let b): return .bool(b)122 case .int(let i): return .number(Double(i))123 case .double(let d): return .number(d)124 case .string(let s): return .string(s)125 case .array(let a): return .array(a.map(model))126 case .object(let o): return .object(o.mapValues(model))127 }128 }129}130131enum ContentHash {132 /// Stable hash of a text (first 16 hex characters of SHA-256): cache key of summaries and fingerprint of what the model was shown.133 static func of(_ text: String) -> String {134 SHA256.hash(data: Data(text.utf8)).prefix(8).map { String(format: "%02x", $0) }.joined()135 }136}137138/// How a bounded wait ended.139enum Timed<T: Sendable>: Sendable {140 case value(T)141 case timedOut142 case cancelled143}144145/// Resumes one continuation exactly once, whichever of the competing sources (the work, the timer, the cancellation) arrives first.146private final class ResumeOnce<T: Sendable>: Sendable {147 private struct State { var continuation: CheckedContinuation<T, Never>?; var early: T?; var done = false }148 private let state = Mutex(State())149150 func install(_ continuation: CheckedContinuation<T, Never>) {151 let early: T? = state.withLock { s in152 if let e = s.early { s.early = nil; return e }153 s.continuation = continuation154 return nil155 }156 if let early { continuation.resume(returning: early) }157 }158159 func resume(_ value: T) {160 let continuation: CheckedContinuation<T, Never>? = state.withLock { s in161 guard !s.done else { return nil }162 s.done = true163 if let c = s.continuation { s.continuation = nil; return c }164 s.early = value165 return nil166 }167 continuation?.resume(returning: value)168 }169}170171enum Abandonable {172 /// Runs `operation` and waits for it at most `timeout` seconds, or until the calling task is cancelled. When the wait ends early the173 /// operation's task is cancelled and no longer waited for: a tool or an approver that ignores cancellation cannot hold a run hostage.174 static func run<T: Sendable>(timeout: TimeInterval?, _ operation: @escaping @Sendable () async -> T) async -> Timed<T> {175 let gate = ResumeOnce<Timed<T>>()176 let work = Task { gate.resume(.value(await operation())) }177 let timer: Task<Void, Never>? = timeout.map { seconds in178 Task {179 try? await Task.sleep(nanoseconds: UInt64(max(0, min(seconds, 86_400)) * 1_000_000_000))180 if !Task.isCancelled { gate.resume(.timedOut) }181 }182 }183 let result = await withTaskCancellationHandler {184 await withCheckedContinuation { gate.install($0) }185 } onCancel: {186 gate.resume(.cancelled)187 }188 timer?.cancel()189 if case .value = result {} else { work.cancel() }190 return result191 }192}193194/// A value shared between tasks behind a lock. A class (and not a bare `Mutex`) so that escaping closures can capture it.195final class Locked<Value: Sendable>: Sendable {196 private let mutex: Mutex<Value>197 init(_ value: Value) { mutex = Mutex(value) }198 func withLock<R: Sendable>(_ body: @Sendable (inout Value) -> R) -> R { mutex.withLock { body(&$0) } }199 var value: Value { mutex.withLock { $0 } }200}201202/// A flag several tasks can read and one can raise: the cancellation switch of a run and of a whole agent tree.203public final class CancellationFlag: Sendable {204 private let raised = Mutex(false)205 public init() {}206 public func cancel() { raised.withLock { $0 = true } }207 public var isCancelled: Bool { raised.withLock { $0 } }208}209210extension String {211 /// The text cut to `limit` characters with a visible mark.212 func clipped(_ limit: Int) -> String { count > limit ? String(prefix(limit)) + "…" : self }213}214