SPB Git

Repository Public

ToolCatalog.swift 14.4 KB 262 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Docs9// File             : Packages/ORIXDocsAI/Sources/DocAgent/ToolCatalog.swift10// Description      : The tools a model may call: every command of the command11//                    engine, renamed for providers that forbid dots, filtered12//                    by the scopes granted to the run, plus the agent's own13//                    control tools (plan, question, finish, workflow, context).14//                    Nothing else is reachable.15// Module           : DocAgent16// Repository       : https://git.spboucher.ai/orix-docs17// Created          : 2026-11-2218// Last Modified    : 2026-11-2219//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : None specified (no license file in this repository)85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Foundation93import AstraCore94import DocCommands9596/// What calling a tool can do. Derived from the command specification, never from what a model says.97public enum ToolEffect: String, Sendable, Codable, Hashable {98    /// Reads the document or the agent's own context.99    case read100    /// Changes the document through a command-engine transaction.101    case mutate102    /// Produces a file handed to the host.103    case artifact104    /// Changes the state of the run only (plan, final report).105    case control106    /// Waits for the person.107    case question108    /// Runs a workflow supplied by the host.109    case workflow110}111112/// The agent's own tools, handled by the loop.113public enum AgentToolID {114    public static let planUpdate = "plan.update"115    public static let askUser = "ask_user"116    public static let finish = "finish"117    public static let workflowExecute = "workflow.execute"118    public static let contextOverview = "context.overview"119    public static let contextRetrieve = "context.retrieve"120    public static let all = [planUpdate, askUser, finish, workflowExecute, contextOverview, contextRetrieve]121}122123/// One tool as the registry describes it: for the model, for the approval sheet, for the audit trail and for the documentation.124public struct DocAgentTool: Sendable, Hashable, Identifiable {125    /// Canonical identifier ("text.replace", "plan.update").126    public var id: String127    /// Name given to the model ("text_replace").128    public var name: String129    public var title: String130    public var summary: String131    public var input: DocJSON132    /// What the tool returns, in words.133    public var outputSummary: String134    public var scopes: [DocScope]135    public var effect: ToolEffect136    /// Seconds the loop waits for the tool before giving the model a timeout error. Nil for tools that wait for the person.137    public var timeout: TimeInterval?138    public var cancellable: Bool139    /// True for a command of the command engine, false for an agent tool.140    public var isCommand: Bool141142    public var definition: ToolDefinition {143        var text = summary144        switch effect {145        case .mutate: text += " Changes the document: the changes requested in one turn form one atomic batch, previewed and possibly submitted for approval."146        case .artifact: text += " Produces a file that is handed to the application; you never choose where it is written."147        default: break148        }149        if !outputSummary.isEmpty { text += " Returns: \(outputSummary)." }150        return ToolDefinition(name: name, summary: text, parameters: JSONBridge.model(input))151    }152}153154public enum ToolNaming {155    /// Providers accept `^[A-Za-z0-9_-]{1,64}$`. Command identifiers use letters and dots only, so replacing the dot is reversible through the catalog.156    public static func modelName(_ id: String) -> String {157        String(id.map { $0 == "." ? "_" : $0 }.filter { $0.isLetter || $0.isNumber || $0 == "_" || $0 == "-" }.prefix(64))158    }159}160161/// The set of tools exposed to one run. Built once, from code; a model cannot add to it.162public struct DocToolCatalog: Sendable {163    public private(set) var tools: [DocAgentTool] = []164    private var byName: [String: DocAgentTool] = [:]165    private var byID: [String: DocAgentTool] = [:]166167    public struct Options: Sendable {168        /// When set, only these command identifiers are exposed (a role's tool subset).169        public var commandAllowlist: Set<String>?170        /// Commands never exposed (a Custom autonomy "deny").171        public var deniedCommands: Set<String> = []172        /// Agent tools to leave out ("workflow.execute" when the host supplies no workflow runner).173        public var excludedAgentTools: Set<String> = []174        public var defaultTimeout: TimeInterval = 30175        /// Commands that paginate or convert the whole document get more time.176        public var slowTimeout: TimeInterval = 120177        /// When set, replaces the deadline of every tool that has one.178        public var timeoutOverride: TimeInterval?179        public init(commandAllowlist: Set<String>? = nil, deniedCommands: Set<String> = [], excludedAgentTools: Set<String> = []) {180            self.commandAllowlist = commandAllowlist; self.deniedCommands = deniedCommands; self.excludedAgentTools = excludedAgentTools181        }182    }183184    static let slowCommands: Set<String> = ["document.statistics", "document.audit", "document.export", "document.compare", "publishing.preflight"]185186    public init(registry: DocCommandRegistry = .standard, scopes: Set<DocScope>, options: Options = Options()) {187        for spec in registry.specs {188            guard Set(spec.permissions).isSubset(of: scopes) else { continue }189            if let allow = options.commandAllowlist, !allow.contains(spec.id) { continue }190            if options.deniedCommands.contains(spec.id) { continue }191            add(DocAgentTool(id: spec.id, name: ToolNaming.modelName(spec.id), title: spec.title, summary: spec.summary, input: spec.input,192                             outputSummary: spec.output["description"].stringValue ?? "",193                             scopes: spec.permissions, effect: spec.mutates ? .mutate : (spec.sideEffect == .producesArtifact ? .artifact : .read),194                             timeout: Self.slowCommands.contains(spec.id) ? options.slowTimeout : options.defaultTimeout,195                             cancellable: spec.cancellable, isCommand: true))196        }197        for tool in Self.agentTools(scopes: scopes) where !options.excludedAgentTools.contains(tool.id) { add(tool) }198        if let override = options.timeoutOverride {199            tools = tools.map { var t = $0; if t.timeout != nil { t.timeout = override }; return t }200            byName = Dictionary(uniqueKeysWithValues: tools.map { ($0.name, $0) }); byID = Dictionary(uniqueKeysWithValues: tools.map { ($0.id, $0) })201        }202    }203204    private mutating func add(_ tool: DocAgentTool) {205        precondition(byName[tool.name] == nil, "Two tools map to the model name \(tool.name)")206        tools.append(tool); byName[tool.name] = tool; byID[tool.id] = tool207    }208209    /// Resolves a call by the name the model used. A tool that is not exposed does not exist, whatever the reason.210    public func tool(named name: String) -> DocAgentTool? { byName[name] }211    public func tool(id: String) -> DocAgentTool? { byID[id] }212    public var definitions: [ToolDefinition] { tools.map(\.definition) }213    public var names: [String] { tools.map(\.name) }214215    // MARK: Agent tools216217    static func agentTools(scopes: Set<DocScope>) -> [DocAgentTool] {218        var out: [DocAgentTool] = []219        func tool(_ id: String, _ title: String, _ summary: String, _ input: DocJSON, _ output: String, _ effect: ToolEffect, scopes: [DocScope] = [], timeout: TimeInterval? = 30) {220            out.append(DocAgentTool(id: id, name: ToolNaming.modelName(id), title: title, summary: summary, input: input, outputSummary: output, scopes: scopes,221                                    effect: effect, timeout: timeout, cancellable: true, isCommand: false))222        }223        tool(AgentToolID.planUpdate, "Update plan",224             "Records or updates your plan as a list of steps with statuses. Send the whole list each time. Use it for work with several steps; keep one step in_progress.",225             Schema.object(["steps": Schema.array(Schema.object([226                 "title": Schema.string("What the step does.", maxLength: 300, minLength: 1),227                 "status": Schema.string(nil, enum: ["pending", "in_progress", "done", "skipped", "failed"]),228             ], required: ["title", "status"]), nil, maxItems: 40, minItems: 1)], required: ["steps"]),229             "the recorded plan", .control)230        tool(AgentToolID.askUser, "Ask the user",231             "Asks the person one question and waits for the answer. Use it when the request is ambiguous or when a source or a decision is missing; never guess a citation or a fact.",232             Schema.object(["question": Schema.string("The question.", maxLength: 2000, minLength: 1),233                            "options": Schema.array(Schema.string(nil, maxLength: 300), "Suggested answers.", maxItems: 8)], required: ["question"]),234             "the person's answer", .question, timeout: nil)235        tool(AgentToolID.finish, "Finish",236             "Ends the run with your report. State honestly how much of the document you examined: the application checks it against what you were actually shown, "237                 + "and lists the changes itself from the command engine's records.",238             Schema.object(["summary": Schema.string("What was done and what remains.", maxLength: 8000, minLength: 1),239                            "scope": Schema.string("How much of the document your analysis covers.", enum: ["whole_document", "partial"]),240                            "unresolved": Schema.array(Schema.string(nil, maxLength: 1000), "Open questions or things left undone.", maxItems: 30)], required: ["summary", "scope"]),241             "nothing; the run ends", .control)242        if scopes.contains(.documentAutomation) {243            tool(AgentToolID.workflowExecute, "Run workflow",244                 "Runs a workflow provided by the application, by name. The application decides what the workflow may do.",245                 Schema.object(["workflow": Schema.string("Name of the workflow.", maxLength: 200, minLength: 1), "input": Schema.openObject("Input of the workflow.")], required: ["workflow"]),246                 "the workflow's output", .workflow, scopes: [.documentAutomation], timeout: 300)247        }248        if scopes.contains(.documentRead) {249            tool(AgentToolID.contextOverview, "Document overview",250                 "For long documents: the outline with word counts and a short summary of each section. Summaries are not the text: read a section before editing or judging it.",251                 Schema.object(["maxSections": Schema.integer("Maximum number of sections returned (default 60).", minimum: 1, maximum: 400)]),252                 "sections: [{id, title, level, words, summary}], totalSections, truncated", .read, scopes: [.documentRead], timeout: 120)253            tool(AgentToolID.contextRetrieve, "Retrieve passages",254                 "For long documents: finds the paragraphs most relevant to a query and returns them with their identifiers, their section and the citation keys they contain.",255                 Schema.object(["query": Schema.string("What to look for.", maxLength: 1000, minLength: 1),256                                "limit": Schema.integer("Maximum number of passages (default 8).", minimum: 1, maximum: 30)], required: ["query"]),257                 "passages: [{block, section, text, citations, score}]", .read, scopes: [.documentRead], timeout: 60)258        }259        return out260    }261}262
Files main
Menu

Theme