Repository Public MIT
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 /// False when the autonomy profile does not allow "allow for this run" for this call (or the call carries a warning).105 public var offersRunGrant: Bool = true106 /// The declared permission level of the tool.107 public var level: PermissionLevel?108 /// The sub-agent that asks, when the call comes from one ("Research", "Verification"…).109 public var requestedBy: String?110 /// Reasons to look twice: possible exfiltration in a URL, a call that follows untrusted content with suspicious instructions.111 public var warnings: [String]112113 public init(id: String, runID: UUID, toolName: String, risk: ToolRisk, summary: String, arguments: JSONValue, scope: String? = nil, warnings: [String] = []) {114 self.id = id; self.runID = runID; self.toolName = toolName; self.risk = risk; self.summary = summary115 self.arguments = arguments; self.scope = scope; self.warnings = warnings116 }117118 public init(from decoder: Decoder) throws {119 let c = try decoder.container(keyedBy: CodingKeys.self)120 id = try c.decode(String.self, forKey: .id); runID = try c.decode(UUID.self, forKey: .runID)121 toolName = try c.decode(String.self, forKey: .toolName); risk = try c.decode(ToolRisk.self, forKey: .risk)122 summary = try c.decode(String.self, forKey: .summary); arguments = try c.decode(JSONValue.self, forKey: .arguments)123 scope = try c.decodeIfPresent(String.self, forKey: .scope); warnings = try c.decodeIfPresent([String].self, forKey: .warnings) ?? []124 offersRunGrant = try c.decodeIfPresent(Bool.self, forKey: .offersRunGrant) ?? true125 level = try c.decodeIfPresent(PermissionLevel.self, forKey: .level)126 requestedBy = try c.decodeIfPresent(String.self, forKey: .requestedBy)127 }128129 /// Label for the "allow for this run" button.130 public var allowForRunLabel: String { scope.map { "Allow \(toolName) for \($0) during this run" } ?? "Allow \(toolName) during this run" }131}132133public enum ApprovalDecision: Sendable, Hashable, Codable {134 case allowOnce135 /// Covers later calls of the same tool in this run and, for scoped tools, the same scope only (same host for `web_fetch`).136 case allowForRun137 case deny(reason: String?)138139 public var isAllowed: Bool { if case .deny = self { return false }; return true }140}141142/// Implemented by the UI layer: present the request, suspend until the person answers.143/// If the run is cancelled while waiting, the runner stops waiting; the handler's own task is cancelled and its answer is ignored.144public protocol ApprovalHandler: Sendable {145 func requestApproval(_ request: ApprovalRequest) async -> ApprovalDecision146}147148/// Wraps a closure; also the default "deny everything" handler for unattended contexts.149public struct ClosureApprovalHandler: ApprovalHandler {150 private let body: @Sendable (ApprovalRequest) async -> ApprovalDecision151 public init(_ body: @escaping @Sendable (ApprovalRequest) async -> ApprovalDecision) { self.body = body }152 public func requestApproval(_ request: ApprovalRequest) async -> ApprovalDecision { await body(request) }153 public static let denyAll = ClosureApprovalHandler { _ in .deny(reason: "Approvals are not available in this context.") }154}155156/// 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.157public struct ApprovalGrants: Sendable, Hashable, Codable {158 /// Keys `tool` or `tool|scope` allowed for the rest of the run.159 public private(set) var forRun: Set<String>160 /// Read-only tools already approved once in this run.161 public private(set) var readsApproved: Set<String>162163 public init(forRun: Set<String> = [], readsApproved: Set<String> = []) { self.forRun = forRun; self.readsApproved = readsApproved }164165 public static func key(tool: String, scope: String?) -> String { scope.map { tool + "|" + $0.lowercased() } ?? tool }166167 /// The whole approval policy, in code:168 /// safe → never; reads user data → once per run and per tool; writes, sends externally, destructive → every call unless an169 /// "allow for run" grant covers this tool (and this scope).170 public func needsApproval(tool: String, risk: ToolRisk, scope: String?) -> Bool {171 switch risk {172 case .safe: false173 case .readsUserData: !(readsApproved.contains(tool) || forRun.contains(Self.key(tool: tool, scope: scope)))174 case .writesUserData, .sendsDataExternally, .destructive: !forRun.contains(Self.key(tool: tool, scope: scope))175 }176 }177178 public mutating func record(_ decision: ApprovalDecision, tool: String, risk: ToolRisk, scope: String?) {179 switch decision {180 case .deny: break181 case .allowOnce: if risk == .readsUserData { readsApproved.insert(tool) }182 case .allowForRun:183 forRun.insert(Self.key(tool: tool, scope: scope))184 if risk == .readsUserData { readsApproved.insert(tool) }185 }186 }187188 public mutating func grant(tool: String, scope: String?) { forRun.insert(Self.key(tool: tool, scope: scope)) }189190 /// Records the first approval of a "once per run" rule: it covers this tool, and for scoped tools this scope only.191 public mutating func approveOnce(tool: String, scope: String?) { readsApproved.insert(Self.key(tool: tool, scope: scope)) }192193 /// Adds another run's grants (a sub-agent's answers count for its parent and the other way round).194 public mutating func merge(_ other: ApprovalGrants) { forRun.formUnion(other.forRun); readsApproved.formUnion(other.readsApproved) }195196 /// Drops grants for tools that are no longer allowed (a checkpoint resumed under a narrower profile).197 public func restricted(to tools: [String]) -> ApprovalGrants {198 let allowed = Set(tools)199 func tool(_ key: String) -> String { String(key.split(separator: "|").first ?? "") }200 return ApprovalGrants(forRun: forRun.filter { allowed.contains(tool($0)) }, readsApproved: readsApproved.filter { allowed.contains(tool($0)) })201 }202}203204/// Redaction applied to everything that reaches the timeline, an approval sheet or a log.205public enum AuditRedactor {206 public static let mask = "•••"207 static let sensitiveWords: Set<String> = ["key", "apikey", "token", "password", "passwd", "pwd", "secret", "authorization", "auth", "credential",208 "credentials", "cookie", "bearer", "passphrase", "signature", "session"]209210 /// True for `api_key`, `accessToken`, `Authorization`, `password`… but not for `keyword` or `author`.211 public static func isSensitive(fieldName: String) -> Bool {212 var words: [String] = []213 var current = ""214 for scalar in fieldName.unicodeScalars {215 let c = Character(scalar)216 if !(c.isLetter || c.isNumber) { if !current.isEmpty { words.append(current) }; current = ""; continue }217 if c.isUppercase, let last = current.last, last.isLowercase { words.append(current); current = "" }218 current.append(c)219 }220 if !current.isEmpty { words.append(current) }221 let lowered = words.map { $0.lowercased() }222 return lowered.contains(where: sensitiveWords.contains) || sensitiveWords.contains(lowered.joined())223 }224225 /// `name=value` and `name: value` pairs whose name is a secret-looking word (`token=…`, `session_key: …`), which the226 /// credential patterns of `Redactor` do not all cover.227 private static let assignment = try? NSRegularExpression(228 pattern: #"(?i)(?<![A-Za-z0-9])((?:[A-Za-z0-9]+[_\-])*(?:token|key|apikey|passwd|pwd|passphrase|auth|authorization|cookie|credentials?)["']?\s*[:=]\s*["']?)[^\s"',;}&]{6,}"#)229230 public static func redact(_ text: String) -> String {231 let clean = Redactor.redact(text)232 guard let assignment else { return clean }233 return assignment.stringByReplacingMatches(in: clean, range: NSRange(clean.startIndex..., in: clean), withTemplate: "$1" + mask)234 }235236 /// Masks the values of secret-looking fields, redacts credential patterns inside strings and shortens long strings.237 public static func redact(_ value: JSONValue, maxStringLength: Int = 2_000) -> JSONValue {238 switch value {239 case .string(let s):240 let clean = redact(s)241 return .string(clean.count > maxStringLength ? String(clean.prefix(maxStringLength)) + "… (\(clean.count) characters)" : clean)242 case .array(let items): return .array(items.map { redact($0, maxStringLength: maxStringLength) })243 case .object(let object):244 var out: [String: JSONValue] = [:]245 for (key, child) in object {246 if isSensitive(fieldName: key), child != .null { out[key] = .string(mask) }247 else { out[key] = redact(child, maxStringLength: maxStringLength) }248 }249 return .object(out)250 default: return value251 }252 }253254 /// A readable one-line description of a call when the tool does not provide its own.255 public static func summary(toolName: String, arguments: JSONValue) -> String {256 guard case .object(let object) = redact(arguments, maxStringLength: 120), !object.isEmpty else { return "Run \(toolName)" }257 let parts = object.keys.sorted().prefix(6).map { key -> String in258 let v = object[key] ?? .null259 return "\(key): \(v.stringValue.map { $0.replacingOccurrences(of: "\n", with: " ") } ?? v.serialized())"260 }261 let line = "Run \(toolName) with " + parts.joined(separator: ", ")262 return line.count > 400 ? String(line.prefix(400)) + "…" : line263 }264}265