SPB Git

Repository Public

Helpers.swift 6.3 KB 143 lines swift

1import Foundation23private let shellFenceLanguages: Set<String> = [4    "", "sh", "bash", "zsh", "fish", "shell", "console", "terminal", "shell-session", "shellsession", "shellscript", "ksh", "dash",5]67/// Extracts candidate commands from the fenced code blocks of a Markdown answer.8///9/// Only untagged blocks and shell-tagged blocks (`sh`, `bash`, `zsh`, `console`, ...) are read.10/// Comment and blank lines are dropped, `$ ` prompts are stripped (and, in a block that uses11/// prompts, lines without one are treated as output), and backslash continuations are joined.12/// The result is plain text: wrap each entry in a ``ProposedCommand`` and pass it through ``ConsentGate``.13public func extractCommands(fromMarkdown markdown: String) -> [String] {14    var commands: [String] = []15    var fence: Substring?16    var isShell = false17    var block: [String] = []1819    func flush() {20        guard isShell else { return }21        let usesPrompts = block.contains { $0.trimmingCharacters(in: .whitespaces).hasPrefix("$ ") }22        var pending: String?23        for raw in block {24            var line = raw.trimmingCharacters(in: .whitespaces)25            if let start = pending {26                line = start + " " + line27                pending = nil28            } else {29                if line.isEmpty || line.hasPrefix("#") { continue }30                if usesPrompts {31                    guard line.hasPrefix("$ ") else { continue }32                    line = String(line.dropFirst(2)).trimmingCharacters(in: .whitespaces)33                }34            }35            if line.hasSuffix("\\") && !line.hasSuffix("\\\\") {36                pending = String(line.dropLast()).trimmingCharacters(in: .whitespaces)37                continue38            }39            if !line.isEmpty { commands.append(line) }40        }41        if let pending, !pending.isEmpty { commands.append(pending) }42    }4344    for rawLine in markdown.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) {45        let trimmed = rawLine.trimmingCharacters(in: .whitespaces)46        if let open = fence {47            if trimmed.hasPrefix(open), trimmed.allSatisfy({ $0 == open.first }) {48                flush()49                fence = nil50            } else {51                block.append(String(rawLine))52            }53        } else if trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") {54            let marker = trimmed.prefix { $0 == trimmed.first }55            let info = trimmed.dropFirst(marker.count).trimmingCharacters(in: .whitespaces).lowercased()56            let language = info.split(whereSeparator: { $0 == " " || $0 == "," || $0 == "{" }).first.map(String.init) ?? ""57            fence = Substring(String(marker))58            isShell = shellFenceLanguages.contains(language)59            block = []60        }61    }62    if fence != nil { flush() }63    return commands64}6566/// An agent command-line tool SP Term knows how to recognise.67public struct AgentCLI: Sendable, Equatable, Hashable, Identifiable, Codable {68    /// Stable identifier.69    public let id: String70    /// Name shown to the user.71    public let displayName: String72    /// Executable file names to look for.73    public let executableNames: [String]7475    public init(id: String, displayName: String, executableNames: [String]) {76        self.id = id77        self.displayName = displayName78        self.executableNames = executableNames79    }80}8182/// An agent CLI found on this machine.83public struct DetectedAgentCLI: Sendable, Equatable, Hashable, Identifiable {84    public let cli: AgentCLI85    /// Absolute path of the executable that was found first in the search order.86    public let executablePath: String87    public var id: String { cli.id }88}8990/// Detects installed agent CLIs by looking for executables in PATH directories.91///92/// Detection only: it never launches a tool, never reads its configuration and never touches its credentials.93public struct AgentCLICatalog: Sendable {94    /// Built-in list of known agent CLIs.95    public static let knownCLIs: [AgentCLI] = [96        AgentCLI(id: "claude", displayName: "Claude Code", executableNames: ["claude"]),97        AgentCLI(id: "codex", displayName: "Codex CLI", executableNames: ["codex"]),98        AgentCLI(id: "gemini", displayName: "Gemini CLI", executableNames: ["gemini"]),99        AgentCLI(id: "aider", displayName: "Aider", executableNames: ["aider"]),100        AgentCLI(id: "opencode", displayName: "OpenCode", executableNames: ["opencode"]),101        AgentCLI(id: "goose", displayName: "Goose", executableNames: ["goose"]),102        AgentCLI(id: "amp", displayName: "Amp", executableNames: ["amp"]),103        AgentCLI(id: "cursor-agent", displayName: "Cursor Agent", executableNames: ["cursor-agent"]),104        AgentCLI(id: "copilot", displayName: "GitHub Copilot CLI", executableNames: ["copilot"]),105        AgentCLI(id: "qwen", displayName: "Qwen Code", executableNames: ["qwen"]),106        AgentCLI(id: "crush", displayName: "Crush", executableNames: ["crush"]),107    ]108109    private let clis: [AgentCLI]110    private let isExecutable: @Sendable (String) -> Bool111112    /// - Parameters:113    ///   - clis: tools to look for.114    ///   - isExecutable: file check, injectable for tests; defaults to `FileManager.isExecutableFile(atPath:)`.115    public init(116        clis: [AgentCLI] = AgentCLICatalog.knownCLIs,117        isExecutable: @escaping @Sendable (String) -> Bool = { FileManager.default.isExecutableFile(atPath: $0) }118    ) {119        self.clis = clis120        self.isExecutable = isExecutable121    }122123    /// Splits a `PATH` value into directories, dropping empty and duplicate entries.124    public static func directories(fromPATH path: String) -> [String] {125        var seen = Set<String>()126        return path.split(separator: ":").map(String.init).filter { !$0.isEmpty && seen.insert($0).inserted }127    }128129    /// Returns the known CLIs that have an executable in `directories` (searched in order).130    public func detect(in directories: [String]) -> [DetectedAgentCLI] {131        clis.compactMap { cli in132            for directory in directories {133                let base = directory.hasSuffix("/") ? String(directory.dropLast()) : directory134                for name in cli.executableNames {135                    let path = base + "/" + name136                    if isExecutable(path) { return DetectedAgentCLI(cli: cli, executablePath: path) }137                }138            }139            return nil140        }141    }142}143
Files main
Menu

Theme