SPB Git

Repository Public

Approvals.swift 11.9 KB 242 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraAgents/Sources/Approvals.swift10// Module           : Packages11// 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 AstraCore9091/// What the person is asked before a tool touches their data or the network. Everything shown is already redacted.92public struct ApprovalRequest: Sendable, Hashable, Codable, Identifiable {93    /// The tool call id.94    public var id: String95    public var runID: UUID96    public var toolName: String97    public var risk: ToolRisk98    /// One readable line: what will happen.99    public var summary: String100    /// The arguments, with secret-looking fields masked and long values shortened.101    public var arguments: JSONValue102    /// What an "allow for this run" answer would cover beyond this call (the host for `web_fetch`); nil = every call of this tool.103    public var scope: String?104    /// Reasons to look twice: possible exfiltration in a URL, a call that follows untrusted content with suspicious instructions.105    public var warnings: [String]106107    public init(id: String, runID: UUID, toolName: String, risk: ToolRisk, summary: String, arguments: JSONValue, scope: String? = nil, warnings: [String] = []) {108        self.id = id; self.runID = runID; self.toolName = toolName; self.risk = risk; self.summary = summary109        self.arguments = arguments; self.scope = scope; self.warnings = warnings110    }111112    /// Label for the "allow for this run" button.113    public var allowForRunLabel: String { scope.map { "Allow \(toolName) for \($0) during this run" } ?? "Allow \(toolName) during this run" }114}115116public enum ApprovalDecision: Sendable, Hashable, Codable {117    case allowOnce118    /// Covers later calls of the same tool in this run and, for scoped tools, the same scope only (same host for `web_fetch`).119    case allowForRun120    case deny(reason: String?)121122    public var isAllowed: Bool { if case .deny = self { return false }; return true }123}124125/// Implemented by the UI layer: present the request, suspend until the person answers.126/// If the run is cancelled while waiting, the runner stops waiting; the handler's own task is cancelled and its answer is ignored.127public protocol ApprovalHandler: Sendable {128    func requestApproval(_ request: ApprovalRequest) async -> ApprovalDecision129}130131/// Wraps a closure; also the default "deny everything" handler for unattended contexts.132public struct ClosureApprovalHandler: ApprovalHandler {133    private let body: @Sendable (ApprovalRequest) async -> ApprovalDecision134    public init(_ body: @escaping @Sendable (ApprovalRequest) async -> ApprovalDecision) { self.body = body }135    public func requestApproval(_ request: ApprovalRequest) async -> ApprovalDecision { await body(request) }136    public static let denyAll = ClosureApprovalHandler { _ in .deny(reason: "Approvals are not available in this context.") }137}138139/// The grants accumulated during one run. Part of the checkpoint, so a resumed run does not ask again for what was allowed for the run.140public struct ApprovalGrants: Sendable, Hashable, Codable {141    /// Keys `tool` or `tool|scope` allowed for the rest of the run.142    public private(set) var forRun: Set<String>143    /// Read-only tools already approved once in this run.144    public private(set) var readsApproved: Set<String>145146    public init(forRun: Set<String> = [], readsApproved: Set<String> = []) { self.forRun = forRun; self.readsApproved = readsApproved }147148    public static func key(tool: String, scope: String?) -> String { scope.map { tool + "|" + $0.lowercased() } ?? tool }149150    /// The whole approval policy, in code:151    /// safe → never; reads user data → once per run and per tool; writes, sends externally, destructive → every call unless an152    /// "allow for run" grant covers this tool (and this scope).153    public func needsApproval(tool: String, risk: ToolRisk, scope: String?) -> Bool {154        switch risk {155        case .safe: false156        case .readsUserData: !(readsApproved.contains(tool) || forRun.contains(Self.key(tool: tool, scope: scope)))157        case .writesUserData, .sendsDataExternally, .destructive: !forRun.contains(Self.key(tool: tool, scope: scope))158        }159    }160161    public mutating func record(_ decision: ApprovalDecision, tool: String, risk: ToolRisk, scope: String?) {162        switch decision {163        case .deny: break164        case .allowOnce: if risk == .readsUserData { readsApproved.insert(tool) }165        case .allowForRun:166            forRun.insert(Self.key(tool: tool, scope: scope))167            if risk == .readsUserData { readsApproved.insert(tool) }168        }169    }170171    public mutating func grant(tool: String, scope: String?) { forRun.insert(Self.key(tool: tool, scope: scope)) }172173    /// Drops grants for tools that are no longer allowed (a checkpoint resumed under a narrower profile).174    public func restricted(to tools: [String]) -> ApprovalGrants {175        let allowed = Set(tools)176        return ApprovalGrants(forRun: forRun.filter { allowed.contains(String($0.split(separator: "|").first ?? "")) },177                              readsApproved: readsApproved.intersection(allowed))178    }179}180181/// Redaction applied to everything that reaches the timeline, an approval sheet or a log.182public enum AuditRedactor {183    public static let mask = "•••"184    static let sensitiveWords: Set<String> = ["key", "apikey", "token", "password", "passwd", "pwd", "secret", "authorization", "auth", "credential",185                                              "credentials", "cookie", "bearer", "passphrase", "signature", "session"]186187    /// True for `api_key`, `accessToken`, `Authorization`, `password`… but not for `keyword` or `author`.188    public static func isSensitive(fieldName: String) -> Bool {189        var words: [String] = []190        var current = ""191        for scalar in fieldName.unicodeScalars {192            let c = Character(scalar)193            if !(c.isLetter || c.isNumber) { if !current.isEmpty { words.append(current) }; current = ""; continue }194            if c.isUppercase, let last = current.last, last.isLowercase { words.append(current); current = "" }195            current.append(c)196        }197        if !current.isEmpty { words.append(current) }198        let lowered = words.map { $0.lowercased() }199        return lowered.contains(where: sensitiveWords.contains) || sensitiveWords.contains(lowered.joined())200    }201202    /// `name=value` and `name: value` pairs whose name is a secret-looking word (`token=…`, `session_key: …`), which the203    /// credential patterns of `Redactor` do not all cover.204    private static let assignment = try? NSRegularExpression(205        pattern: #"(?i)(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_\-])*(?:token|key|apikey|passwd|pwd|passphrase|auth|authorization|cookie|credentials?)["']?\s*[:=]\s*["']?)[^\s"',;}&]{6,}"#)206207    public static func redact(_ text: String) -> String {208        let clean = Redactor.redact(text)209        guard let assignment else { return clean }210        return assignment.stringByReplacingMatches(in: clean, range: NSRange(clean.startIndex..., in: clean), withTemplate: "$1" + mask)211    }212213    /// Masks the values of secret-looking fields, redacts credential patterns inside strings and shortens long strings.214    public static func redact(_ value: JSONValue, maxStringLength: Int = 2_000) -> JSONValue {215        switch value {216        case .string(let s):217            let clean = redact(s)218            return .string(clean.count > maxStringLength ? String(clean.prefix(maxStringLength)) + "… (\(clean.count) characters)" : clean)219        case .array(let items): return .array(items.map { redact($0, maxStringLength: maxStringLength) })220        case .object(let object):221            var out: [String: JSONValue] = [:]222            for (key, child) in object {223                if isSensitive(fieldName: key), child != .null { out[key] = .string(mask) }224                else { out[key] = redact(child, maxStringLength: maxStringLength) }225            }226            return .object(out)227        default: return value228        }229    }230231    /// A readable one-line description of a call when the tool does not provide its own.232    public static func summary(toolName: String, arguments: JSONValue) -> String {233        guard case .object(let object) = redact(arguments, maxStringLength: 120), !object.isEmpty else { return "Run \(toolName)" }234        let parts = object.keys.sorted().prefix(6).map { key -> String in235            let v = object[key] ?? .null236            return "\(key): \(v.stringValue.map { $0.replacingOccurrences(of: "\n", with: " ") } ?? v.serialized())"237        }238        let line = "Run \(toolName) with " + parts.joined(separator: ", ")239        return line.count > 400 ? String(line.prefix(400)) + "…" : line240    }241}242
Files main
Menu

Theme