SPB Git

Repository Public License

main.swift 16.9 KB 315 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX OS Automation9// File             : Packages/ORIXServices/Sources/orixctl/main.swift10// Description      : Command-line front end to the same services as the app:11//                    tools, agent runs, workflows, runs, providers, skills, and12//                    the headless scheduler loop.13// Module           : orixctl14// Repository       : https://git.spboucher.ai/orix-automation15// Created          : 2026-11-2116// Last Modified    : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : Proprietary, all rights reserved (see license file)83// License File     : LICENSE84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation92import ORIXCore93import ORIXServices94import ORIXWorkflowEngine9596struct Args {97    var positional: [String] = []98    var options: [String: [String]] = [:]99    init(_ raw: [String]) {100        var i = 0101        while i < raw.count {102            let a = raw[i]103            if a.hasPrefix("--") {104                let name = String(a.dropFirst(2))105                if i + 1 < raw.count, !raw[i + 1].hasPrefix("--") { options[name, default: []].append(raw[i + 1]); i += 1 }106                else { options[name, default: []].append("true") }107            } else { positional.append(a) }108            i += 1109        }110    }111    func value(_ name: String) -> String? { options[name]?.last }112    func flag(_ name: String) -> Bool { options[name] != nil }113    func values(_ name: String) -> [String] { options[name] ?? [] }114}115116func fail(_ message: String) -> Never { FileHandle.standardError.write(Data(("orixctl: " + message + "\n").utf8)); exit(1) }117118let usage = """119orixctl — ORIX OS Automation from the command line120121  orixctl tools [--family F] [--markdown]122  orixctl permissions123  orixctl providers [--test provider:model]124  orixctl agent run --objective TEXT --dir FOLDER [--mode quick|guided|autonomous|review] [--model provider:model]125                    [--agent NAME] [--access none|read|readWrite] [--approve all] [--expect kind:path[:text]] [--max-cost USD]126  orixctl workflow templates | list | validate FILE | save FILE | install SLUG | show ID127  orixctl workflow run ID [--param name=json] [--dry-run] [--accept-permissions] [--approve all] [--mode MODE]128  orixctl workflow draft --objective TEXT [--model provider:model]129  orixctl runs [--limit N] | orixctl run ID [--events]130  orixctl skills131  orixctl daemon                      run the scheduler until interrupted (what the background agent does)132133Global: --data DIR (data folder; default is the app's), --dev-keys (Debug builds: take provider keys from ORIX_DEV_*_API_KEY)134Without --approve all, anything that needs approval is left unanswered and does not run.135"""136137func modelRef(_ s: String?) -> ModelRef? {138    guard let s, let i = s.firstIndex(of: ":") else { return nil }139    return ModelRef(provider: ProviderID(rawValue: String(s[..<i])), model: String(s[s.index(after: i)...]))140}141142func printRun(_ services: ORIXServices, _ id: String, events: Bool) async {143    guard let r = try? await services.store.run(id: id) else { fail("no run \(id)") }144    if events {145        for e in (try? await services.store.events(runID: id, afterSeq: 0, limit: 5000)) ?? [] {146            print("\(e.seq)\t\(e.kind.rawValue)\t\(e.stepID ?? "-")\t\(e.text.replacingOccurrences(of: "\n", with: " ⏎ ").prefix(200))")147        }148    }149    if let receipt = try? await services.store.receipt(runID: id) { print(receipt.markdown()) }150    else { print("\(r.id)  \(r.status.rawValue)  \(r.title)") }151}152153func autoApprove(_ services: ORIXServices) {154    Task {155        for await pending in services.approvals.updates() {156            for p in pending {157                FileHandle.standardError.write(Data("approve[--approve all]: \(p.access.toolID) \(p.access.tier.label) — \(p.access.summary)\n".utf8))158                await services.approvals.resolve(id: p.id, response: .approveOnce)159            }160        }161    }162    Task {163        for await items in services.interaction.updates() {164            for item in items {165                switch item {166                case .plan(let p): await services.interaction.review(planID: p.id, .approved)167                case .question(let q): await services.interaction.answer(questionID: q.id, nil)168                }169            }170        }171    }172}173174@Sendable func main() async {175    let args = Args(Array(CommandLine.arguments.dropFirst()))176    guard let command = args.positional.first else { print(usage); exit(0) }177    var options = ServiceOptions()178    options.interactive = args.flag("approve")179    options.allowDevelopmentCredentials = args.flag("dev-keys")180    let paths = args.value("data").map { ORIXPaths(root: URL(fileURLWithPath: $0)) } ?? .default181    let services: ORIXServices182    do { services = try await ORIXServices.bootstrap(paths: paths, options: options) } catch { fail("cannot start: \(error.localizedDescription)") }183    if args.value("approve") == "all" { autoApprove(services) }184    let sub = args.positional.dropFirst().first185186    switch command {187    case "tools" where args.flag("markdown"):188        // Reference documentation generated from the live manifests, so it cannot drift from the code.189        let manifests = await services.executor.manifests()190        print("<!--\nORIX OS Automation\nFile: docs/api/tools.md\nAuthor: Simon-Pierre Boucher\nContact: contact@spboucher.ai\n-->\n# Tool reference\n")191        print("Generated by `orixctl tools --markdown` from the registered tool manifests (\(manifests.count) tools). Do not edit by hand.\n")192        for family in Array(Set(manifests.map(\.family))).sorted() {193            print("## \(family)\n")194            for m in manifests where m.family == family {195                print("### `\(m.identifier)`\n\n\(m.summary)\n")196                var facts = ["side effect: \(m.sideEffect.rawValue)", "default tier: \(m.defaultTier.rawValue)", "timeout: \(Int(m.defaultTimeoutSeconds)) s"]197                if m.supportsDryRun { facts.append("dry run: yes") }198                if m.idempotent { facts.append("idempotent") }199                if m.outputIsUntrusted { facts.append("output is untrusted data") }200                if !m.macPermissions.isEmpty { facts.append("macOS permission: " + m.macPermissions.map(\.rawValue).joined(separator: ", ")) }201                print(facts.map { "- \($0)" }.joined(separator: "\n") + "\n")202                let props = m.inputSchema.raw["properties"]?.objectValue ?? [:]203                let required = Set(m.inputSchema.raw["required"]?.arrayValue?.compactMap(\.stringValue) ?? [])204                if !props.isEmpty {205                    print("| Argument | Type | Required | Description |\n|---|---|---|---|")206                    for k in props.keys.sorted() {207                        let t = props[k]?["type"]?.stringValue ?? (props[k]?["type"]?.arrayValue?.compactMap(\.stringValue).joined(separator: " or ") ?? "any")208                        let d = (props[k]?["description"]?.stringValue ?? "").replacingOccurrences(of: "|", with: "\\|").replacingOccurrences(of: "\n", with: " ")209                        print("| `\(k)` | \(t) | \(required.contains(k) ? "yes" : "") | \(d) |")210                    }211                    print("")212                }213                let outs = (m.outputSchema.raw["properties"]?.objectValue ?? [:]).keys.sorted()214                if !outs.isEmpty { print("Output fields: " + outs.map { "`\($0)`" }.joined(separator: ", ") + "\n") }215            }216        }217    case "tools":218        for m in await services.executor.manifests() where args.value("family") == nil || m.family == args.value("family") {219            print("\(m.identifier)\t\(m.sideEffect.rawValue)\ttier \(m.defaultTier.rawValue)\t\(m.summary.prefix(90))")220        }221    case "permissions":222        for (p, s) in services.permissionSnapshot().sorted(by: { $0.key.rawValue < $1.key.rawValue }) { print("\(p.rawValue)\t\(s.rawValue)") }223    case "providers":224        for p in ProviderID.all { print("\(p.rawValue)\tkey: \(await services.providers.keySource(for: p).rawValue)") }225        if let ref = modelRef(args.value("test")) {226            let r = await services.providers.test(ref)227            print("\(ref.displayString): \(r.ok ? "ok" : "FAILED") in \(r.latencyMs) ms" + (r.message.map { " — \($0)" } ?? ""))228            if !r.ok { exit(2) }229        }230    case "agent":231        guard sub == "run", let objective = args.value("objective"), let dir = args.value("dir") else { fail("usage: agent run --objective TEXT --dir FOLDER") }232        var req = AgentRunRequest(objective: objective, workingDirectory: dir)233        req.mode = ExecutionMode(rawValue: args.value("mode") ?? "autonomous") ?? .autonomous234        req.model = modelRef(args.value("model"))235        req.agent = args.value("agent") ?? "general"236        req.workspaceAccess = WorkspaceAccess(rawValue: args.value("access") ?? "readWrite") ?? .readWrite237        if let c = args.value("max-cost").flatMap(Double.init) { var b = Budget.standard; b.maxCostUSD = c; req.budget = b }238        for e in args.values("expect") {239            let parts = e.split(separator: ":", maxSplits: 2).map(String.init)240            guard parts.count >= 2 else { fail("--expect kind:path[:text]") }241            req.expectations.append(Expectation(kind: parts[0], path: parts[1], text: parts.count > 2 ? parts[2] : nil))242        }243        do {244            let id = try await services.runs.startAgentRun(req)245            Task { for await u in services.runs.live.subscribe(runID: id) {246                if case .toolFinished(let c, let r) = u { FileHandle.standardError.write(Data("  tool \(c.toolID): \(r.status.rawValue) — \(r.summary.prefix(120))\n".utf8)) }247            } }248            let final = await services.runs.wait(runID: id)249            await printRun(services, id, events: false)250            exit(final?.status == .succeeded ? 0 : 3)251        } catch { fail((error as? LocalizedError)?.errorDescription ?? error.localizedDescription) }252    case "workflow":253        do {254            switch sub {255            case "templates": for b in BuiltInWorkflows.all() { print("\(b.slug)\t\(b.title)\t\(b.summary.prefix(80))") }256            case "list": for w in await services.workflows.list() { print("\(w.id)\tv\(w.currentVersion)\t\(w.name)") }257            case "validate", "save":258                guard let file = args.positional.dropFirst(2).first, let src = try? String(contentsOfFile: file, encoding: .utf8) else { fail("give a readable file") }259                let format: WorkflowFormat = file.hasSuffix(".json") ? .json : .yaml260                let (_, diags) = await services.workflows.diagnose(src, format: format)261                for d in diags { print("\(d.severity)\tline \(d.line)\t\(d.stepID ?? "-")\t\(d.message)") }262                if diags.contains(where: { $0.severity == .error }) { exit(2) }263                if sub == "save" { let s = try await services.workflows.save(source: src, format: format); print("saved \(s.id) v\(s.version)") } else { print("valid") }264            case "install":265                guard let slug = args.positional.dropFirst(2).first else { fail("give a template slug") }266                let s = try await services.workflows.installBuiltIn(slug: slug); print("installed \(s.id) v\(s.version)")267            case "show":268                guard let id = args.positional.dropFirst(2).first else { fail("give a workflow id") }269                print(try await services.workflows.source(workflowID: id))270            case "draft":271                guard let objective = args.value("objective") else { fail("--objective TEXT") }272                let r = try await services.workflows.generate(objective: objective, model: modelRef(args.value("model")))273                print(r.source)274                for d in r.diagnostics { FileHandle.standardError.write(Data("\(d.severity) line \(d.line): \(d.message)\n".utf8)) }275            case "run":276                guard let id = args.positional.dropFirst(2).first else { fail("give a workflow id") }277                var req = WorkflowRunRequest(workflowID: id)278                req.dryRun = args.flag("dry-run")279                req.mode = ExecutionMode(rawValue: args.value("mode") ?? "guided") ?? .guided280                for p in args.values("param") {281                    guard let i = p.firstIndex(of: "=") else { fail("--param name=json") }282                    let raw = String(p[p.index(after: i)...])283                    req.parameters[String(p[..<i])] = (try? JSONValue.parse(raw)) ?? .string(raw)284                }285                if args.flag("accept-permissions") { try await services.workflows.acceptPermissions(workflowID: id, parameters: req.parameters) }286                let runID = try await services.workflows.startRun(req)287                let final = await services.runs.wait(runID: runID)288                await printRun(services, runID, events: args.flag("events"))289                exit(final?.status == .succeeded ? 0 : 3)290            default: fail("unknown workflow command")291            }292        } catch { fail((error as? LocalizedError)?.errorDescription ?? error.localizedDescription) }293    case "runs":294        for r in (try? await services.store.runs(limit: Int(args.value("limit") ?? "20") ?? 20)) ?? [] {295            print("\(r.id)\t\(r.status.rawValue)\t\(r.kind)\t\(r.title.prefix(60))")296        }297    case "run":298        guard let id = sub else { fail("give a run id") }299        await printRun(services, id, events: args.flag("events"))300    case "skills":301        for s in await services.skills.installed() { print("\(s.id)\t\(s.package.manifest.version)\t\(s.enabled ? "enabled" : "disabled")\t\(s.package.manifest.summary.prefix(70))") }302    case "daemon":303        _ = await services.runs.recoverInterrupted(startedAt: services.processStart)304        await services.workflows.startScheduler(owner: "orixctl-\(ProcessInfo.processInfo.processIdentifier)")305        print("scheduler running; interrupt to stop")306        while true { try? await Task.sleep(nanoseconds: 3_600_000_000_000) }307    default:308        print(usage); exit(64)309    }310    exit(0)311}312313Task { await main() }314RunLoop.main.run()315
Files main
Menu

Theme