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 / OmegaCore.swift

182 lines · 9692 bytes Raw Blame History
1import Foundation
2
3/// Hop's matching core is an Omega program, `Omega/hopcore.om`, compiled by the seeded Omega NG compiler into
4/// the helper `hopcore` that sits beside Hop inside the app. This file is the host boundary and nothing more:
5/// it lowercases text, turns each character into one number, sends the cases and reads the answers. Every
6/// decision about what matches, and how well, is made in the Omega code. Contract: Omega/README.md.
7final class OmegaCore: @unchecked Sendable {
8 static let shared = OmegaCore()
9
10 static let magic: UInt64 = 1212568922
11 static let maxQuery = 64, maxName = 184, caseBytes = 2048
12
13 private let lock = NSLock()
14 private var process: Process?
15 private var toCore: Int32 = -1, fromCore: Int32 = -1
16 private var failures = 0
17
18 /// Where the helper lives: beside this executable's real file (the `hop` command is a link to it from
19 /// another folder). A test can point at another build with HOP_CORE.
20 static var path: String {
21 if let p = ProcessInfo.processInfo.environment["HOP_CORE"], !p.isEmpty { return p }
22 return Cli.program.deletingLastPathComponent().appendingPathComponent("hopcore").path
23 }
24
25 /// One case as the core reads it: 256 words. nil when a text is over the core's limits (it is then "no match";
26 /// the core itself refuses over-long input instead of cutting it short).
27 static func encode(query: String, name: String) -> [UInt64]? {
28 let q = Array(query.lowercased()), n = Array(name.lowercased())
29 guard q.count <= maxQuery, n.count <= maxName else { return nil }
30 var ids: [Character: UInt64] = [:]
31 func word(_ c: Character) -> UInt64 {
32 var id: UInt64
33 if c.unicodeScalars.count == 1, let s = c.unicodeScalars.first { id = UInt64(s.value) }
34 else if let k = ids[c] { id = k }
35 else { id = 0x110000 + UInt64(ids.count); ids[c] = id }
36 if c.isLetter || c.isNumber { id |= 1 << 32 }
37 if c.unicodeScalars.allSatisfy({ CharacterSet.whitespaces.contains($0) }) { id |= 1 << 33 }
38 return id
39 }
40 var w = [UInt64](repeating: 0, count: 256)
41 w[0] = magic; w[1] = 1; w[2] = UInt64(q.count); w[3] = UInt64(n.count)
42 for (i, c) in q.enumerated() { w[8 + i] = word(c) }
43 for (i, c) in n.enumerated() { w[72 + i] = word(c) }
44 return w
45 }
46
47 /// The score of every case, in order: nil for "no match", for a refused case, and for every case when the
48 /// core cannot be reached (Hop then shows no app matches rather than guessing).
49 func scores(_ cases: [[UInt64]?]) -> [Int?] {
50 var out = [Int?](repeating: nil, count: cases.count)
51 let live = cases.indices.filter { cases[$0] != nil }
52 var k0 = 0
53 while k0 < live.count { // at most 512 cases a request (the core's limit)
54 let n = min(512, live.count - k0)
55 var body = [UInt8](); body.reserveCapacity(n * Self.caseBytes)
56 for k in 0..<n { for w in cases[live[k0 + k]]! { var le = w.littleEndian; withUnsafeBytes(of: &le) { body.append(contentsOf: $0) } } }
57 guard let reply = request(kind: 1, body: body), reply.count == n * 3 else { return out }
58 for k in 0..<n where reply[3 * k] == 1 { out[live[k0 + k]] = Int(reply[3 * k + 1]) | Int(reply[3 * k + 2]) << 8 }
59 k0 += n
60 }
61 return out
62 }
63
64 /// File-name scoring for paths found on another machine: nil for "no match", for a path or term too long
65 /// for the core (65535 bytes), for more than 64 terms, and when the core cannot be reached. `terms` are used
66 /// as given; an empty term matches nothing.
67 func fileScores(paths: [String], terms: [String]) -> [Int?] {
68 var out = [Int?](repeating: nil, count: paths.count)
69 let t = terms.map { Array($0.utf8) }
70 guard t.count <= 64, t.allSatisfy({ $0.count <= 65535 }) else { return out }
71 func u16(_ v: Int) -> [UInt8] { [UInt8(v & 255), UInt8(v >> 8)] }
72 var head = [UInt8](); for x in t { head += u16(x.count) + x }
73 var i = 0
74 while i < paths.count {
75 var body = [UInt8](), sent: [Int] = []
76 while i < paths.count, sent.count < 16000 {
77 let low = paths[i].lowercased()
78 let lp = Array(low.utf8), name = Array((low as NSString).lastPathComponent.utf8), written = paths[i].utf8.count
79 if lp.count <= 65535, written <= 65535 {
80 if 4 + head.count + body.count + 6 + lp.count + name.count > 1_048_576 { break }
81 body += u16(lp.count) + u16(name.count) + u16(written) + lp + name
82 sent.append(i)
83 }
84 i += 1
85 }
86 guard !sent.isEmpty else { continue }
87 guard let reply = request(kind: 2, body: u16(t.count) + u16(sent.count) + head + body), reply.count == sent.count * 4 else { return out }
88 for (k, j) in sent.enumerated() {
89 let v = Int(reply[4 * k]) | Int(reply[4 * k + 1]) << 8 | Int(reply[4 * k + 2]) << 16 | Int(reply[4 * k + 3]) << 24
90 if v != 0 { out[j] = v - 1_000_000 }
91 }
92 }
93 return out
94 }
95
96 /// A text decision (kind 3): the text, already lowercased, as one word per character with its flags. nil when
97 /// the text is over the core's limit (16384 characters) or the core cannot be reached. `aux` and `extra` are two
98 /// numbers the op uses; `ends` are the characters that close a run (flag 16).
99 func text(op: UInt32, _ chars: [Character], aux: Int = 0, extra: UInt32 = 0, ends: [Int] = []) -> [UInt8]? {
100 guard chars.count <= 16384 else { return nil }
101 var body = [UInt8](); body.reserveCapacity(16 + chars.count * 8)
102 for v in [op, UInt32(chars.count), UInt32(min(aux, Int(Int32.max))), extra] { body += [UInt8(v & 255), UInt8((v >> 8) & 255), UInt8((v >> 16) & 255), UInt8(v >> 24)] }
103 var ids: [Character: UInt32] = [:]
104 let last = Set(ends)
105 for (i, c) in chars.enumerated() {
106 var id: UInt32
107 if c.unicodeScalars.count == 1, let s = c.unicodeScalars.first { id = s.value }
108 else if let k = ids[c] { id = k }
109 else { id = 0x110000 + UInt32(ids.count); ids[c] = id }
110 var f: UInt8 = 0
111 if c.isLetter || c.isNumber { f |= 1 }
112 if c.unicodeScalars.allSatisfy({ CharacterSet.whitespaces.contains($0) }) { f |= 2 }
113 if c.isWhitespace { f |= 4 }
114 if c.unicodeScalars.allSatisfy({ CharacterSet.whitespacesAndNewlines.contains($0) }) { f |= 8 }
115 if last.contains(i) { f |= 16 }
116 body += [UInt8(id & 255), UInt8((id >> 8) & 255), UInt8((id >> 16) & 255), UInt8(id >> 24), f, 0, 0, 0]
117 }
118 return request(kind: 3, body: body)
119 }
120
121 /// One request to the core: 8 bytes (kind, body length), then the body. The answer's body, or nil when the
122 /// core refused it (unknown kind, malformed body) or cannot be reached. Tries a fresh core once.
123 func request(kind: UInt32, body: [UInt8]) -> [UInt8]? {
124 guard body.count <= 1_048_576 else { return nil }
125 var msg = [UInt8](); msg.reserveCapacity(8 + body.count)
126 for v in [kind, UInt32(body.count)] { msg += [UInt8(v & 255), UInt8((v >> 8) & 255), UInt8((v >> 16) & 255), UInt8(v >> 24)] }
127 msg += body
128 lock.lock(); defer { lock.unlock() }
129 for _ in 0..<2 {
130 guard start(), send(msg), let h = receive(8) else { stop(); continue }
131 let status = Int(h[0]) | Int(h[1]) << 8 | Int(h[2]) << 16 | Int(h[3]) << 24
132 let m = Int(h[4]) | Int(h[5]) << 8 | Int(h[6]) << 16 | Int(h[7]) << 24
133 guard m <= 65536, let reply = receive(m) else { stop(); continue }
134 failures = 0
135 return status == 0 ? reply : nil
136 }
137 return nil
138 }
139
140 private func send(_ bytes: [UInt8]) -> Bool {
141 var sent = 0
142 while sent < bytes.count {
143 let k = bytes.withUnsafeBytes { write(toCore, $0.baseAddress! + sent, min(bytes.count - sent, 1 << 16)) }
144 if k <= 0 { return false }
145 sent += k
146 }
147 return true
148 }
149
150 private func receive(_ n: Int) -> [UInt8]? {
151 var reply = [UInt8](repeating: 0, count: n), got = 0
152 while got < n {
153 let k = reply.withUnsafeMutableBytes { read(fromCore, $0.baseAddress! + got, n - got) }
154 if k <= 0 { return nil }
155 got += k
156 }
157 return reply
158 }
159
160 private func start() -> Bool {
161 if let p = process, p.isRunning { return true }
162 stop()
163 guard failures < 8, FileManager.default.isExecutableFile(atPath: Self.path) else { return false }
164 signal(SIGPIPE, SIG_IGN)
165 let p = Process(), inPipe = Pipe(), outPipe = Pipe()
166 p.executableURL = URL(fileURLWithPath: Self.path)
167 p.standardInput = inPipe; p.standardOutput = outPipe; p.standardError = FileHandle.nullDevice
168 do { try p.run() } catch { failures += 1; return false }
169 toCore = dup(inPipe.fileHandleForWriting.fileDescriptor)
170 fromCore = dup(outPipe.fileHandleForReading.fileDescriptor)
171 try? inPipe.fileHandleForWriting.close(); try? outPipe.fileHandleForReading.close()
172 process = p
173 return toCore >= 0 && fromCore >= 0
174 }
175
176 private func stop() {
177 if toCore >= 0 { close(toCore); toCore = -1 }
178 if fromCore >= 0 { close(fromCore); fromCore = -1 }
179 if let p = process { if p.isRunning { p.terminate() }; failures += 1 }
180 process = nil
181 }
182}