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/Permissions.swift10// Module : Packages11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2213// Last Modified : 2026-11-2214//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 a tool is allowed to touch, from the person's point of view. Every tool declares exactly one level; the permission92/// engine decides from the level, the autonomy profile and what was already granted. A model cannot change any of the three.93public enum PermissionLevel: String, Sendable, Codable, Hashable, CaseIterable, Identifiable {94 /// Pure computation: no access to the person's data, the device or the network.95 case readOnly96 /// Reads data the person keeps in the app or shared with it (documents, files, conversations, memories).97 case sensitiveData98 /// Changes something on the device (saves a file, stores a memory).99 case localModification100 /// Sends a request to a website. The address travels to that site.101 case externalNetwork102 /// Changes something outside the device, or cannot be undone.103 case externalSideEffects104105 public var id: String { rawValue }106107 public var title: String {108 switch self {109 case .readOnly: "Computation only"110 case .sensitiveData: "Reads your data"111 case .localModification: "Changes data on this iPhone"112 case .externalNetwork: "Reaches a website"113 case .externalSideEffects: "Acts outside this iPhone"114 }115 }116117 /// The level of a tool from its declared risk.118 public init(risk: ToolRisk) {119 switch risk {120 case .safe: self = .readOnly121 case .readsUserData: self = .sensitiveData122 case .writesUserData: self = .localModification123 case .sendsDataExternally: self = .externalNetwork124 case .destructive: self = .externalSideEffects125 }126 }127}128129/// How often the person is asked for one permission level.130public enum ApprovalRule: String, Sendable, Codable, Hashable, CaseIterable, Identifiable {131 /// Never asks.132 case allow133 /// Asks the first time in a run (per tool, and per website for network tools), then not again in that run.134 case askOncePerRun135 /// Asks before every call, unless the person answered "allow for this run".136 case askEveryTime137 /// Asks before every call; "allow for this run" is not offered.138 case alwaysAsk139 /// Refuses without asking.140 case never141142 public var id: String { rawValue }143144 public var title: String {145 switch self {146 case .allow: "Without asking"147 case .askOncePerRun: "Ask once per run"148 case .askEveryTime: "Ask every time"149 case .alwaysAsk: "Always ask, no shortcuts"150 case .never: "Never allowed"151 }152 }153}154155/// How much an agent may do without asking. A profile is a table of rules, one per permission level; nothing else.156public enum AutonomyProfile: Sendable, Codable, Hashable {157 /// A confirmation before anything that touches data or the network, every time.158 case guided159 /// Reads are confirmed once per run; writes and network requests each time (or once per website with "allow for this run").160 case balanced161 /// Reads without asking; each website is confirmed once per run; changes are still confirmed every time.162 case advanced163 /// The person's own table.164 case custom([PermissionLevel: ApprovalRule])165166 public static let selectable: [AutonomyProfile] = [.guided, .balanced, .advanced]167168 public var title: String {169 switch self {170 case .guided: "Guided"171 case .balanced: "Balanced"172 case .advanced: "Advanced"173 case .custom: "Custom"174 }175 }176177 public var summary: String {178 switch self {179 case .guided: "Asks before every action that reads your data, changes something or reaches a website."180 case .balanced: "Reads your data after one confirmation per run. Asks before each change and each website."181 case .advanced: "Reads your data without asking. Asks once per website and before every change."182 case .custom: "Your own rule for each kind of action."183 }184 }185186 /// The rule for one level. Computation never asks under any profile; nothing else is ever allowed silently by default.187 public func rule(for level: PermissionLevel) -> ApprovalRule {188 if level == .readOnly, case .custom(let table) = self { return table[.readOnly] == .never ? .never : .allow }189 switch (self, level) {190 case (_, .readOnly): return .allow191 case (.guided, .sensitiveData): return .askEveryTime192 case (.guided, _): return .alwaysAsk193 case (.balanced, .sensitiveData): return .askOncePerRun194 case (.balanced, _): return .askEveryTime195 case (.advanced, .sensitiveData): return .allow196 case (.advanced, .externalNetwork): return .askOncePerRun197 case (.advanced, _): return .askEveryTime198 case (.custom(let table), let level): return table[level] ?? AutonomyProfile.balanced.rule(for: level)199 }200 }201202 /// The full table of a profile, for display and as the starting point of a custom one.203 public var table: [PermissionLevel: ApprovalRule] {204 Dictionary(uniqueKeysWithValues: PermissionLevel.allCases.map { ($0, rule(for: $0)) })205 }206207 // Stored as {"kind": "...", "rules": {...}}; an unknown kind reads as balanced, never as something more permissive.208 private enum CodingKeys: String, CodingKey { case kind, rules }209210 public init(from decoder: Decoder) throws {211 let c = try decoder.container(keyedBy: CodingKeys.self)212 switch try c.decodeIfPresent(String.self, forKey: .kind) {213 case "guided": self = .guided214 case "advanced": self = .advanced215 case "custom":216 let raw = try c.decodeIfPresent([String: String].self, forKey: .rules) ?? [:]217 var table: [PermissionLevel: ApprovalRule] = [:]218 for (key, value) in raw { if let level = PermissionLevel(rawValue: key), let rule = ApprovalRule(rawValue: value) { table[level] = rule } }219 self = .custom(table)220 default: self = .balanced221 }222 }223224 public func encode(to encoder: Encoder) throws {225 var c = encoder.container(keyedBy: CodingKeys.self)226 switch self {227 case .guided: try c.encode("guided", forKey: .kind)228 case .balanced: try c.encode("balanced", forKey: .kind)229 case .advanced: try c.encode("advanced", forKey: .kind)230 case .custom(let table):231 try c.encode("custom", forKey: .kind)232 try c.encode(Dictionary(uniqueKeysWithValues: table.map { ($0.key.rawValue, $0.value.rawValue) }), forKey: .rules)233 }234 }235}236237/// The single place where "may this call run, and must the person be asked first" is decided.238/// Inputs: the tool's declared level, the autonomy profile, the grants of the run, and whether the call looks dangerous.239/// A call that carries a warning (possible exfiltration, a call that follows suspicious content) is never allowed silently.240public struct PermissionEngine: Sendable, Hashable {241 public enum Verdict: Sendable, Hashable {242 case allow243 /// Ask the person. `offerRunGrant` is false when "allow for this run" must not be offered.244 case ask(offerRunGrant: Bool)245 case refuse(String)246 }247248 public var autonomy: AutonomyProfile249 public init(autonomy: AutonomyProfile = .balanced) { self.autonomy = autonomy }250251 public func verdict(tool: String, level: PermissionLevel, scope: String?, grants: ApprovalGrants, hasWarnings: Bool) -> Verdict {252 let rule = autonomy.rule(for: level)253 if rule == .never { return .refuse("This agent is not allowed to use \(tool) (\(level.title.lowercased())).") }254 if level == .readOnly { return .allow }255 // Something about this call deserves a second look: the person sees it, whatever was granted before.256 if hasWarnings { return .ask(offerRunGrant: false) }257 let key = ApprovalGrants.key(tool: tool, scope: scope)258 switch rule {259 case .allow: return .allow260 case .askOncePerRun:261 return grants.forRun.contains(key) || grants.readsApproved.contains(key) || (scope == nil && grants.readsApproved.contains(tool))262 ? .allow : .ask(offerRunGrant: true)263 case .askEveryTime: return grants.forRun.contains(key) ? .allow : .ask(offerRunGrant: true)264 case .alwaysAsk: return .ask(offerRunGrant: false)265 case .never: return .refuse("This agent is not allowed to use \(tool).")266 }267 }268269 /// What an answer adds to the grants of the run.270 public func record(_ decision: ApprovalDecision, tool: String, level: PermissionLevel, scope: String?, into grants: inout ApprovalGrants) {271 let rule = autonomy.rule(for: level)272 switch decision {273 case .deny: return274 case .allowOnce:275 // "Once per run" means the first yes covers the rest of the run for that tool (and that website).276 if rule == .askOncePerRun { grants.approveOnce(tool: tool, scope: scope) }277 case .allowForRun:278 guard rule != .alwaysAsk else { return } // the shortcut does not exist under this rule, whatever the UI sent279 grants.grant(tool: tool, scope: scope)280 if rule == .askOncePerRun { grants.approveOnce(tool: tool, scope: scope) }281 }282 }283}284