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/AgentEditorScreen.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 AstraCore90import AstraAgents91import AstraDesign9293/// Creates or edits an agent profile. Resolves the profile first, then hands a private copy to the form.94struct AgentEditorScreen: View {95 let agents: AgentsController96 let existingID: String?97 @Binding var path: [AgentRoute]9899 var body: some View {100 if let existingID {101 if let profile = agents.profile(id: existingID) { AgentEditorForm(agents: agents, initial: profile, isNew: false, path: $path).id(existingID) }102 else { missing("This agent no longer exists", "It was deleted.") }103 } else if let draft = agents.newProfileDraft() {104 AgentEditorForm(agents: agents, initial: draft, isNew: true, path: $path)105 } else {106 missing("Agents need a model", "Download an on-device model or add a provider key in Models, then create the agent.")107 }108 }109110 private func missing(_ title: String, _ message: String) -> some View {111 EmptyStateView(symbol: "questionmark.folder", title: title, message: message)112 .frame(maxWidth: .infinity, maxHeight: .infinity).background(Starfield(density: 0.35))113 }114}115116struct AgentEditorForm: View {117 @Environment(AppModel.self) private var app118 let agents: AgentsController119 let isNew: Bool120 @Binding var path: [AgentRoute]121 private let original: AgentProfile122123 @State private var draft: AgentProfile124 @State private var limitTokens: Bool125 @State private var tokenText: String126 @State private var limitCost: Bool127 @State private var costText: String128 @State private var newHost = ""129 @State private var hostError: String?130 @State private var showModelPicker = false131 @State private var isSaving = false132 @State private var confirmDelete = false133 @State private var confirmDiscard = false134 @State private var searchKey = ""135 @State private var hasSearchKey = false136 @FocusState private var focus: Field?137138 private enum Field: Hashable { case name, instructions, tokens, cost, host }139140 static let timeLimits: [TimeInterval] = [60, 120, 300, 600, 900, 1_800, 3_600]141142 init(agents: AgentsController, initial: AgentProfile, isNew: Bool, path: Binding<[AgentRoute]>) {143 self.agents = agents; self.isNew = isNew; _path = path; original = initial144 _draft = State(initialValue: initial)145 _limitTokens = State(initialValue: initial.budgets.maxTotalTokens != nil)146 _tokenText = State(initialValue: initial.budgets.maxTotalTokens.map(String.init) ?? "200000")147 _limitCost = State(initialValue: initial.budgets.maxTotalCostUSD != nil)148 _costText = State(initialValue: initial.budgets.maxTotalCostUSD.map { String(format: "%.2f", $0) } ?? "0.50")149 }150151 private var tokenLimit: Int? { Int(tokenText.filter(\.isNumber)).flatMap { $0 >= 1_000 ? $0 : nil } }152 private var costLimit: Double? { Double(costText.replacingOccurrences(of: ",", with: ".").trimmingCharacters(in: .whitespaces)).flatMap { $0 > 0 && $0.isFinite ? $0 : nil } }153154 /// The draft with the two typed limits applied; nil while one of them is switched on but not a usable number.155 private var resolved: AgentProfile? {156 var out = draft157 if limitTokens { guard let tokenLimit else { return nil }; out.budgets.maxTotalTokens = tokenLimit } else { out.budgets.maxTotalTokens = nil }158 if limitCost { guard let costLimit else { return nil }; out.budgets.maxTotalCostUSD = costLimit } else { out.budgets.maxTotalCostUSD = nil }159 return out160 }161162 private var isDirty: Bool { isNew ? (!draft.name.isEmpty || !draft.instructions.isEmpty) : resolved != original }163 private var canSave: Bool { !draft.name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && resolved != nil && !isSaving }164165 var body: some View {166 Form {167 identitySection168 modelSection169 planningSection170 autonomySection171 ForEach(AgentToolCatalog.grouped, id: \.risk) { group in toolSection(group.risk, group.tools) }172 if draft.usesSearch { searchKeySection }173 if draft.usesWeb { hostsSection }174 delegationSection175 budgetSection176 if !isNew {177 Section {178 Button("Delete agent", role: .destructive) { confirmDelete = true }.accessibilityIdentifier("agent-delete")179 } footer: { Text("Its past runs stay in the history.") }180 }181 }182 .scrollContentBackground(.hidden).background(AstraColor.background)183 .scrollDismissesKeyboard(.interactively)184 .navigationTitle(isNew ? "New agent" : "Edit agent").navigationBarTitleDisplayMode(.inline)185 .navigationBarBackButtonHidden(isDirty)186 .toolbar {187 if isDirty {188 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { confirmDiscard = true }.accessibilityIdentifier("agent-edit-cancel") }189 }190 ToolbarItem(placement: .confirmationAction) {191 Button("Save") { save() }.disabled(!canSave).accessibilityIdentifier("agent-save")192 }193 ToolbarItemGroup(placement: .keyboard) {194 Spacer()195 Button("Done") { focus = nil }196 }197 }198 .sheet(isPresented: $showModelPicker) {199 ModelPickerSheet(selected: draft.model, title: "Model for this agent") { draft.model = $0 }200 }201 .confirmationDialog("Discard your changes?", isPresented: $confirmDiscard, titleVisibility: .visible) {202 Button("Discard changes", role: .destructive) { pop() }203 Button("Keep editing", role: .cancel) {}204 }205 .confirmationDialog("Delete “\(original.name)”?", isPresented: $confirmDelete, titleVisibility: .visible) {206 Button("Delete agent", role: .destructive) { delete() }207 Button("Cancel", role: .cancel) {}208 } message: { Text("Its past runs stay in the history.") }209 }210211 private func pop() { if !path.isEmpty { path.removeLast() } }212213 private func save() {214 guard let profile = resolved, canSave else { return }215 isSaving = true216 Task {217 defer { isSaving = false }218 do {219 try await agents.save(profile)220 AstraHaptics.success()221 app.show(isNew ? "Agent created" : "Agent saved", .success)222 pop()223 } catch { app.show(AstraError.wrap(error).message, .error) }224 }225 }226227 private func delete() {228 Task {229 do {230 try await agents.delete(original)231 // Leaves the editor and the run screen of the agent that no longer exists.232 path.removeAll { $0 == .edit(original.id) || $0 == .run(original.id) }233 } catch { app.show(AstraError.wrap(error).message, .error) }234 }235 }236237 // MARK: Sections238239 private var identitySection: some View {240 Group {241 Section("Name") {242 TextField("Research assistant", text: $draft.name).focused($focus, equals: .name)243 .accessibilityLabel("Agent name").accessibilityIdentifier("agent-name")244 }245 Section {246 TextEditor(text: $draft.instructions).frame(minHeight: 150).font(AstraFont.callout).focused($focus, equals: .instructions)247 .accessibilityLabel("Instructions").accessibilityIdentifier("agent-instructions")248 } header: { Text("Instructions") } footer: {249 Text("Sent to the model at every step, before the rules the app adds about tools and untrusted content. Leave empty for a general assistant.")250 }251 }252 }253254 private var modelSection: some View {255 let info = app.library.info(for: draft.model)256 return Section {257 Button { showModelPicker = true } label: {258 HStack(spacing: AstraSpace.md) {259 ProviderLogo(ref: draft.model, vendor: info?.vendor, size: 34)260 VStack(alignment: .leading, spacing: AstraSpace.xxs) {261 Text(app.library.displayName(for: draft.model)).font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary)262 Text(draft.model.provider.isLocal ? "On this iPhone" : (app.library.endpointName(for: draft.model) ?? draft.model.provider.displayName))263 .font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary)264 }265 Spacer(minLength: AstraSpace.sm)266 Text("Change").font(AstraFont.subheadline.weight(.semibold)).foregroundStyle(AstraColor.violet)267 }268 .frame(minHeight: AstraSpace.hit).contentShape(Rectangle())269 }270 .buttonStyle(.plain)271 .accessibilityElement(children: .combine)272 .accessibilityHint("Chooses another model")273 .accessibilityIdentifier("agent-model")274 if let unavailable = app.library.availability(of: draft.model) {275 Label(unavailable.message, systemImage: "xmark.octagon.fill").font(AstraFont.footnote).foregroundStyle(AstraColor.danger)276 }277 if let warning = AgentModelCheck.toolWarning(info: info, profile: draft) {278 Label(warning, systemImage: "exclamationmark.triangle.fill").font(AstraFont.footnote).foregroundStyle(AstraColor.warning)279 .accessibilityIdentifier("agent-model-tool-warning")280 }281 } header: { Text("Model") } footer: {282 Text(draft.model.provider.isLocal283 ? "On-device model: the goal, tool results and answers stay on this iPhone."284 : "Cloud model: the goal and everything the tools return are sent to \(draft.model.provider.displayName) under its terms.")285 }286 }287288 private var planningSection: some View {289 Section {290 Toggle("Keep a visible plan", isOn: $draft.planningEnabled).accessibilityIdentifier("agent-planning")291 } footer: {292 Text("Gives the agent a built-in way to write its plan and tick steps off as it goes. It touches nothing on your iPhone and never needs approval.")293 }294 }295296 private func toolSection(_ risk: ToolRisk, _ tools: [AgentToolInfo]) -> some View {297 Section {298 ForEach(tools) { tool in299 Toggle(isOn: toolBinding(tool.name)) {300 HStack(alignment: .top, spacing: AstraSpace.md) {301 Image(systemName: tool.symbol).foregroundStyle(AstraColor.violet).frame(width: 26).accessibilityHidden(true)302 VStack(alignment: .leading, spacing: AstraSpace.xxs) {303 Text(tool.title).font(AstraFont.body).foregroundStyle(AstraColor.textPrimary)304 Text(tool.touches).font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true)305 }306 }307 }308 .accessibilityIdentifier("agent-tool-\(tool.name)")309 }310 } header: {311 Label(risk.label, systemImage: risk.symbol)312 } footer: { Text(Self.ruleText(draft.autonomy.rule(for: PermissionLevel(risk: risk)), risk: risk)) }313 }314315 /// The approval rule that applies to a group of tools under the chosen autonomy, in words.316 static func ruleText(_ rule: ApprovalRule, risk: ToolRisk) -> String {317 switch rule {318 case .allow: risk == .safe ? "Never asks: these tools cannot reach your data or the network." : "Runs without asking, under this agent's autonomy."319 case .askOncePerRun: risk == .sendsDataExternally ? "Asks you once per website in each run." : "Asks you the first time in each run."320 case .askEveryTime: risk == .sendsDataExternally ? "Asks you every time, per website. You can allow a website for the rest of a run." : "Asks you every time. You can allow it for the rest of a run."321 case .alwaysAsk: "Asks you every time, with no shortcut."322 case .never: "Not allowed for this agent: calls are refused without asking."323 }324 }325326 private var autonomySection: some View {327 Section {328 Picker("Autonomy", selection: Binding(get: { draft.autonomy }, set: { draft.autonomy = $0 })) {329 ForEach(AutonomyProfile.selectable, id: \.self) { profile in Text(profile.title).tag(profile) }330 if case .custom = draft.autonomy { Text("Custom").tag(draft.autonomy) }331 }332 .pickerStyle(.segmented)333 .accessibilityIdentifier("agent-autonomy")334 Text(draft.autonomy.summary).font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true)335 DisclosureGroup("Rule for each kind of action") {336 ForEach(PermissionLevel.allCases.filter { $0 != .readOnly }) { level in337 Picker(level.title, selection: Binding(get: { draft.autonomy.rule(for: level) }, set: { rule in338 var table = draft.autonomy.table339 table[level] = rule340 // a table equal to a named profile is that profile again341 draft.autonomy = AutonomyProfile.selectable.first { $0.table == table } ?? .custom(table)342 })) {343 ForEach(ApprovalRule.allCases) { rule in Text(rule.title).tag(rule) }344 }345 .accessibilityIdentifier("agent-rule-\(level.rawValue)")346 }347 }348 } header: { Text("Autonomy") } footer: {349 Text("These rules are enforced by the app, not by the model. Whatever the autonomy, a call that looks like it carries your data away, or that follows suspicious content, is always shown to you.")350 }351 }352353 private var delegationSection: some View {354 Section {355 Toggle("Allow sub-agents", isOn: $draft.delegation.enabled).accessibilityIdentifier("agent-delegation")356 if draft.delegation.enabled {357 Stepper("At the same time: \(draft.delegation.maxParallel)", value: $draft.delegation.maxParallel, in: 1...4)358 Stepper("Steps each: up to \(draft.delegation.maxStepsPerDelegate)", value: $draft.delegation.maxStepsPerDelegate, in: 1...20)359 }360 } header: { Text("Sub-agents") } footer: {361 Text("Lets the agent hand independent pieces of a task to specialised sub-agents (research, analysis, verification…). They use this agent's tools at most, ask you through the same approvals, share what is left of its budgets, and cannot start sub-agents of their own.")362 }363 }364365 private var searchKeySection: some View {366 Section {367 if hasSearchKey {368 Label("A Tavily key is saved on this iPhone", systemImage: "checkmark.seal").foregroundStyle(AstraColor.success)369 Button("Remove the key", role: .destructive) { try? agents.setSearchKey(nil); hasSearchKey = agents.hasSearchKey }370 .accessibilityIdentifier("agent-search-key-remove")371 } else {372 SecureField("Tavily API key", text: $searchKey).textInputAutocapitalization(.never).autocorrectionDisabled()373 .accessibilityIdentifier("agent-search-key")374 Button("Save key") {375 let key = searchKey; searchKey = ""376 do { try agents.setSearchKey(key); hasSearchKey = agents.hasSearchKey } catch { app.show(AstraError.wrap(error).message, .error) }377 }378 .disabled(searchKey.trimmingCharacters(in: .whitespaces).count < 8)379 .accessibilityIdentifier("agent-search-key-save")380 }381 } header: { Text("Web search key") } footer: {382 Text("Web search uses Tavily with your own key, kept in this iPhone's Keychain. Each query is sent to api.tavily.com; nothing else is.")383 }384 .task { hasSearchKey = agents.hasSearchKey }385 }386387 /// Keeps the allowlist in the catalogue's order whatever the order of the taps.388 private func toolBinding(_ name: String) -> Binding<Bool> {389 Binding(get: { draft.allowedTools.contains(name) }, set: { isOn in390 var chosen = Set(draft.allowedTools)391 if isOn { chosen.insert(name) } else { chosen.remove(name) }392 let known = AgentToolCatalog.all.map(\.name)393 draft.allowedTools = known.filter(chosen.contains) + draft.allowedTools.filter { chosen.contains($0) && !known.contains($0) }394 })395 }396397 private var hostsSection: some View {398 Section {399 ForEach(draft.preApprovedWebHosts, id: \.self) { host in400 HStack {401 Text(host).font(AstraFont.mono).foregroundStyle(AstraColor.textPrimary).lineLimit(1).truncationMode(.middle)402 Spacer(minLength: AstraSpace.sm)403 IconButton("minus.circle.fill", label: "Remove \(host)", tint: AstraColor.danger) { draft.preApprovedWebHosts.removeAll { $0 == host } }404 }405 }406 HStack(spacing: AstraSpace.sm) {407 TextField("example.org", text: $newHost)408 .textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.URL)409 .focused($focus, equals: .host).onSubmit(addHost)410 .accessibilityLabel("Website to pre-approve").accessibilityIdentifier("agent-host-field")411 Button("Add", action: addHost).disabled(newHost.trimmingCharacters(in: .whitespaces).isEmpty)412 .frame(minWidth: AstraSpace.hit, minHeight: AstraSpace.hit).accessibilityIdentifier("agent-host-add")413 }414 if let hostError { Label(hostError, systemImage: "xmark.octagon.fill").font(AstraFont.footnote).foregroundStyle(AstraColor.danger) }415 } header: { Text("Pre-approved websites") } footer: {416 Text("Pages on these exact hosts are fetched without asking. Every other website asks you each time, and an address that seems to carry your data always asks. Leave the list empty to be asked for everything.")417 }418 }419420 private func addHost() {421 var text = newHost.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()422 guard !text.isEmpty else { return }423 if !text.contains("://") { text = "https://" + text }424 guard let url = URL(string: text), let host = WebHostPolicy.normalisedHost(url) else { hostError = "That is not a website name. Enter something like example.org."; return }425 var components = URLComponents()426 components.scheme = "https"; components.host = host427 if let bare = components.url, let reason = WebHostPolicy().refusal(for: bare) { hostError = reason; return }428 if url.scheme != "https" { hostError = "Only https websites can be fetched."; return }429 hostError = nil430 if !draft.preApprovedWebHosts.contains(host) { draft.preApprovedWebHosts.append(host) }431 newHost = ""432 }433434 private var budgetSection: some View {435 Section {436 Stepper(value: $draft.budgets.maxSteps, in: 1...50) {437 LabeledContent("Steps") { Text("\(draft.budgets.maxSteps)").monospacedDigit() }438 }439 .accessibilityValue("\(draft.budgets.maxSteps)").accessibilityIdentifier("agent-budget-steps")440 Stepper(value: $draft.budgets.maxToolCalls, in: 0...100) {441 LabeledContent("Tool calls") { Text("\(draft.budgets.maxToolCalls)").monospacedDigit() }442 }443 .accessibilityValue("\(draft.budgets.maxToolCalls)").accessibilityIdentifier("agent-budget-tool-calls")444 Stepper(value: outputTokens, in: 256...16_384, step: 256) {445 LabeledContent("Output per step") { Text("\(AgentFormat.count(outputTokens.wrappedValue)) tokens").monospacedDigit() }446 }447 .accessibilityValue("\(outputTokens.wrappedValue) tokens").accessibilityIdentifier("agent-budget-output")448449 Toggle("Limit total tokens", isOn: $limitTokens).accessibilityIdentifier("agent-budget-tokens-toggle")450 if limitTokens {451 LabeledContent("Total tokens") {452 TextField("200000", text: $tokenText).keyboardType(.numberPad).multilineTextAlignment(.trailing).monospacedDigit()453 .focused($focus, equals: .tokens).accessibilityLabel("Total token limit").accessibilityIdentifier("agent-budget-tokens")454 }455 if tokenLimit == nil { Label("Enter a whole number of at least 1,000.", systemImage: "xmark.octagon.fill").font(AstraFont.footnote).foregroundStyle(AstraColor.danger) }456 }457 Toggle("Limit cost", isOn: $limitCost).accessibilityIdentifier("agent-budget-cost-toggle")458 if limitCost {459 LabeledContent("Cost limit (USD)") {460 TextField("0.50", text: $costText).keyboardType(.decimalPad).multilineTextAlignment(.trailing).monospacedDigit()461 .focused($focus, equals: .cost).accessibilityLabel("Cost limit in US dollars").accessibilityIdentifier("agent-budget-cost")462 }463 if costLimit == nil { Label("Enter an amount above zero.", systemImage: "xmark.octagon.fill").font(AstraFont.footnote).foregroundStyle(AstraColor.danger) }464 }465 Picker("Time limit", selection: $draft.budgets.wallClockLimit) {466 ForEach(Self.timeLimits, id: \.self) { Text(AgentFormat.minutes($0)).tag(TimeInterval?.some($0)) }467 if let current = draft.budgets.wallClockLimit, !Self.timeLimits.contains(current) { Text(AgentFormat.minutes(current)).tag(TimeInterval?.some(current)) }468 Text("No limit").tag(TimeInterval?.none)469 }470 .accessibilityIdentifier("agent-budget-time")471 } header: { Text("Limits") } footer: {472 Text("Limits are enforced by the app, not by the model. Tokens are counted when the model reports them. The cost limit works when the cost is known (reported by the provider, or usage × published price); when it is not, the run says so instead of guessing. On-device models cost nothing.")473 }474 }475476 private var outputTokens: Binding<Int> {477 Binding(get: { min(16_384, max(256, draft.budgets.maxOutputTokensPerTurn ?? 2_048)) }, set: { draft.budgets.maxOutputTokensPerTurn = $0 })478 }479}480