SPB Git

Repository Public

FileTools.swift 9.7 KB 141 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatAgents/Sources/FileTools.swift3// Description: File tools confined to the folders the user granted: read, list, search, write (no overwrite unless asked).4import Foundation5import LocalChatCore67enum FileLimits {8    static let maxReadBytes = 400_0009    static let maxWriteBytes = 2_000_00010    static let maxEntries = 50011    static let maxSearchFiles = 400012    static let maxMatches = 1001314    static func looksBinary(_ data: Data) -> Bool {15        let head = data.prefix(8192)16        if head.contains(0) { return true }17        return String(data: Data(head), encoding: .utf8) == nil && String(data: Data(head.dropLast(3)), encoding: .utf8) == nil18            && String(data: Data(head), encoding: .isoLatin1).map { s in s.unicodeScalars.filter { $0.value < 9 }.count > head.count / 20 } ?? true19    }20    static func text(_ data: Data) -> String? { String(data: data, encoding: .utf8) ?? String(data: data, encoding: .isoLatin1) }21}2223struct ReadFileTool: AgentTool {24    let risk: ToolRisk = .read25    let definition = ToolDefinition(26        name: "read_file", summary: "Reads a text file inside the folders the user granted. Paths are relative to the first granted folder.",27        parameters: ["type": "object", "properties": [28            "path": ["type": "string"], "start_line": ["type": "integer", "description": "1-based first line, default 1"],29            "max_lines": ["type": "integer", "description": "default 400"]], "required": ["path"]])30    func run(arguments: JSONValue, context: ToolContext) async throws -> ToolOutput {31        let url = try context.jail.resolve(arguments["path"]?.stringValue ?? "")32        var isDir: ObjCBool = false33        guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir) else { throw ToolError("File not found: \(context.jail.display(url))") }34        guard !isDir.boolValue else { throw ToolError("\(context.jail.display(url)) is a directory; use list_directory.") }35        let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() }36        let data = try handle.read(upToCount: FileLimits.maxReadBytes + 1) ?? Data()37        guard !FileLimits.looksBinary(data) else { throw ToolError("\(context.jail.display(url)) is a binary file and cannot be read as text.") }38        let truncatedBytes = data.count > FileLimits.maxReadBytes39        guard let text = FileLimits.text(data.prefix(FileLimits.maxReadBytes)) else { throw ToolError("The file is not valid text.") }40        let lines = text.components(separatedBy: "\n")41        let start = max(1, arguments["start_line"]?.intValue ?? 1), count = max(1, min(2000, arguments["max_lines"]?.intValue ?? 400))42        guard start <= max(1, lines.count) else { throw ToolError("start_line \(start) is beyond the end of the file (\(lines.count) lines).") }43        let slice = lines[(start - 1)..<min(lines.count, start - 1 + count)]44        var out = slice.joined(separator: "\n")45        if start - 1 + count < lines.count || truncatedBytes { out += "\n[… truncated: showing lines \(start)–\(start - 1 + slice.count) of \(truncatedBytes ? "a larger file" : "\(lines.count)")]" }46        return ToolOutput(out)47    }48}4950struct ListDirectoryTool: AgentTool {51    let risk: ToolRisk = .read52    let definition = ToolDefinition(53        name: "list_directory", summary: "Lists the files and folders of a directory inside the granted folders.",54        parameters: ["type": "object", "properties": ["path": ["type": "string", "description": "default: the first granted folder"]]])55    func run(arguments: JSONValue, context: ToolContext) async throws -> ToolOutput {56        let url = try context.jail.resolve(arguments["path"]?.stringValue ?? ".")57        let keys: [URLResourceKey] = [.isDirectoryKey, .fileSizeKey]58        let items: [URL]59        do { items = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: keys, options: []) }60        catch { throw ToolError("Cannot list \(context.jail.display(url)): \(error.localizedDescription)") }61        let sorted = items.sorted { $0.lastPathComponent.localizedStandardCompare($1.lastPathComponent) == .orderedAscending }62        var lines = sorted.prefix(FileLimits.maxEntries).map { item -> String in63            let v = try? item.resourceValues(forKeys: Set(keys))64            return v?.isDirectory == true ? "\(item.lastPathComponent)/" : "\(item.lastPathComponent)  (\(ByteFormat.string(Int64(v?.fileSize ?? 0))))"65        }66        if sorted.count > FileLimits.maxEntries { lines.append("[… \(sorted.count - FileLimits.maxEntries) more entries]") }67        return ToolOutput(lines.isEmpty ? "(empty directory)" : lines.joined(separator: "\n"))68    }69}7071struct SearchFilesTool: AgentTool {72    let risk: ToolRisk = .read73    let definition = ToolDefinition(74        name: "search_files", summary: "Finds files by name pattern (glob, e.g. *.swift) and/or lines containing a text, inside the granted folders.",75        parameters: ["type": "object", "properties": [76            "path": ["type": "string", "description": "directory to search, default: the first granted folder"],77            "name": ["type": "string", "description": "glob on the file name, e.g. *.md"],78            "contains": ["type": "string", "description": "case-insensitive text to find inside files"]]])7980    static func globMatches(_ pattern: String, _ name: String) -> Bool { fnmatch(pattern, name, FNM_CASEFOLD) == 0 }8182    func run(arguments: JSONValue, context: ToolContext) async throws -> ToolOutput {83        let jail = context.jail84        let root = try jail.resolve(arguments["path"]?.stringValue ?? ".")85        let glob = arguments["name"]?.stringValue.flatMap { $0.isEmpty ? nil : $0 }86        let needle = arguments["contains"]?.stringValue.flatMap { $0.isEmpty ? nil : $0 }87        guard glob != nil || needle != nil else { throw ToolError("Give \"name\", \"contains\", or both.") }88        guard let walker = FileManager.default.enumerator(at: root, includingPropertiesForKeys: [.isRegularFileKey, .fileSizeKey], options: [.skipsPackageDescendants]) else {89            throw ToolError("Cannot search \(jail.display(root)).")90        }91        var results: [String] = []; var visited = 0; var capped = false92        while let item = walker.nextObject() as? URL {93            try Task.checkCancellation()94            if [".git", "node_modules", ".build", "DerivedData"].contains(item.lastPathComponent) { walker.skipDescendants(); continue }95            guard (try? item.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile == true else { continue }96            visited += 197            if visited > FileLimits.maxSearchFiles || results.count >= FileLimits.maxMatches { capped = true; break }98            if let glob, !Self.globMatches(glob, item.lastPathComponent) { continue }99            // a symlinked file must still resolve inside the granted folders100            let real = FolderJail.canonical(item)101            guard jail.roots.contains(where: { FolderJail.isInside(real, $0) }) else { continue }102            guard let needle else { results.append(jail.display(real)); continue }103            guard let handle = try? FileHandle(forReadingFrom: real) else { continue }104            let data = (try? handle.read(upToCount: FileLimits.maxReadBytes)) ?? Data(); try? handle.close()105            guard !FileLimits.looksBinary(data), let text = FileLimits.text(data) else { continue }106            for (n, line) in text.components(separatedBy: "\n").enumerated() where line.range(of: needle, options: .caseInsensitive) != nil {107                results.append("\(jail.display(real)):\(n + 1): \(line.trimmingCharacters(in: .whitespaces).prefix(200))")108                if results.count >= FileLimits.maxMatches { break }109            }110        }111        if results.isEmpty { return ToolOutput("No match.") }112        return ToolOutput(results.joined(separator: "\n") + (capped ? "\n[… search stopped at the limit; narrow the query]" : ""))113    }114}115116struct WriteFileTool: AgentTool {117    let risk: ToolRisk = .write118    let definition = ToolDefinition(119        name: "write_file", summary: "Writes a text file inside the granted folders. Refuses to replace an existing file unless overwrite is true.",120        parameters: ["type": "object", "properties": [121            "path": ["type": "string"], "content": ["type": "string"],122            "overwrite": ["type": "boolean", "description": "default false"]], "required": ["path", "content"]])123    func run(arguments: JSONValue, context: ToolContext) async throws -> ToolOutput {124        let url = try context.jail.resolve(arguments["path"]?.stringValue ?? "")125        let content = arguments["content"]?.stringValue ?? ""126        guard content.utf8.count <= FileLimits.maxWriteBytes else { throw ToolError("The content is too large (limit \(ByteFormat.string(Int64(FileLimits.maxWriteBytes)))).") }127        let fm = FileManager.default; var isDir: ObjCBool = false128        let exists = fm.fileExists(atPath: url.path, isDirectory: &isDir)129        if exists && isDir.boolValue { throw ToolError("\(context.jail.display(url)) is a directory.") }130        if exists && arguments["overwrite"]?.boolValue != true {131            throw ToolError("\(context.jail.display(url)) already exists. Pass overwrite: true to replace it.")132        }133        // the parent may be new: it was validated as inside a granted folder by resolve()134        try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)135        // re-check after creating directories (a racing symlink must not move the target outside)136        _ = try context.jail.resolve(url.path)137        try Data(content.utf8).write(to: url, options: .atomic)138        return ToolOutput("\(exists ? "Replaced" : "Created") \(context.jail.display(url)) (\(content.utf8.count) bytes).")139    }140}141
Files main
Menu

Theme