interplane.Get Omega
Read in your language

hop

Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.

Brought by drakestapleton

branch main Branches Tags History

hop / Sources / Cortex.swift

214 lines · 13224 bytes Raw Blame History
1import Foundation
2
3/// Optional: a Cortex knowledge base server of your own. Off unless switched on in the config file.
4/// Nothing here is secret: the access token is fetched at run time by `tokenCommand` and kept in memory only.
5struct CortexConfig: Codable, Hashable {
6 var enabled = false
7 var url = "" // e.g. http://127.0.0.1:8080
8 var host = "" // ssh alias of the computer it runs on; empty = this Mac
9 var remotePort = 0 // its port on that computer (Hop forwards the port in `url` to it)
10 var tokenCommand = "" // prints the access token; run on `host` (or here when host is empty)
11 var readSpaces: [String] = [] // spaces searched
12 var learn = false // save what the agent did, in the background
13 var learnSpace = "" // space those notes go to
14 var lessonSpace = "" // optional: a read space whose entries rank a little higher
15 var contextForClaudeAsk = true // Ask through the Claude CLI also carries matching entries along
16
17 init() {}
18 init(from decoder: Decoder) throws {
19 let c = try decoder.container(keyedBy: CodingKeys.self)
20 enabled = try c.decodeIfPresent(Bool.self, forKey: .enabled) ?? enabled
21 url = try c.decodeIfPresent(String.self, forKey: .url) ?? url
22 host = try c.decodeIfPresent(String.self, forKey: .host) ?? host
23 remotePort = try c.decodeIfPresent(Int.self, forKey: .remotePort) ?? remotePort
24 tokenCommand = try c.decodeIfPresent(String.self, forKey: .tokenCommand) ?? tokenCommand
25 readSpaces = try c.decodeIfPresent([String].self, forKey: .readSpaces) ?? readSpaces
26 learn = try c.decodeIfPresent(Bool.self, forKey: .learn) ?? learn
27 learnSpace = try c.decodeIfPresent(String.self, forKey: .learnSpace) ?? learnSpace
28 lessonSpace = try c.decodeIfPresent(String.self, forKey: .lessonSpace) ?? lessonSpace
29 contextForClaudeAsk = try c.decodeIfPresent(Bool.self, forKey: .contextForClaudeAsk) ?? contextForClaudeAsk
30 }
31}
32
33/// The user's own knowledge base (Cortex). Reads are quick and time-boxed; writes go through a queue on disk and are
34/// sent in the background, so nothing in Hop ever waits on it.
35@MainActor
36final class Cortex: ObservableObject {
37 struct Hit: Identifiable, Hashable { let id: String; let space: String; let kind: String; let title: String; let content: String; var score: Double }
38
39 @Published private(set) var hits: [Hit] = []
40 @Published private(set) var state = "" // short note for the UI when it is unavailable
41 let cfg: CortexConfig
42 private var token: String?
43 private var tokenTask: Task<String?, Never>?
44 private var searchTask: Task<Void, Never>?
45 private var flushing = false
46 private let outboxFile: URL? // tests point this at a throwaway file
47 private var outbox: URL { outboxFile ?? HopConfig.dir.appendingPathComponent("cortex-outbox.jsonl") }
48
49 init(_ cfg: CortexConfig, outbox: URL? = nil) { self.cfg = cfg; outboxFile = outbox }
50
51 // MARK: Access
52 private func bearer() async -> String? {
53 if let token { return token }
54 if let tokenTask { return await tokenTask.value }
55 let host = cfg.host, cmd = cfg.tokenCommand
56 guard !cmd.isEmpty else { state = "Cortex has no tokenCommand set"; return nil }
57 let t = Task<String?, Never> {
58 let box = LineBox()
59 let code: Int32 = await withCheckedContinuation { c in
60 let run = host.isEmpty ? CommandRun(["sh", "-c", cmd]) : Shell.ssh(host: host, cmd)
61 run.start(onLine: { if !$0.hasPrefix("! ") { box.add($0) } }, onExit: { c.resume(returning: $0) })
62 }
63 let v = box.text.trimmingCharacters(in: .whitespacesAndNewlines)
64 return code == 0 && !v.isEmpty && !v.contains(" ") ? v : nil
65 }
66 tokenTask = t
67 token = await t.value
68 tokenTask = nil
69 state = token == nil ? "Cortex is locked or unreachable" : ""
70 return token
71 }
72
73 private func call(_ path: String, query: [URLQueryItem] = [], body: [String: Any]? = nil, timeout: TimeInterval) async -> [String: Any]? {
74 guard cfg.enabled, let tok = await bearer(), var comps = URLComponents(string: cfg.url + path) else { return nil }
75 if !query.isEmpty { comps.queryItems = query }
76 guard let url = comps.url else { return nil }
77 var req = URLRequest(url: url, timeoutInterval: timeout)
78 req.setValue("Bearer \(tok)", forHTTPHeaderField: "Authorization")
79 if let body {
80 req.httpMethod = "POST"
81 req.setValue("application/json", forHTTPHeaderField: "Content-Type")
82 req.httpBody = try? JSONSerialization.data(withJSONObject: body)
83 }
84 guard let (data, resp) = try? await Net.session.data(for: req), let http = resp as? HTTPURLResponse else { return nil }
85 if http.statusCode == 401 || http.statusCode == 403 { token = nil }
86 guard http.statusCode < 300 else { return nil }
87 return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
88 }
89
90 /// True only when the server answered a real request just now. A server that cannot be reached, a token that
91 /// cannot be fetched and a refused login are all false, with the reason in `state`.
92 func check(timeout: TimeInterval = 6) async -> Bool {
93 guard cfg.enabled else { state = "Cortex is not enabled"; return false }
94 guard await bearer() != nil else { if state.isEmpty { state = "Cortex is locked or unreachable" }; return false }
95 let space = cfg.readSpaces.first ?? cfg.learnSpace
96 let r = await call("/api/cortex/search", query: [.init(name: "q", value: "hop"), .init(name: "space", value: space), .init(name: "limit", value: "1")], timeout: timeout)
97 state = r == nil ? "Cortex did not answer at \(cfg.url)" : ""
98 return r != nil
99 }
100
101 /// Fetches the access token ahead of time (the vault takes about two seconds to open).
102 func warm() { if token == nil, tokenTask == nil, cfg.enabled { Task { _ = await bearer() } } }
103
104 // MARK: Search
105 /// The words to search for: three characters or more, common words left out, each once, the longest four.
106 /// Chosen by Omega code (`Omega/hopcore.om`, fn keyw); a text over the core's limit gives none.
107 nonisolated static func keywords(_ q: String) -> [String] {
108 OmegaText.keywords(q)
109 }
110
111 /// The server matches one word at a time, so each keyword is asked separately and the results are ranked here.
112 func search(_ query: String, limit: Int = 8, timeout: TimeInterval = 2.5) async -> [Hit] {
113 let kws = Self.keywords(query)
114 guard cfg.enabled, !kws.isEmpty else { return [] }
115 var found: [String: Hit] = [:]
116 let lessons = cfg.lessonSpace
117 await withTaskGroup(of: [[String: Any]].self) { group in
118 for kw in kws { for space in cfg.readSpaces {
119 group.addTask { [weak self] in
120 let r = await self?.call("/api/cortex/search", query: [.init(name: "q", value: kw), .init(name: "space", value: space), .init(name: "limit", value: "12")], timeout: timeout)
121 return r?["results"] as? [[String: Any]] ?? []
122 }
123 } }
124 for await rows in group {
125 for e in rows where e["retracted"] as? Bool != true {
126 guard let id = e["id"] as? String, found[id] == nil else { continue }
127 let title = e["canonicalName"] as? String ?? "", content = e["content"] as? String ?? ""
128 let space = e["spaceSlug"] as? String ?? "", lt = title.lowercased(), lc = content.lowercased()
129 let s = kws.reduce(0.0) { $0 + (lt.contains($1) ? 3 : 0) + (lc.contains($1) ? 1 : 0) } + (!lessons.isEmpty && space == lessons ? 1.5 : 0)
130 found[id] = Hit(id: id, space: space, kind: e["entityType"] as? String ?? "", title: title, content: content, score: s)
131 }
132 }
133 }
134 return Array(found.values.sorted { $0.score > $1.score }.prefix(limit))
135 }
136
137 /// For the Find screen: searches after typing pauses and publishes the hits.
138 func searchSoon(_ query: String) {
139 searchTask?.cancel()
140 guard cfg.enabled, query.trimmingCharacters(in: .whitespaces).count >= 3 else { hits = []; return }
141 searchTask = Task { [weak self] in
142 try? await Task.sleep(nanoseconds: 350_000_000)
143 if Task.isCancelled { return }
144 let h = await self?.search(query, limit: 4) ?? []
145 if !Task.isCancelled { self?.hits = h }
146 }
147 }
148
149 /// A short block of what Cortex knows about a question, to hand to a model. Empty if nothing useful comes back in time.
150 func context(for question: String, budget: Int = 1400, within seconds: Double = 0.9) async -> String {
151 guard cfg.enabled else { return "" }
152 guard token != nil else { warm(); return "" } // never make a request wait for the vault
153 let work = Task { await self.search(question, limit: 3, timeout: seconds) }
154 let timer = Task { try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000)); work.cancel() }
155 let top = await work.value.filter { $0.score >= 2 }
156 timer.cancel()
157 guard !top.isEmpty else { return "" }
158 let each = budget / top.count
159 return top.map { "[\($0.title)] " + $0.content.replacingOccurrences(of: "\n", with: " ").prefix(each) }.joined(separator: "\n")
160 }
161
162 // MARK: Learning (background)
163 nonisolated static func redact(_ t: String) -> String {
164 var s = t
165 for p in ["(?i)(api[_-]?key|token|secret|password|passwd|bearer)[\"'=:\\s]+[A-Za-z0-9_\\-\\.+/=]{8,}",
166 "sk-[A-Za-z0-9_\\-]{16,}", "gh[pousr]_[A-Za-z0-9]{20,}", "xox[baprs]-[A-Za-z0-9\\-]{10,}", "AKIA[0-9A-Z]{16}",
167 "-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?-----END [A-Z ]*PRIVATE KEY-----"] {
168 s = s.replacingOccurrences(of: p, with: "[redacted]", options: .regularExpression)
169 }
170 return s
171 }
172
173 /// Queues a note. Returns at once; sending happens later and survives Hop restarts.
174 func learn(title: String, content: String, source: String) {
175 guard cfg.enabled, cfg.learn else { return }
176 let entry: [String: Any] = ["title": String(Self.redact(title).prefix(200)), "content": String(Self.redact(content).prefix(6000)),
177 "source": source, "savedAt": ISO8601DateFormatter().string(from: Date())]
178 guard let d = try? JSONSerialization.data(withJSONObject: entry), let line = String(data: d, encoding: .utf8) else { return }
179 let url = outbox
180 if let h = try? FileHandle(forWritingTo: url) { h.seekToEndOfFile(); h.write(Data((line + "\n").utf8)); try? h.close() }
181 else {
182 try? Data((line + "\n").utf8).write(to: url)
183 try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path)
184 }
185 flush()
186 }
187
188 var queued: Int { ((try? String(contentsOf: outbox, encoding: .utf8)) ?? "").split(separator: "\n").count }
189
190 /// Sends queued notes one by one at background priority. Whatever fails stays queued for next time.
191 /// Only while learning is on: with `learn` off nothing queued is sent, and the queue file is left as it is.
192 func flush() {
193 guard cfg.enabled, cfg.learn, !flushing else { return }
194 flushing = true
195 Task(priority: .background) { [weak self] in
196 guard let self else { return }
197 defer { self.flushing = false }
198 let lines = ((try? String(contentsOf: self.outbox, encoding: .utf8)) ?? "").split(separator: "\n").map(String.init)
199 guard !lines.isEmpty else { return }
200 var left: [String] = []
201 for (i, line) in lines.enumerated() {
202 guard let j = try? JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any] else { continue }
203 let value: [String: Any] = ["space": self.cfg.learnSpace, "entityType": "note", "canonicalName": j["title"] ?? "", "content": j["content"] ?? "",
204 "aliases": ["hop"], "metadata": ["repo": "hop", "source": j["source"] ?? "hop", "savedAt": j["savedAt"] ?? ""]]
205 if await self.call("/api/cortex/write", body: ["kind": "entity", "value": value], timeout: 8) == nil { left = Array(lines[i...]); break }
206 }
207 let now = ((try? String(contentsOf: self.outbox, encoding: .utf8)) ?? "").split(separator: "\n").map(String.init)
208 let added = now.count > lines.count ? Array(now[lines.count...]) : [] // queued while we were sending
209 let keep = left + added
210 if keep.isEmpty { try? FileManager.default.removeItem(at: self.outbox) }
211 else { try? (keep.joined(separator: "\n") + "\n").write(to: self.outbox, atomically: true, encoding: .utf8) }
212 }
213 }
214}