// SPDX-License-Identifier: GPL-3.0-or-later import Foundation // Decode the installed reader's generated JSON payload as data, never executable JavaScript. actor MCPHelpIndex { static let shared = MCPHelpIndex() struct Topic { let id, title, text: String } private struct Book: Decodable { struct Chapter: Decodable { struct Section: Decodable { let id, title: String; let passages: [String] } let page: String let sections: [Section] } let directory: String let chapters: [Chapter] } private let root: URL? private var cached: [Topic]? init(root: URL? = Bundle.main.url(forResource: "ManualLibrary", withExtension: nil)) { self.root = root } private func topics() throws -> [Topic] { if let cached { return cached } guard let root else { throw CocoaError(.fileNoSuchFile) } let contents = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil) let books = [root.appendingPathComponent("book-index.js")] + contents.map { $0.appendingPathComponent("book-index.js") }.filter { FileManager.default.fileExists(atPath: $0.path) } var topics: [Topic] = [] for file in books { let index = try String(contentsOf: file, encoding: .utf8).trimmingCharacters(in: .whitespacesAndNewlines) let prefix = "(globalThis.manualBooks ??= []).push(" guard index.hasPrefix(prefix), index.hasSuffix(");") else { throw CocoaError(.fileReadCorruptFile) } let payload = index.dropFirst(prefix.count).dropLast(2) let book = try JSONDecoder().decode(Book.self, from: Data(payload.utf8)) for chapter in book.chapters { for section in chapter.sections { topics.append(Topic(id: "\(book.directory)/\(chapter.page)#\(section.id)", title: section.title, text: section.passages.joined(separator: "\n\n"))) } } } cached = topics.sorted { $0.id < $1.id } return cached! } func search(_ query: String) throws -> [Topic] { let words = query.lowercased().split(whereSeparator: \.isWhitespace).map(String.init) guard !words.isEmpty else { return [] } return try topics().compactMap { t -> (Int, Topic)? in let title = t.title.lowercased(), body = t.text.lowercased() guard words.allSatisfy({ title.contains($0) || body.contains($0) }) else { return nil } return (words.filter { title.contains($0) }.count + (title == query.lowercased() ? 10 : 0), t) }.sorted { lhs, rhs in lhs.0 == rhs.0 ? lhs.1.id < rhs.1.id : lhs.0 > rhs.0 }.prefix(8).map { $0.1 } } func read(_ id: String) throws -> Topic? { try topics().first { $0.id == id } } @MainActor static func toolResult(_ name: String, arguments args: [String: Any]) async -> [String: Any] { do { switch name { case "search_help": guard args.count == 1, let query = args["query"] as? String, (1...160).contains(query.utf8.count), !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return ["error": "invalid_arguments"] } let topics = try await shared.search(query) return ["result": ["hits": topics.map { ["topic_id": $0.id, "title": $0.title, "excerpt": String($0.text.prefix(240))] }]] case "read_topic": guard args.count == 1, let id = args["topic_id"] as? String, (1...512).contains(id.utf8.count) else { return ["error": "invalid_arguments"] } guard let topic = try await shared.read(id) else { return ["error": "not_found"] } var text = String(decoding: topic.text.utf8.prefix(12 * 1024), as: UTF8.self) while text.utf8.count > 12 * 1024 { text.removeLast() } return ["result": ["topic_id": id, "title": topic.title, "text": text, "truncated": text != topic.text]] default: return ["error": "invalid_arguments"] } } catch { return ["error": "manual_unavailable"] } } }