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/AgentApprovals.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 SwiftUI89import Observation90import AstraCore91import AstraAgents92import AstraDesign9394/// Bridges the runner's approval question to a sheet: the run suspends on a continuation until the person answers.95/// Nothing is ever approved here without a tap; a stopped run or a dismissed sheet resolves as a denial.96@MainActor @Observable final class AgentApprovalBroker: ApprovalHandler {97 private(set) var pending: ApprovalRequest?98 @ObservationIgnored private var continuation: CheckedContinuation<AgentDecision, Never>?99 /// Told when a question arrives, so the app can point at it when another tab is in front.100 @ObservationIgnored var onRequest: ((ApprovalRequest) -> Void)?101102 func requestApproval(_ request: ApprovalRequest) async -> AgentDecision {103 // One question at a time: the runner asks sequentially, so an older one still open belongs to a run that moved on.104 resolve(.deny(reason: nil))105 return await withTaskCancellationHandler {106 await withCheckedContinuation { continuation in107 if Task.isCancelled { continuation.resume(returning: .deny(reason: "The run was stopped.")); return }108 self.continuation = continuation109 pending = request110 onRequest?(request)111 }112 } onCancel: {113 Task { @MainActor in self.resolve(.deny(reason: "The run was stopped."), requestID: request.id) }114 }115 }116117 /// Answers the open question. With `requestID`, only when that question is still the open one.118 func resolve(_ decision: AgentDecision, requestID: String? = nil) {119 guard let waiting = continuation else { return }120 if let requestID, pending?.id != requestID { return }121 continuation = nil122 pending = nil123 waiting.resume(returning: decision)124 }125}126127/// The approval question: what the tool is, what it will do, with which arguments, and the three possible answers.128struct AgentApprovalSheet: View {129 let request: ApprovalRequest130 let resolve: (AgentDecision) -> Void131 let stopRun: () -> Void132133 @State private var showReason = false134 @State private var reason = ""135 @State private var showArguments = false136 @FocusState private var reasonFocused: Bool137138 var body: some View {139 NavigationStack {140 ScrollView {141 VStack(alignment: .leading, spacing: AstraSpace.lg) {142 header143 if !request.warnings.isEmpty {144 VStack(alignment: .leading, spacing: AstraSpace.sm) {145 ForEach(request.warnings, id: \.self) { warning in146 NoticeCard(.error, title: "Look twice before allowing", message: warning)147 }148 }149 .accessibilityIdentifier("approval-warnings")150 }151 AstraCard {152 VStack(alignment: .leading, spacing: AstraSpace.sm) {153 Text("What will happen").font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textTertiary)154 Text(request.summary).font(AstraFont.body).foregroundStyle(AstraColor.textPrimary)155 .fixedSize(horizontal: false, vertical: true).textSelection(.enabled)156 if let scope = request.scope {157 Divider().overlay(AstraColor.stroke)158 Label { Text(scope).font(AstraFont.mono).foregroundStyle(AstraColor.textPrimary) } icon: {159 Image(systemName: "globe").foregroundStyle(AstraColor.textSecondary)160 }161 .accessibilityElement(children: .combine)162 .accessibilityLabel("Website \(scope)")163 if request.offersRunGrant {164 Text("“For this run” would cover this website only.").font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary)165 }166 }167 }168 }169 arguments170 if showReason {171 TextField("Why not? The agent is told (optional)", text: $reason, axis: .vertical)172 .lineLimit(1...4)173 .font(AstraFont.callout)174 .padding(AstraSpace.md)175 .background(AstraColor.surface, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))176 .overlay(RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous).strokeBorder(AstraColor.stroke, lineWidth: 1))177 .focused($reasonFocused)178 .accessibilityIdentifier("approval-deny-reason")179 }180 }181 .padding(.horizontal, AstraSpace.page).padding(.vertical, AstraSpace.lg)182 }183 .scrollDismissesKeyboard(.interactively)184 .background(AstraColor.background)185 .navigationTitle("Approval needed").navigationBarTitleDisplayMode(.inline)186 .toolbar {187 ToolbarItem(placement: .cancellationAction) {188 Button("Stop run", role: .destructive, action: stopRun).accessibilityIdentifier("approval-stop-run")189 }190 }191 .safeAreaInset(edge: .bottom) { choices }192 }193 .presentationDetents([.large])194 .presentationDragIndicator(.visible)195 }196197 private var header: some View {198 HStack(alignment: .top, spacing: AstraSpace.md) {199 Image(systemName: AgentToolCatalog.symbol(request.toolName))200 .font(.title3.weight(.semibold)).foregroundStyle(AstraColor.signature)201 .frame(width: AstraSpace.hit, height: AstraSpace.hit)202 .background(AstraColor.surfaceRaised, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))203 .accessibilityHidden(true)204 VStack(alignment: .leading, spacing: AstraSpace.xs) {205 Text(AgentToolCatalog.title(request.toolName)).font(AstraFont.title).foregroundStyle(AstraColor.textPrimary)206 Text(request.toolName).font(AstraFont.monoSmall).foregroundStyle(AstraColor.textSecondary)207 AstraBadge(request.risk.label, symbol: request.risk.symbol, tone: request.risk.tone)208 if let who = request.requestedBy {209 Text("Asked by the \(who) sub-agent").font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary)210 }211 }212 Spacer(minLength: 0)213 }214 .accessibilityElement(children: .combine)215 }216217 private var arguments: some View {218 VStack(alignment: .leading, spacing: AstraSpace.sm) {219 Button {220 showArguments.toggle()221 } label: {222 HStack {223 Text("Arguments").font(AstraFont.subheadline.weight(.semibold)).foregroundStyle(AstraColor.textPrimary)224 Text("secrets masked").font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary)225 Spacer(minLength: AstraSpace.sm)226 Image(systemName: showArguments ? "chevron.up" : "chevron.down").font(.footnote.weight(.semibold)).foregroundStyle(AstraColor.textSecondary)227 }228 .frame(minHeight: AstraSpace.hit).contentShape(Rectangle())229 }230 .buttonStyle(.plain)231 .accessibilityLabel("Arguments, secrets masked")232 .accessibilityValue(showArguments ? "Shown" : "Hidden")233 .accessibilityIdentifier("approval-arguments")234 if showArguments {235 Text(request.arguments.serialized(pretty: true))236 .font(AstraFont.monoSmall).foregroundStyle(AstraColor.textPrimary)237 .textSelection(.enabled)238 .frame(maxWidth: .infinity, alignment: .leading)239 .padding(AstraSpace.md)240 .background(AstraColor.codeBackground, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))241 }242 }243 }244245 private var choices: some View {246 VStack(spacing: AstraSpace.sm) {247 Button("Allow once") { resolve(.allowOnce) }248 .buttonStyle(AstraPrimaryButtonStyle())249 .accessibilityIdentifier("approval-allow-once")250 // Offered only when this agent's autonomy allows a lasting answer and nothing about the call needs a second look.251 if request.offersRunGrant {252 Button { resolve(.allowForRun) } label: {253 Text(request.allowForRunLabel).multilineTextAlignment(.center).padding(.vertical, AstraSpace.xs)254 }255 .buttonStyle(AstraSecondaryButtonStyle())256 .accessibilityIdentifier("approval-allow-run")257 }258 HStack(spacing: AstraSpace.sm) {259 Button(showReason ? "Hide reason" : "Add a reason") {260 showReason.toggle()261 reasonFocused = showReason262 }263 .buttonStyle(AstraSecondaryButtonStyle())264 .accessibilityIdentifier("approval-add-reason")265 Button("Deny") { resolve(.deny(reason: showReason ? reason : nil)) }266 .buttonStyle(AstraPrimaryButtonStyle(destructive: true))267 .accessibilityIdentifier("approval-deny")268 }269 }270 .padding(.horizontal, AstraSpace.page).padding(.top, AstraSpace.md).padding(.bottom, AstraSpace.sm)271 .background(AstraColor.background)272 .overlay(alignment: .top) { Divider().overlay(AstraColor.stroke) }273 }274}275