diff --git a/Sources/Library.swift b/Sources/Library.swift index 38aa22a..5b23064 100644 --- a/Sources/Library.swift +++ b/Sources/Library.swift @@ -422,6 +422,57 @@ enum ChatWebLookup { } +enum KnowledgeInventory { + static let toolName = "list_knowledge_sources" + + static func matches(_ prompt: String) -> Bool { + let words = Set(prompt.lowercased().split { !$0.isLetter }) + let inventory = !words.isDisjoint(with: ["list", "show", "browse", "what", "which"]) + let subjects = !words.isDisjoint(with: ["topics", "documents", "files", "sources", "contents", "indexed"]) + return words.contains("knowledge") && inventory && subjects + } + + static func sources(client: any MCPToolClient) async throws -> [String] { + struct Page: Decodable { + let sources: [String] + let total: Int + } + struct Response: Decodable { + struct Content: Decodable { let text: String? } + let structuredContent: Page? + let content: [Content]? + let isError: Bool? + } + var sources: [String] = [] + var seen = Set() + var expectedTotal: Int? + repeat { + try Task.checkCancellation() + let arguments = try JSONEncoder().encode(["offset": sources.count, "limit": 200]) + let data = try await client.callTool(toolName, argumentsJSON: arguments) + let decoder = JSONDecoder() + let response = try decoder.decode(Response.self, from: data) + guard response.isError != true else { throw StudioError("The knowledge server could not list its sources.") } + let page = response.structuredContent ?? response.content?.compactMap { item in + item.text.flatMap { try? decoder.decode(Page.self, from: Data($0.utf8)) } + }.first + guard let page, page.total >= 0, page.total == (expectedTotal ?? page.total), + sources.count + page.sources.count <= page.total, + !page.sources.isEmpty || sources.count == page.total else { + throw StudioError("The knowledge inventory changed while it was being read. Try again.") + } + for source in page.sources { + guard seen.insert(source).inserted else { + throw StudioError("The knowledge inventory returned a duplicate page. Try again.") + } + sources.append(source) + } + expectedTotal = page.total + } while sources.count < (expectedTotal ?? 0) + return sources + } +} + enum ExternalKnowledgeSearch { struct Result { let reference: String diff --git a/Sources/StudioModel.swift b/Sources/StudioModel.swift index bb73d80..0c23bfc 100644 --- a/Sources/StudioModel.swift +++ b/Sources/StudioModel.swift @@ -115,6 +115,10 @@ final class StudioModel: ObservableObject { let text = prompt.trimmingCharacters(in: .whitespacesAndNewlines) let tag = model.trimmingCharacters(in: .whitespacesAndNewlines) guard !running, !text.isEmpty else { return } + if KnowledgeInventory.matches(text) { + sendKnowledgeInventory(text) + return + } guard mlxOnly ? !mlxPath.isEmpty : !tag.isEmpty else { status = mlxOnly ? "Choose an MLX model folder in Settings." : "Choose a model in Settings." return @@ -137,7 +141,12 @@ final class StudioModel: ObservableObject { let attachment = toolAttachment let chat = try selected ?? create(String(text.prefix(48))) let user = Message(role: .user, content: text) - let recent = Array(messages.suffix(32)) + let recent = messages.suffix(32).map { message in + guard message.backend.hasPrefix("Knowledge Inventory · ") else { return message } + var summary = message + summary.content = String(message.content.prefix(while: { !$0.isNewline })) + return summary + } var systemParts = instructions.isEmpty ? [] : [instructions] if let skill = snippets.first(where: { $0.id == activeSkill && $0.kind == .skill }) { systemParts.append("Selected skill: \(skill.title)\n\(skill.content)") @@ -492,6 +501,50 @@ final class StudioModel: ObservableObject { } func cancelManagement() { management?.cancel() } + private func sendKnowledgeInventory(_ text: String) { + do { + let store = try database() + let chat = try selected ?? create(String(text.prefix(48))) + let user = Message(role: .user, content: text) + try store.save(user, in: chat) + messages.append(user) + prompt = "" + status = "" + webStatus = "" + webDiagnostics = [] + webSearchLink = nil + knowledgeSources = [] + knowledgeStatus = "Reading the knowledge inventory…" + running = true + generation = Task { + defer { running = false; generation = nil } + do { + let connections = mcpOperations.compactMap { id, operation in + mcpConnections[id]?.progress == "Connecting…" && id != .web ? operation.task : nil + } + for connection in connections { await connection.value } + try Task.checkCancellation() + guard let server = activeToolsets.first(where: { + $0.toolset.tools.contains { $0.name == KnowledgeInventory.toolName } + }) else { + throw StudioError("No connected knowledge server exposes an inventory. Check Toolbox → MCP Servers and reconnect the local knowledge server.") + } + let sources = try await KnowledgeInventory.sources(client: server.toolset.client) + try Task.checkCancellation() + let content = sources.isEmpty ? "The connected knowledge base has no indexed sources." : + "The knowledge base contains \(sources.count.formatted()) indexed sources. The inventory lists document paths.\n\n" + + sources.map { "• " + $0 }.joined(separator: "\n") + let reply = Message(role: .assistant, content: content, backend: "Knowledge Inventory · " + server.toolset.name) + try store.save(reply, in: chat) + if selected == chat { messages.append(reply) } + knowledgeStatus = "Knowledge inventory · \(sources.count.formatted()) sources." + } catch { + knowledgeStatus = Task.isCancelled ? "Knowledge inventory stopped." : error.localizedDescription + } + } + } catch { status = error.localizedDescription } + } + func selectMLXModel(_ path: String) { let defaults = UserDefaults.standard defaults.set(path, forKey: "mlxPath") diff --git a/Tests/StudioTests.swift b/Tests/StudioTests.swift index 1e2098a..f9a0ee4 100644 --- a/Tests/StudioTests.swift +++ b/Tests/StudioTests.swift @@ -867,6 +867,33 @@ final class ConnectedChatTests: XCTestCase { XCTAssertEqual(try Store(url: url).conversations().map(\.id), [second]) } + @MainActor + func testLiveKnowledgeInventoryAnswersWithoutModel() async throws { + guard let path = ProcessInfo.processInfo.environment["AISTUDIO_TEST_REAL_MCP_CONFIG"] else { + throw XCTSkip("Set a local knowledge MCP configuration to verify its inventory.") + } + let config = try MCPServerConfiguration.File.read(URL(fileURLWithPath: path)) + let profile = try XCTUnwrap(config.mcpServers["local-knowledge"]) + let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) + defer { try? FileManager.default.removeItem(at: folder) } + let studio = StudioModel() + studio.open(databaseURL: folder.appending(path: "studio.sqlite")) + studio.connectMCP(.profile("local-knowledge"), name: "local-knowledge") { try profile.makeClient() } + studio.prompt = "List all topics in our knowledge base" + studio.send(endpoint: "", model: "", mlxPath: "", thinking: .off, failover: false, + mlxOnly: false, compatible: false, recall: false, useDocuments: false, + instructions: "", settings: GenerationSettings()) + let deadline = ContinuousClock.now + .seconds(30) + while studio.running && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(50)) } + XCTAssertFalse(studio.running) + let reply = try XCTUnwrap(studio.messages.last) + XCTAssertEqual(reply.role, .assistant, studio.knowledgeStatus) + XCTAssertEqual(reply.backend, "Knowledge Inventory · local-knowledge") + let listed = reply.content.split(separator: "\n").filter { $0.hasPrefix("• ") } + XCTAssertGreaterThan(listed.count, 200) + XCTAssertEqual(Set(listed).count, listed.count) + } + func testLiveLocalKnowledgeSearch() async throws { guard let path = ProcessInfo.processInfo.environment["AISTUDIO_TEST_REAL_MCP_CONFIG"] else { throw XCTSkip("Set the installed MCP configuration to verify knowledge search.")