Publish VCC Plus OSS source distribution for 3.6.2 build 60
This commit is contained in:
commit
c652a5276d
1192 files changed
+272368
No files matched your search
@@ -0,0 +1,169 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import AppKit
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
|
||||
/// A separate grant with its own listener and no reference to a workspace or emulator.
|
||||
@MainActor
|
||||
final class MCPArchiveAccess: ObservableObject {
|
||||
static let shared = MCPArchiveAccess(catalog: .shared)
|
||||
private let catalog: ArchiveLibraryCatalog
|
||||
private var listener: MCPTransport?
|
||||
private var secret: String?
|
||||
private var pending: UUID?
|
||||
private var panel: NSPanel?
|
||||
@Published private(set) var grantFile: MCPGrantFile?
|
||||
@Published fileprivate var message: String?
|
||||
|
||||
init(catalog: ArchiveLibraryCatalog) { self.catalog = catalog }
|
||||
|
||||
func show() {
|
||||
if let panel {
|
||||
panel.makeKeyAndOrderFront(nil)
|
||||
return
|
||||
}
|
||||
let window = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 540, height: 380),
|
||||
styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)
|
||||
window.title = "Archive Search Connection"
|
||||
window.isReleasedWhenClosed = false
|
||||
window.contentMinSize = NSSize(width: 360, height: 230)
|
||||
let content = NSHostingView(rootView: ScrollView { MCPArchiveAccessView(access: self) })
|
||||
content.sizingOptions = []
|
||||
window.contentView = content
|
||||
window.center()
|
||||
panel = window
|
||||
window.makeKeyAndOrderFront(nil)
|
||||
}
|
||||
|
||||
fileprivate func chooseGrant() {
|
||||
let picker = NSSavePanel()
|
||||
picker.nameFieldStringValue = "VCC Plus OSS Archive Search.json"
|
||||
picker.title = "Save Archive Search Connection"
|
||||
picker.message = "Choose a new file for the assistant that will search the Archive."
|
||||
guard picker.runModal() == .OK, let url = picker.url else { return }
|
||||
Task {
|
||||
do { try await connect(at: url) }
|
||||
catch is CancellationError {}
|
||||
catch { message = "Could not save the connection. " + error.localizedDescription }
|
||||
}
|
||||
}
|
||||
|
||||
func connect(at url: URL) async throws {
|
||||
let ticket = UUID()
|
||||
pending = ticket
|
||||
defer { if pending == ticket { pending = nil } }
|
||||
let token = UUID().uuidString + UUID().uuidString
|
||||
let handler: MCPTransport.Handler = { [weak self] bytes in
|
||||
guard let self else { return Self.denied }
|
||||
return await self.reply(to: bytes, connection: token)
|
||||
}
|
||||
let (server, file) = try await Task.detached(priority: .userInitiated) {
|
||||
let server = try MCPTransport(handler: handler)
|
||||
let bytes = try JSONSerialization.data(withJSONObject: ["kind": "archive", "version": 2, "token": token,
|
||||
"socket": server.unixPath, "port": Int(server.port)])
|
||||
return (server, try MCPGrantFile(create: url, data: bytes))
|
||||
}.value
|
||||
guard pending == ticket else {
|
||||
await Task.detached { server.stop(); file.remove() }.value
|
||||
throw CancellationError()
|
||||
}
|
||||
revoke()
|
||||
listener = server
|
||||
secret = token
|
||||
grantFile = file
|
||||
message = nil
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func revoke() -> Task<Void, Never> {
|
||||
pending = nil
|
||||
secret = nil
|
||||
let old = listener, file = grantFile
|
||||
listener = nil
|
||||
grantFile = nil
|
||||
message = nil
|
||||
return Task.detached { old?.stop(); file?.remove() }
|
||||
}
|
||||
|
||||
private nonisolated static let denied = Data(#"{"error":"access_denied"}"#.utf8)
|
||||
|
||||
private func reply(to data: Data, connection: String) async -> Data {
|
||||
guard let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
|
||||
secret == connection, request["token"] as? String == connection else { return Self.denied }
|
||||
let response: [String: Any]
|
||||
if Self.integer(request["version"]) != 1 {
|
||||
response = ["error": "version_mismatch"]
|
||||
} else if let tool = request["tool"] as? String, let args = request["arguments"] as? [String: Any] {
|
||||
do { response = try await perform(tool, args) }
|
||||
catch ArchiveLibraryError.input(let message) { response = ["error": message] }
|
||||
catch { response = ["error": "archive_index_unavailable"] }
|
||||
} else {
|
||||
response = ["error": "invalid_arguments"]
|
||||
}
|
||||
// The user can revoke or replace the grant while SQLite serves an asynchronous query.
|
||||
guard secret == connection else { return Self.denied }
|
||||
return (try? JSONSerialization.data(withJSONObject: response)) ?? Data(#"{"error":"encoding_error"}"#.utf8)
|
||||
}
|
||||
|
||||
private func perform(_ tool: String, _ args: [String: Any]) async throws -> [String: Any] {
|
||||
switch tool {
|
||||
case "search_archive":
|
||||
guard Set(args.keys).isSubset(of: ["query", "category", "limit", "offset"]),
|
||||
let query = args["query"] as? String, !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
|
||||
query.unicodeScalars.count <= 256,
|
||||
let limit = Self.integer(args["limit"] ?? 10), (1...50).contains(limit),
|
||||
let offset = Self.integer(args["offset"] ?? 0), (0...250_000).contains(offset)
|
||||
else { return ["error": "invalid_arguments"] }
|
||||
let category = args["category"] as? String
|
||||
if args["category"] != nil {
|
||||
guard let category, !category.isEmpty, category.unicodeScalars.count <= 512 else {
|
||||
return ["error": "invalid_arguments"]
|
||||
}
|
||||
}
|
||||
let hits = try await catalog.search(query: query, collection: category, limit: limit, offset: offset)
|
||||
var result: [String: Any] = ["results": hits.map(Self.publicCitation), "offset": offset]
|
||||
if hits.count == limit && offset + limit <= 250_000 { result["next_offset"] = offset + limit }
|
||||
return ["result": result]
|
||||
case "get_archive_citation":
|
||||
guard args.count == 1, let id = args["citation_id"] as? String, !id.isEmpty, id.utf8.count <= 128
|
||||
else { return ["error": "invalid_arguments"] }
|
||||
guard let hit = try await catalog.citation(id: id) else { return ["error": "citation_unavailable"] }
|
||||
return ["result": Self.publicCitation(hit)]
|
||||
default:
|
||||
return ["error": "access_denied"]
|
||||
}
|
||||
}
|
||||
|
||||
private static func integer(_ value: Any?) -> Int? {
|
||||
guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(),
|
||||
!CFNumberIsFloatType(number) else { return nil }
|
||||
return Int(number.stringValue)
|
||||
}
|
||||
|
||||
private static func publicCitation(_ hit: ArchiveHit) -> [String: Any] {
|
||||
var value: [String: Any] = ["citation_id": hit.id, "document_sha256": hit.document.id,
|
||||
"title": hit.document.title, "collection": hit.document.collection, "citation": hit.citation,
|
||||
"source_url": hit.sourceURL.absoluteString, "locator": hit.locator, "ocr": hit.ocr]
|
||||
if let page = hit.page { value["pdf_page"] = page }
|
||||
if let member = hit.document.memberPath { value["member_path"] = member }
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
private struct MCPArchiveAccessView: View {
|
||||
@ObservedObject var access: MCPArchiveAccess
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Connect a local assistant to search the Archive and look up citations. Its model provider may receive your queries and the public references it finds.").fixedSize(horizontal: false, vertical: true)
|
||||
if let file = access.grantFile {
|
||||
Label("Archive search is available to this connection.", systemImage: "link")
|
||||
Button("Revoke Archive Access") { access.revoke() }
|
||||
Divider()
|
||||
MCPChatGPTSetup(grantURL: file.url, firstPrompt: "Use Archive Search to find a reference to JOYSTK and give me its original source and page.")
|
||||
} else {
|
||||
Button("Save Archive Search Connection…") { access.chooseGrant() }
|
||||
}
|
||||
if let message = access.message { Text(message).font(.callout).textSelection(.enabled) }
|
||||
}.padding().frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user