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

391 lines · 24328 bytes Raw Blame History
1import AppKit
2
3/// The developer side of `hop` in a terminal: ask a model, read what was copied, open an app by Hop's own
4/// matching, see Hop's state, put `hop` on the PATH, and `--json` for scripts. Answers and items go to standard
5/// output and nothing else does: notes, who answered and errors go to standard error, so a pipe gets only the result.
6/// Exit status: 0 done, 1 nothing found or it failed, 2 the command was not written correctly.
7extension Cli {
8 /// Every command: its arguments, one line on what it does, and what else is worth knowing.
9 static let guide: [(name: String, args: String, what: String, more: String)] = [
10 ("show", "", "open Hop's box, starting Hop if it is not running",
11 "hop typed alone in a terminal does the same. Hop has no Dock icon of its own while it runs, only the one in the menu bar. Opening Hop.app while Hop runs also opens the box; opening it when Hop is not running only starts Hop."),
12 ("ask", "[-m <model>] [question]", "ask the model Hop's Ask uses; the answer streams to standard output",
13 "Text piped in is added under the question (git diff | hop ask review this). Without -m the model is chosen as on the Ask screen: your own model first when it answers. The request goes where that model's settings send it. Who answered is said on standard error. Each question stands alone: Hop keeps no conversation and adds no Cortex notes (the Claude CLI saves its own session files, as it does for the Ask screen)."),
14 ("fuse", "[--plan] [--stronger-than <tier>] [--kind <kind>] [--difficulty <level>] [--stakes <level>] [--brief <text>] [--] <request>", "let Hop choose who answers or does the work", "Uses the same chooser as Agent. A coding tool may act on files after the configured permission checks."),
15 ("clip", "[--json] [-n <count>] [<number> | <words>]", "what you copied: 20 of them (pinned first, then newest), the ones with these words, or one item whole",
16 "Read only: nothing is changed and Hop need not be running. The order is the Clipboard screen's. A lone number prints that text item exactly as it was copied (hop clip 1 | pbcopy). Images are listed but not printed."),
17 ("open", "[--which] <app name>", "open or switch to an app, matched as the one box matches it",
18 "Part of a name, initials or a slip of the finger are enough. --which only says which app it would be."),
19 ("find", "[--json] <words>", "search this Mac and every machine in the settings at once", ""),
20 ("run", "<machine> <command>", "run a command on a machine (the network route is automatic)", "The exit status is the remote command's, as ssh reports it."),
21 ("machines", "[--json]", "which machines are reachable, and by which route", ""),
22 ("status", "[--json]", "version, whether Hop is running, settings, models, machines, clipboard",
23 "Only your own models (this Mac, your network) are asked whether they answer; nothing is sent anywhere else."),
24 ("swarm", "[<number> | board | check] [--posts]", "list the agent swarms Hop can read, or show one", ""),
25 ("panel", "", "the launcher panel written in Omega: type, Enter opens the app", ""),
26 ("hear", "<audio file> [--raw]", "what Hop would type for a recording", ""),
27 ("hear-many", "<manifest.jsonl> <out.jsonl>", "the same for many recordings ({\"id\",\"wav\"} per line)", ""),
28 ("tidy", "<text>", "Hop's dictation cleanup alone", ""),
29 ("know", "<words>", "what Cortex has on it (needs Cortex in the settings, and Hop running)", ""),
30 ("note", "<title> :: <text>", "save a note to Cortex", ""),
31 ("link", "[--dir <folder>]", "put the hop command in ~/.local/bin (or the folder given)",
32 "A link to the program inside Hop.app. A file or any other link named hop that is already there is left as it is."),
33 ("version", "", "the version of this Hop", ""),
34 ("help", "[command]", "this list, or one command with its notes", ""),
35 ]
36
37 nonisolated static func err(_ s: String) { FileHandle.standardError.write(Data((s + "\n").utf8)) }
38 nonisolated private static func out(_ s: String) { FileHandle.standardOutput.write(Data(s.utf8)) }
39
40 /// JSON on standard output, keys in a fixed order.
41 static func emit(_ value: Any) {
42 let d = (try? JSONSerialization.data(withJSONObject: value, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])) ?? Data("null".utf8)
43 print(String(decoding: d, as: UTF8.self))
44 }
45
46 /// Takes a flag out of the arguments; true when it was there.
47 static func take(_ flag: String, from args: inout [String]) -> Bool {
48 guard args.contains(flag) else { return false }
49 args.removeAll { $0 == flag }
50 return true
51 }
52
53 /// Takes `-x <value>` out of the arguments. `given` without a value means the value was left out.
54 static func option(_ names: [String], from args: inout [String]) -> (given: Bool, value: String?) {
55 guard let i = args.firstIndex(where: { names.contains($0) }) else { return (false, nil) }
56 let value = i + 1 < args.count ? args[i + 1] : nil
57 args.removeSubrange(i...(value == nil ? i : i + 1))
58 return (true, value)
59 }
60
61 static func usage(_ name: String) -> Int32 {
62 if let g = guide.first(where: { $0.name == name }) { err("usage: hop \(g.name) \(g.args)") }
63 return 2
64 }
65
66 /// This program's real file, whichever link it was started through (`~/.local/bin/hop` is a link into the app).
67 nonisolated static var program: URL { (Bundle.main.executableURL ?? URL(fileURLWithPath: CommandLine.arguments[0])).resolvingSymlinksInPath() }
68
69 /// The app's Info.plist, read beside the real program: started through a link, the main bundle is not the app.
70 nonisolated static var info: [String: Any] {
71 let plist = program.deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Info.plist")
72 return (NSDictionary(contentsOf: plist) as? [String: Any]) ?? Bundle.main.infoDictionary ?? [:]
73 }
74
75 static var version: String {
76 return "Hop \(info["CFBundleShortVersionString"] as? String ?? "unknown") (\(info["CFBundleVersion"] as? String ?? "?"))"
77 }
78
79 static func help(_ args: [String]) -> Int32 {
80 if let name = args.first {
81 guard let g = guide.first(where: { $0.name == name }) else { err("hop: no command named \"\(name)\". Run: hop help"); return 2 }
82 print("hop \(g.name) \(g.args)\n\(g.what)" + (g.more.isEmpty ? "" : "\n\n" + g.more))
83 return 0
84 }
85 let left = guide.map { "hop \($0.name) \($0.args)" }
86 let width = min(34, left.map(\.count).max() ?? 0)
87 for (l, g) in zip(left, guide) {
88 print(l.count <= width ? l.padding(toLength: width + 2, withPad: " ", startingAt: 0) + g.what
89 : l + "\n" + String(repeating: " ", count: width + 2) + g.what)
90 }
91 print("\nhop help <command> says more. Exit status: 0 done, 1 nothing found or it failed, 2 not written correctly.")
92 return 0
93 }
94
95 // MARK: ask
96
97 /// Text piped or redirected in. A terminal, /dev/null and anything else is not read, so `hop ask` never waits on a keyboard.
98 static func pipedInput() -> String? {
99 var st = stat()
100 guard fstat(0, &st) == 0 else { return nil }
101 let kind = st.st_mode & S_IFMT
102 guard kind == S_IFIFO || kind == S_IFREG else { return nil }
103 return String(decoding: FileHandle.standardInput.readDataToEndOfFile(), as: UTF8.self)
104 }
105
106 static func ask(_ argv: [String], _ cfg: HopConfig) async -> Int32 {
107 var args = argv
108 let picked = option(["-m", "--model"], from: &args)
109 if picked.given, picked.value == nil { return usage("ask") }
110 var text = args.joined(separator: " ")
111 if let piped = pipedInput(), !piped.isEmpty { text = text.isEmpty ? piped : text + "\n\n" + piped }
112 text = text.trimmingCharacters(in: .whitespacesAndNewlines)
113 guard !text.isEmpty else { return usage("ask") }
114
115 let ep: ModelEndpoint
116 if let name = picked.value {
117 guard let m = cfg.models.first(where: { $0.name.caseInsensitiveCompare(name) == .orderedSame }) else {
118 err("hop ask: no model named \"\(name)\" in the settings. Models: " + cfg.models.map { "\"\($0.name)\"" }.joined(separator: ", "))
119 return 2
120 }
121 ep = m
122 } else {
123 let choice = await AskRoute.choose(cfg) { await AskRoute.answers($0) }
124 if let note = choice.note { err(note) }
125 guard let m = cfg.models.first(where: { $0.name == choice.name }) ?? cfg.models.first else {
126 err("hop ask: no model set up yet. Add one to \(HopConfig.url.path)")
127 return 1
128 }
129 ep = m
130 }
131
132 let started = Date()
133 if ep.kind == "claude-cli" { return await askClaude(ep, text) }
134 let reply = Reply()
135 do {
136 let got = try await ModelClient.streamReply(ep, history: [ChatMessage(role: "user", text: text)]) { reply.write($0) }
137 guard !reply.text.isEmpty else { err("hop ask: \(ep.name) gave no reply"); return 1 }
138 reply.endLine()
139 guard got.finished else { err("hop ask: \(ep.name) stopped without saying the answer was complete; what is above may be only part of it"); return 1 }
140 let tokens = got.tokens > 0 ? got.tokens : Savings.estimate(reply.text) + Savings.estimate(text)
141 err(AppModel.answerMeta(ep, tokens: tokens, seconds: Date().timeIntervalSince(started), who: AskRoute.who(ep, reported: got.model)))
142 return 0
143 } catch ModelClient.Busy.busy {
144 reply.endLine()
145 err("hop ask: \(ep.name) is busy right now. Try again in a moment.")
146 return 1
147 } catch {
148 reply.endLine()
149 err("hop ask: \(ep.name) did not answer: \(error.localizedDescription)")
150 return 1
151 }
152 }
153
154 /// The Claude CLI, run exactly as the Ask screen runs it (chat only, tools off), one question, no session kept.
155 private static func askClaude(_ ep: ModelEndpoint, _ text: String) async -> Int32 {
156 let run = CommandRun(AppModel.claudeAskArgs(model: ep.model, text: text, known: "", session: nil), cwd: HopConfig.dir.path)
157 let reply = Reply()
158 let code: Int32 = await withCheckedContinuation { c in
159 run.start(onLine: { line in DispatchQueue.main.async { reply.claude(line) } }, // the main queue keeps the lines in order,
160 onExit: { code in DispatchQueue.main.async { c.resume(returning: code) } }) // and the end after the last of them
161 }
162 if reply.text.isEmpty, reply.failure == nil, let whole = reply.whole { reply.write(whole) }
163 reply.endLine()
164 if let failure = reply.failure { err("hop ask: " + failure); return 1 }
165 if code == 127 { err("hop ask: the Claude CLI is not installed on this Mac. Install Claude Code and sign in, or add your own model to \(HopConfig.url.path)"); return 1 }
166 if code != 0 {
167 reply.complaints.forEach(err)
168 err("hop ask: Claude didn't answer (exit \(code)). Is Claude Code signed in? In Terminal run: claude, then /login")
169 return 1
170 }
171 guard !reply.text.isEmpty else { err("hop ask: Claude gave no reply"); return 1 }
172 guard reply.finished else { err("hop ask: the Claude CLI ended without its closing result; what is above may be only part of the answer"); return 1 }
173 err(AppModel.claudeMeta(ep, reported: reply.model, tokens: reply.tokens ?? Savings.estimate(reply.text) + Savings.estimate(text), seconds: reply.seconds))
174 return 0
175 }
176
177 /// One answer as it arrives. Used on the main queue only.
178 private final class Reply: @unchecked Sendable {
179 var text = "", model: String?, failure: String?, tokens: Int?, seconds: Double?, complaints: [String] = []
180 var whole: String? // the Claude CLI's answer in one piece, printed at the end only when no part of it streamed
181 var finished = false // the Claude CLI's closing result line arrived: the answer is complete
182
183 func write(_ s: String) { text += s; Cli.out(s) }
184 /// A terminal prompt should start on its own line after the answer.
185 func endLine() { if !text.isEmpty, !text.hasSuffix("\n") { Cli.out("\n") } }
186
187 /// One line of the Claude CLI's stream-json output, read as the Ask screen reads it.
188 func claude(_ line: String) {
189 guard let d = line.data(using: .utf8), let j = try? JSONSerialization.jsonObject(with: d) as? [String: Any] else {
190 if line.hasPrefix("! ") { complaints.append(String(line.dropFirst(2))) } // the tool's own standard error
191 return
192 }
193 if model == nil { model = AskRoute.reportedModel(j) }
194 switch j["type"] as? String {
195 case "stream_event":
196 if let ev = j["event"] as? [String: Any], ev["type"] as? String == "content_block_delta",
197 let t = (ev["delta"] as? [String: Any])?["text"] as? String { write(t) }
198 case "result":
199 if j["is_error"] as? Bool == true { failure = j["result"] as? String ?? "Claude returned an error." }
200 else { whole = j["result"] as? String; finished = true }
201 tokens = AppModel.claudeTokens(j)
202 seconds = (j["duration_ms"] as? Double).map { $0 / 1000 }
203 default: break
204 }
205 }
206 }
207
208 // MARK: clip
209
210 static func clip(_ argv: [String]) -> Int32 {
211 var args = argv
212 let json = take("--json", from: &args)
213 let count = option(["-n"], from: &args)
214 var limit = 20
215 if count.given {
216 guard let n = count.value.flatMap({ Int($0) }), n > 0 else { return usage("clip") }
217 limit = n
218 }
219 let all: [ClipItem]
220 do {
221 guard let saved = try ClipboardStore.saved() else { err("hop clip: no clipboard history is saved in \(HopConfig.dir.path)"); return 1 }
222 all = ClipboardStore.search("", in: saved)
223 } catch {
224 err("hop clip: the clipboard history cannot be read: \(error.localizedDescription)")
225 return 1
226 }
227 let stamp = ISO8601DateFormatter()
228 func row(_ n: Int, _ it: ClipItem) -> [String: Any] {
229 ["n": n, "date": stamp.string(from: it.date), "app": it.sourceApp ?? "", "pinned": it.pinned, "image": it.text == nil, "text": it.text ?? NSNull()]
230 }
231 if args.count == 1, let n = Int(args[0]) {
232 guard n >= 1, n <= all.count else { err("hop clip: there is no item \(n) (\(all.count) saved)"); return 1 }
233 let it = all[n - 1]
234 if json { emit(row(n, it)); return 0 }
235 guard let text = it.text else { err("hop clip: item \(n) is an image; hop clip prints text"); return 1 }
236 out(text)
237 return 0
238 }
239 let wanted = Set(ClipboardStore.search(args.joined(separator: " "), in: all).map(\.id))
240 let rows = all.enumerated().filter { wanted.contains($0.element.id) }.prefix(limit)
241 if json { emit(rows.map { row($0.offset + 1, $0.element) }) }
242 else {
243 for (i, it) in rows {
244 print("\(i + 1)\t\(stamp.string(from: it.date))\t\(it.sourceApp ?? "-")\t\(it.pinned ? "pinned " : "")\(it.preview.prefix(120))")
245 }
246 }
247 return rows.isEmpty ? 1 : 0
248 }
249
250 // MARK: open
251
252 static func open(_ argv: [String]) async -> Int32 {
253 var args = argv
254 let which = take("--which", from: &args)
255 let q = args.joined(separator: " ")
256 guard !q.isEmpty else { return usage("open") }
257 guard let best = AppCatalog.match(q, apps: AppCatalog().apps, running: AppCatalog.runningNow()).first else {
258 err("hop open: no app matches \"\(q)\"")
259 return 1
260 }
261 if !which {
262 do { _ = try await NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: best.app.path), configuration: NSWorkspace.OpenConfiguration()) }
263 catch { err("hop open: \(best.app.name) did not open: \(error.localizedDescription)"); return 1 }
264 }
265 print("\(best.app.name)\t\(best.app.path)")
266 return 0
267 }
268
269 // MARK: show
270
271 /// `hop show`, and `hop` typed alone: what clicking Hop.app does. A running Hop opens its box; otherwise Hop starts.
272 static func show(_ args: [String]) async -> Int32 {
273 guard args.isEmpty else { return usage("show") }
274 let id = info["CFBundleIdentifier"] as? String ?? "com.aienos.hop", me = ProcessInfo.processInfo.processIdentifier
275 let running = NSRunningApplication.runningApplications(withBundleIdentifier: id).first { $0.processIdentifier != me }
276 let app = running?.bundleURL ?? program.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
277 // A running Hop opens its box when it is opened again. A Hop that is not running starts with the box
278 // hidden, so it is started with --show, and on the settings folder this terminal names, if it names one.
279 let how = NSWorkspace.OpenConfiguration()
280 if running == nil {
281 how.arguments = ["--show"]
282 if let dir = ProcessInfo.processInfo.environment["HOP_CONFIG_DIR"], !dir.isEmpty { how.environment = ["HOP_CONFIG_DIR": URL(fileURLWithPath: dir).standardizedFileURL.path] } // absolute: the app starts in another folder
283 }
284 do { _ = try await NSWorkspace.shared.openApplication(at: app, configuration: how) }
285 catch { err("hop show: Hop did not open: \(error.localizedDescription)"); return 1 }
286 print(running == nil ? "started Hop (\(app.path))" : "opened Hop's box")
287 return 0
288 }
289
290 // MARK: status
291
292 private static func onPath(_ dir: String) -> Bool {
293 let want = URL(fileURLWithPath: dir).standardizedFileURL.path
294 return (ProcessInfo.processInfo.environment["PATH"] ?? "").split(separator: ":").contains { URL(fileURLWithPath: String($0)).standardizedFileURL.path == want }
295 }
296
297 /// The first `hop` the shell would find, and whether it is this program.
298 private static func commandOnPath() -> (path: String, thisHop: Bool)? {
299 for dir in (ProcessInfo.processInfo.environment["PATH"] ?? "").split(separator: ":") {
300 let p = String(dir) + "/hop"
301 if FileManager.default.isExecutableFile(atPath: p) { return (p, URL(fileURLWithPath: p).resolvingSymlinksInPath().path == program.path) }
302 }
303 return nil
304 }
305
306 static func status(_ argv: [String], _ cfg: HopConfig) async -> Int32 {
307 var args = argv
308 let json = take("--json", from: &args)
309 guard args.isEmpty else { return usage("status") }
310 let info = Self.info
311 let id = info["CFBundleIdentifier"] as? String ?? "com.aienos.hop", me = ProcessInfo.processInfo.processIdentifier
312 let pids = NSRunningApplication.runningApplications(withBundleIdentifier: id).map(\.processIdentifier).filter { $0 != me }
313 let command = commandOnPath()
314 let settingsOK = !SettingsFile.isBroken(HopConfig.url)
315
316 var models: [[String: Any]] = []
317 let own = Set(AskRoute.ownModels(cfg).map(\.id))
318 for m in cfg.models {
319 var state = "not asked" // only an own model gets the /health request; nothing is sent anywhere else
320 if own.contains(m.id) {
321 switch await ModelStatus.probe(m) {
322 case .free: state = "ready"
323 case .busy: state = "busy"
324 case .offline, .unknown: state = "not answering"
325 }
326 }
327 models.append(["name": m.name, "kind": m.kind, "place": m.place.rawValue, "address": m.baseURL, "state": state])
328 }
329
330 var clipboard: [String: Any]
331 do {
332 if let saved = try ClipboardStore.saved() { clipboard = ["state": "readable", "items": saved.count] }
333 else { clipboard = ["state": "nothing saved", "items": 0] }
334 } catch { clipboard = ["state": "cannot be read: \(error.localizedDescription)", "items": NSNull()] }
335
336 if json {
337 emit(["version": info["CFBundleShortVersionString"] as? String ?? "unknown", "build": info["CFBundleVersion"] as? String ?? "?",
338 "program": program.path, "running": !pids.isEmpty, "pids": pids.map { Int($0) },
339 "command": command.map { ["path": $0.path, "thisHop": $0.thisHop] as [String: Any] } ?? NSNull(),
340 "settings": ["path": HopConfig.url.path, "readable": settingsOK] as [String: Any],
341 "hotkey": cfg.hotkey, "models": models,
342 "machines": cfg.machines.map { ["name": $0.name, "ssh": $0.ssh] }, "clipboard": clipboard] as [String: Any])
343 return 0
344 }
345 func line(_ k: String, _ v: String) { print(k.padding(toLength: 11, withPad: " ", startingAt: 0) + v) }
346 print(version)
347 line("program", program.path)
348 line("running", pids.isEmpty ? "no" : "yes (pid \(pids.map(String.init).joined(separator: ", ")))")
349 line("command", command.map { $0.path + ($0.thisHop ? "" : " (another program, not this Hop)") } ?? "hop is not on your PATH; run: \(program.path) link")
350 line("settings", HopConfig.url.path + (settingsOK ? "" : " (could not be read; Hop runs on its built-in settings)"))
351 line("hotkey", cfg.hotkey)
352 for (i, m) in models.enumerated() {
353 let address = (m["address"] as? String).flatMap { $0.isEmpty ? nil : $0 }
354 line(i == 0 ? "models" : "", ([m["name"], m["place"], address, m["state"] as? String == "not asked" ? nil : m["state"]] as [Any?]).compactMap { $0 as? String }.joined(separator: " ยท "))
355 }
356 if models.isEmpty { line("models", "none") }
357 line("machines", cfg.machines.isEmpty ? "none" : cfg.machines.map { "\($0.name) (ssh \($0.ssh))" }.joined(separator: ", "))
358 line("clipboard", clipboard["state"] as? String == "readable" ? "\(clipboard["items"] ?? 0) items" : clipboard["state"] as? String ?? "")
359 return 0
360 }
361
362 // MARK: link
363
364 /// `hop link`: a link named hop to this program, in ~/.local/bin or the folder given. Only a missing name is
365 /// written. A file, or a link that leads anywhere else (even nowhere: its volume may be away), is not Hop's to replace.
366 static func link(_ argv: [String]) -> Int32 {
367 var args = argv
368 let picked = option(["--dir"], from: &args)
369 guard args.isEmpty, !(picked.given && picked.value == nil) else { return usage("link") }
370 let fm = FileManager.default
371 let dir = URL(fileURLWithPath: ((picked.value ?? "~/.local/bin") as NSString).expandingTildeInPath, isDirectory: true).standardizedFileURL
372 let link = dir.appendingPathComponent("hop"), target = program
373 if let existing = try? fm.destinationOfSymbolicLink(atPath: link.path) {
374 let leadsTo = URL(fileURLWithPath: existing, relativeTo: dir).resolvingSymlinksInPath()
375 guard leadsTo.path == target.path else {
376 err("hop link: \(link.path) already leads somewhere else (\(leadsTo.path)) and was left as it is. To link this Hop, remove it first: rm -- \(Shell.quote(link.path))")
377 return 1
378 }
379 print("hop is already linked: \(link.path) -> \(target.path)")
380 } else if (try? fm.attributesOfItem(atPath: link.path)) != nil {
381 err("hop link: \(link.path) is a file of its own, not a link, and was left as it is.")
382 return 1
383 } else {
384 do { try fm.createDirectory(at: dir, withIntermediateDirectories: true); try fm.createSymbolicLink(at: link, withDestinationURL: target) }
385 catch { err("hop link: \(error.localizedDescription)"); return 1 }
386 print("linked \(link.path) -> \(target.path)")
387 }
388 if !onPath(dir.path) { err("\(dir.path) is not on your PATH. To type hop, add this line to ~/.zshrc:\n export PATH=\"\(dir.path):$PATH\"") }
389 return 0
390 }
391}