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/Delegation.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/// Whether and how far an agent may hand parts of its task to sub-agents.92public struct DelegationPolicy: Sendable, Codable, Hashable {93 public var enabled: Bool94 /// 1 = sub-agents cannot delegate again. Never more than 2.95 public var maxDepth: Int96 /// Sub-agents of one `delegate` call that run at the same time.97 public var maxParallel: Int98 /// Model turns one sub-agent may take, at most (also bounded by what the parent has left).99 public var maxStepsPerDelegate: Int100101 public init(enabled: Bool = false, maxDepth: Int = 1, maxParallel: Int = 3, maxStepsPerDelegate: Int = 6) {102 self.enabled = enabled; self.maxDepth = min(2, max(1, maxDepth)); self.maxParallel = min(4, max(1, maxParallel))103 self.maxStepsPerDelegate = min(20, max(1, maxStepsPerDelegate))104 }105106 public init(from decoder: Decoder) throws {107 let c = try decoder.container(keyedBy: CodingKeys.self)108 self.init(enabled: try c.decodeIfPresent(Bool.self, forKey: .enabled) ?? false, maxDepth: try c.decodeIfPresent(Int.self, forKey: .maxDepth) ?? 1,109 maxParallel: try c.decodeIfPresent(Int.self, forKey: .maxParallel) ?? 3,110 maxStepsPerDelegate: try c.decodeIfPresent(Int.self, forKey: .maxStepsPerDelegate) ?? 6)111 }112}113114/// The specialised sub-agents. A role is a set of instructions, nothing more: it grants no tool and no permission.115public enum DelegateRole: String, Sendable, Codable, Hashable, CaseIterable, Identifiable {116 case research, coding, analysis, document, verification, planning, synthesis117 public var id: String { rawValue }118119 public var title: String {120 switch self {121 case .research: "Research"122 case .coding: "Coding"123 case .analysis: "Analysis"124 case .document: "Document"125 case .verification: "Verification"126 case .planning: "Planning"127 case .synthesis: "Synthesis"128 }129 }130131 public var symbol: String {132 switch self {133 case .research: "magnifyingglass"134 case .coding: "chevron.left.forwardslash.chevron.right"135 case .analysis: "chart.bar.xaxis"136 case .document: "doc.text"137 case .verification: "checkmark.seal"138 case .planning: "list.bullet.clipboard"139 case .synthesis: "square.stack.3d.down.right"140 }141 }142143 public var instructions: String {144 switch self {145 case .research:146 "You are a research sub-agent. Find what the task asks for with the tools you have, keep track of where each fact comes from, "147 + "and report the facts with their sources. Say plainly what you could not find or could not verify. Do not speculate."148 case .coding:149 "You are a coding sub-agent. Produce correct, complete code for the task, state the assumptions you made, and name what you did not test. "150 + "You cannot run code: reason about it carefully instead."151 case .analysis:152 "You are an analysis sub-agent. Work through the data or the question methodically, show the figures you rely on, use the calculation "153 + "tools for arithmetic, and separate what the data shows from what you infer."154 case .document:155 "You are a document sub-agent. Read the documents or files the task points to, quote or cite the passages you rely on, and report "156 + "exactly what they say. Mark anything the documents do not cover."157 case .verification:158 "You are a verification sub-agent. Check the claim or the result you are given against the tools and sources you have. Report what you "159 + "confirmed, what you found wrong, and what you could not check. Agreement between sources is not proof; say how strong the evidence is."160 case .planning:161 "You are a planning sub-agent. Break the task into concrete steps in a sensible order, name what each step needs, and point out the risks "162 + "and the unknowns. Do not carry the steps out."163 case .synthesis:164 "You are a synthesis sub-agent. Combine the material you are given into one coherent answer. Keep disagreements visible instead of "165 + "averaging them away, and keep the sources attached to the claims."166 }167 }168}169170/// The built-in delegation tool. Like `update_plan` it is handled by the runner; it is offered only when the profile enables171/// delegation and the agent is not already at the depth limit.172public enum DelegateTool {173 public static let name = "delegate"174 public static let maxTasks = 4175176 public static let definition = ToolDefinition(177 name: name,178 summary: "Hands one or more self-contained subtasks to specialised sub-agents and returns their reports. Sub-agents of one call run at the "179 + "same time, share your tools (never more) and your remaining budget, and see only the task text you write, so make each task complete. "180 + "Use it for independent pieces of work; do the work yourself when it is small.",181 parameters: [182 "type": "object",183 "properties": [184 "tasks": [185 "type": "array", "minItems": 1, "maxItems": .number(Double(maxTasks)),186 "items": [187 "type": "object",188 "properties": [189 "role": ["type": "string", "enum": .array(DelegateRole.allCases.map { .string($0.rawValue) })],190 "task": ["type": "string", "minLength": 1, "maxLength": 4000,191 "description": "Everything the sub-agent needs: the question, the material, the expected form of the report."],192 "tools": ["type": "array", "maxItems": 16, "items": ["type": "string", "minLength": 1, "maxLength": 64],193 "description": "Optional subset of your tools for this sub-agent. Default: all of yours."],194 ],195 "required": ["role", "task"],196 "additionalProperties": false,197 ],198 ],199 ],200 "required": ["tasks"],201 "additionalProperties": false,202 ])203204 struct Assignment: Sendable, Hashable {205 var id: String206 var role: DelegateRole207 var task: String208 var tools: [String]?209 }210211 static func assignments(from arguments: JSONValue, callID: String) throws -> [Assignment] {212 try SchemaValidator.validate(arguments: arguments, for: definition)213 return (arguments["tasks"]?.arrayValue ?? []).enumerated().compactMap { index, item in214 guard let role = item["role"]?.stringValue.flatMap(DelegateRole.init(rawValue:)), let task = item["task"]?.stringValue else { return nil }215 return Assignment(id: "\(callID)#\(index + 1)", role: role, task: task, tools: item["tools"]?.arrayValue?.compactMap(\.stringValue))216 }217 }218}219220/// What a model must be able to do to run an agent, checked before a run starts. Nothing here is a guess: the caller passes221/// what is known about the model (from its provider's metadata or from the loaded on-device model).222public struct AgentModelFacts: Sendable, Hashable {223 public var isOnDevice: Bool224 public var supportsTools: Bool?225 public var contextLength: Int?226 public var supportsVision: Bool?227 public var supportsReasoning: Bool?228 public init(isOnDevice: Bool, supportsTools: Bool? = nil, contextLength: Int? = nil, supportsVision: Bool? = nil, supportsReasoning: Bool? = nil) {229 self.isOnDevice = isOnDevice; self.supportsTools = supportsTools; self.contextLength = contextLength230 self.supportsVision = supportsVision; self.supportsReasoning = supportsReasoning231 }232}233234public struct AgentCompatibility: Sendable, Hashable {235 public enum Severity: String, Sendable, Hashable { case blocking, limitation, note }236 public struct Issue: Sendable, Hashable, Identifiable {237 public var severity: Severity238 public var message: String239 public var id: String { message }240 }241 public var issues: [Issue]242 /// Tools that can really be offered to this model.243 public var usableTools: [String]244 public var canRun: Bool { !issues.contains { $0.severity == .blocking } }245246 /// Compares a profile with what is known about its model. A model without tool calling still runs, without tools, and247 /// the person is told; nothing is ever moved to another model to make it work.248 public static func check(profile: AgentProfile, facts: AgentModelFacts, offered: [ToolDefinition]) -> AgentCompatibility {249 var issues: [Issue] = []250 var usable = offered.map(\.name)251 if !offered.isEmpty {252 switch facts.supportsTools {253 case false?:254 usable = []255 issues.append(Issue(severity: .limitation, message: facts.isOnDevice256 ? "This on-device model has no tool-calling format, so the agent will answer from what it knows, without tools. Pick a model marked “Tools” to use them."257 : "This model does not support tools, so the agent will answer without them."))258 case nil:259 issues.append(Issue(severity: .note, message: "It is not known whether this model can call tools. If it cannot, the agent will answer without them."))260 case true?: break261 }262 }263 if let context = facts.contextLength {264 let overhead = offered.reduce(TokenEstimator.estimate(AgentRunner.systemPrompt(profile: profile, tools: offered))) {265 $0 + 12 + TokenEstimator.estimate($1.summary) + TokenEstimator.estimate($1.parameters.serialized())266 }267 let reserve = profile.budgets.maxOutputTokensPerTurn ?? 1_024268 if overhead + reserve + 256 > context {269 issues.append(Issue(severity: .blocking, message: "The instructions and tool descriptions need about \(overhead) tokens and the answer \(reserve), but this model's context holds \(context). Remove tools, shorten the instructions or pick a model with a longer context."))270 } else if overhead * 2 > context {271 issues.append(Issue(severity: .limitation, message: "The tool descriptions take about \(overhead) of this model's \(context) tokens of context, which leaves little room for the work. Fewer tools will help."))272 }273 }274 if facts.isOnDevice, profile.delegation.enabled {275 issues.append(Issue(severity: .note, message: "Sub-agents on an on-device model run one after the other: the device runs one generation at a time."))276 }277 if facts.isOnDevice {278 issues.append(Issue(severity: .note, message: "This agent runs on this iPhone. Nothing is sent to a cloud model; web tools still reach the websites you approve."))279 }280 return AgentCompatibility(issues: issues, usableTools: usable)281 }282}283