hop
Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.
Brought by drakestapleton
| 1 | import Foundation |
| 2 | |
| 3 | /// `hop` on the command line, for the user, for developers and for the user's agents. `hop help` lists every |
| 4 | /// command (`Cli.guide`, in CliDev.swift, which also holds ask, clip, open, status, link and the --json output): |
| 5 | /// hop find <words> search this Mac and every configured machine at once |
| 6 | /// hop run <machine> <command> run a command on a machine (auto-routed ssh) |
| 7 | /// hop machines which machines are reachable, and by which route |
| 8 | /// hop swarm [number|board] the agent swarms the Factory screen's Swarm section shows, as plain text |
| 9 | /// hop panel the launcher panel written in Omega (Omega/ui/hoppanel.om): type, Enter opens the app |
| 10 | /// hop fuse <what you want> Hop picks who does it, as the Agent screen does, and prints the reply |
| 11 | @MainActor |
| 12 | enum Cli { |
| 13 | static let commands: Set<String> = ["find", "run", "machines", "help", "--help", "-h", "hear", "hear-many", "tidy", "know", "note", "swarm", "panel", |
| 14 | "ask", "clip", "open", "status", "link", "show", "version", "--version", "fuse"] |
| 15 | |
| 16 | /// The options that start the app itself or one of its self-tests. Any other `--word` is a slip in a terminal. |
| 17 | static let appFlags: Set<String> = ["--factory", "--no-global-hotkey", "--selftest", "--selftest-ask", "--selftest-pick", "--selftest-flow", "--uitest", "--uitest-agent", |
| 18 | "--uitest-arrows", "--uitest-box", "--uitest-launch", "--uitest-learn", "--uitest-voice", "--show"] |
| 19 | |
| 20 | static func main(_ cmd: String, _ args: [String]) async -> Int32 { |
| 21 | // These read no settings, so they also work before Hop has ever been opened. |
| 22 | switch cmd { |
| 23 | case "version", "--version": print(version); return 0 |
| 24 | case "help", "--help", "-h": return help(args) |
| 25 | case "link": return link(args) |
| 26 | case "show": return await show(args) |
| 27 | default: break |
| 28 | } |
| 29 | let cfg = HopConfig.load() |
| 30 | switch cmd { |
| 31 | case "hear": // hop hear <recording>: what Hop would type for it (same engine and cleanup as live dictation) |
| 32 | guard let f = args.first, FileManager.default.isReadableFile(atPath: f) else { err("usage: hop hear <audio file>"); return 2 } |
| 33 | let engine = SpeechEngine(), set = DictationSettings.load() |
| 34 | engine.hints = set.words + set.fixes.map(\.write) |
| 35 | do { try await engine.start(.file(URL(fileURLWithPath: f))) } catch { err("hop hear: \(error.localizedDescription)"); return 1 } |
| 36 | let heard = await engine.finish() |
| 37 | print(args.contains("--raw") ? heard : Cleanup.apply(heard, set)) |
| 38 | return heard.isEmpty ? 1 : 0 |
| 39 | case "hear-many": // hop hear-many <manifest.jsonl> <out.jsonl>: measure on many recordings ({"id","wav"} per line) |
| 40 | guard args.count >= 2, let lines = try? String(contentsOfFile: args[0], encoding: .utf8) else { err("usage: hop hear-many <manifest.jsonl> <out.jsonl>"); return 2 } |
| 41 | let engine = SpeechEngine(), set = DictationSettings.load() |
| 42 | engine.hints = set.words + set.fixes.map(\.write) |
| 43 | var out = "" |
| 44 | for line in lines.split(separator: "\n") { |
| 45 | guard let j = try? JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any], let wav = j["wav"] as? String else { continue } |
| 46 | let t0 = Date() |
| 47 | do { try await engine.start(.file(URL(fileURLWithPath: wav))) } catch { continue } |
| 48 | let heard = await engine.finish() |
| 49 | let o: [String: Any] = ["id": j["id"] ?? "", "heard": heard, "typed": Cleanup.apply(heard, set), "ms": Int(Date().timeIntervalSince(t0) * 1000)] |
| 50 | if let d = try? JSONSerialization.data(withJSONObject: o) { out += String(decoding: d, as: UTF8.self) + "\n" } |
| 51 | } |
| 52 | try? out.write(toFile: args[1], atomically: true, encoding: .utf8) |
| 53 | return 0 |
| 54 | case "know": // hop know <words>: what Cortex has on it (needs Hop running, for the forwarded port) |
| 55 | let cx = Cortex(cfg.cortex), t0 = Date() |
| 56 | let hits = await cx.search(args.joined(separator: " "), limit: 6, timeout: 6) |
| 57 | for h in hits { print("\(h.space)\t\(h.title)\t\(h.content.replacingOccurrences(of: "\n", with: " ").prefix(110))") } |
| 58 | FileHandle.standardError.write(Data("\(hits.count) hits in \(Int(Date().timeIntervalSince(t0) * 1000)) ms (first call includes opening the vault) \(cx.state)\n".utf8)) |
| 59 | return hits.isEmpty ? 1 : 0 |
| 60 | case "note": // hop note <title> :: <text>: save a note to Cortex through the same background queue the agent uses |
| 61 | let parts = args.joined(separator: " ").components(separatedBy: " :: ") |
| 62 | guard parts.count == 2 else { err("usage: hop note <title> :: <text>"); return 2 } |
| 63 | let cx = Cortex(cfg.cortex) |
| 64 | cx.learn(title: parts[0], content: parts[1], source: "hop/cli") |
| 65 | for _ in 0..<40 where cx.queued > 0 { try? await Task.sleep(nanoseconds: 500_000_000) } |
| 66 | print(cx.queued == 0 ? "saved" : "still queued (\(cx.queued)); it will be sent when Cortex is reachable") |
| 67 | return cx.queued == 0 ? 0 : 1 |
| 68 | case "fuse": // hop fuse <what you want>: Hop sorts it and picks the mind, or fuses several (Sources/Fusion.swift) |
| 69 | let usage = "usage: hop fuse [--plan] [--stronger-than <tier 1..4>] [--kind 1|2|3] [--difficulty 1..5] [--stakes 1|2|3] [--brief <text>] [--] <what you want>" |
| 70 | var rest = args, brief = "", planOnly = false, forced = Fusion.Triage(), isForced = false, above: Int? |
| 71 | flags: while let a = rest.first, a.hasPrefix("--") { |
| 72 | rest.removeFirst() |
| 73 | switch a { |
| 74 | case "--": break flags // the request follows as written, even when it starts with "--" |
| 75 | case "--plan": planOnly = true // show the seats, the sorting and the plan; run nothing |
| 76 | case "--brief": if !rest.isEmpty { brief = rest.removeFirst() } |
| 77 | case "--kind", "--difficulty", "--stakes", "--stronger-than": // skip the sorting and say it yourself |
| 78 | guard let v = rest.first.flatMap({ Int($0) }), v >= 0 else { print(usage); return 2 } |
| 79 | rest.removeFirst() |
| 80 | if a == "--stronger-than" { above = v; continue } // what the Stronger button does after a mind of that tier answered |
| 81 | isForced = true |
| 82 | if a == "--kind" { forced.kind = v } else if a == "--difficulty" { forced.difficulty = v } else { forced.stakes = v } |
| 83 | default: print(usage); return 2 |
| 84 | } |
| 85 | } |
| 86 | let intent = rest.joined(separator: " ").trimmingCharacters(in: .whitespacesAndNewlines) |
| 87 | guard !intent.isEmpty else { print(usage); return 2 } |
| 88 | if isForced { forced.confidence = 1_000_000; forced.by = "you" } |
| 89 | let installed = await AppModel.detectEngines(cfg) |
| 90 | var ask = Fusion.Ask(text: intent, brief: brief, owner: cfg.owner, force: isForced ? forced : nil) |
| 91 | // The yes to agent tools is given once in Hop's window (or by the current versioned consent in the settings). Without it the |
| 92 | // command line runs no tool: it cannot ask the way the window does. |
| 93 | ask.declinedNote = "Agent tools have not been allowed on this Mac yet, so nothing was run. Hop asks once, in its window, before the first tool runs; say yes there, then ask again here." |
| 94 | let allowed = cfg.agentToolsAllowed |
| 95 | // A command Hop starts runs in a process group of its own, so Ctrl-C in the terminal does not reach it by |
| 96 | // itself: on Ctrl-C, or when this command is asked to end, everything is stopped as the Stop button stops |
| 97 | // it, and this command ends only when the tools are gone. Set up before anybody is asked anything. |
| 98 | let control = Fusion.Control() |
| 99 | var watched: [DispatchSourceSignal] = [] |
| 100 | for sig in [SIGINT, SIGTERM, SIGHUP] { |
| 101 | signal(sig, SIG_IGN) |
| 102 | let src = DispatchSource.makeSignalSource(signal: sig, queue: .global()) |
| 103 | src.setEventHandler { control.stop() } |
| 104 | src.resume() |
| 105 | watched.append(src) |
| 106 | } |
| 107 | defer { watched.forEach { $0.cancel() } } |
| 108 | if let above { |
| 109 | let seats = await Fusion.seats(cfg, installed: installed) |
| 110 | let t = isForced ? forced : await Fusion.triage(intent, seats, cwd: cfg.agentWorkingDirectory, control: control) |
| 111 | ask.above = Fusion.Standing(triage: t, tier: above, by: "a tier \(above) mind", fused: false, reply: "") |
| 112 | } |
| 113 | // Written as it comes. A reply does not end in a line break, so one is put in before anything that follows it. |
| 114 | final class Page: @unchecked Sendable { |
| 115 | private let l = NSLock(), out = FileHandle.standardOutput |
| 116 | private var open = false |
| 117 | func write(_ s: String, reply: Bool = false) { |
| 118 | l.lock(); defer { l.unlock() } |
| 119 | guard !s.isEmpty else { return } |
| 120 | out.write(Data(((open && !reply ? "\n" : "") + s + (reply ? "" : "\n")).utf8)) |
| 121 | open = reply && !s.hasSuffix("\n") |
| 122 | } |
| 123 | } |
| 124 | let page = Page() |
| 125 | let end = await Fusion.run(ask, cfg: cfg, installed: installed, planOnly: planOnly, control: control, mayAct: { _ in allowed }) { line in |
| 126 | switch line { |
| 127 | case .progress(let s): page.write((s.hasPrefix("▸ ") ? "" : "▸ ") + s) |
| 128 | case .answer(let s): page.write(s, reply: true) |
| 129 | case .restart: page.write("▸ What follows replaces the reply above.") |
| 130 | case .problem(let s): page.write("! " + s) |
| 131 | } |
| 132 | } |
| 133 | if control.isStopped { |
| 134 | if !(await Fusion.Control.gone(control.leftRunning, within: CommandRun.graceToEnd + 5)) { |
| 135 | page.write("! A tool that was stopped is still running and could not be ended. End it yourself (Activity Monitor).") |
| 136 | } |
| 137 | return 130 |
| 138 | } |
| 139 | if end.outcome.ok, !planOnly { page.write("▸ " + end.outcome.meta + (end.outcome.strongerLeft ? " · a stronger mind is ready" : "")) } |
| 140 | return end.outcome.ok ? 0 : 1 |
| 141 | case "tidy": // hop tidy <text>: the cleanup alone |
| 142 | print(Cleanup.apply(args.joined(separator: " "), DictationSettings.load())) |
| 143 | return 0 |
| 144 | case "swarm": // hop swarm: list the swarms; hop swarm <number|board>: one of them; hop swarm check: its self-test alone |
| 145 | if args.first == "check" { |
| 146 | var failed = 0 |
| 147 | SwarmChecks.run { name, ok, detail in print("\(ok ? "PASS" : "FAIL") \(name): \(detail)"); if !ok { failed += 1 } } |
| 148 | print(failed == 0 ? "ALL PASS" : "\(failed) FAILED") |
| 149 | return failed == 0 ? 0 : 1 |
| 150 | } |
| 151 | let found = SwarmReader.scan(roots: cfg.swarmFolders) |
| 152 | let board = SwarmStore.boardSource(cfg) |
| 153 | let list = found.sources + (board.map { [$0.source] } ?? []) |
| 154 | guard let pick = args.first else { |
| 155 | for (i, src) in list.enumerated() { |
| 156 | print("\(i + 1)\t\(src.title)\t\(src.place)\t\(src.modified.map { $0.formatted(.iso8601) } ?? (i + 1 == list.count && board != nil ? "hop swarm board" : "-"))") |
| 157 | } |
| 158 | if found.more > 0 { print("(\(found.more) older swarms on this Mac are not listed)") } |
| 159 | if list.isEmpty { err("no swarm found (folders: \(cfg.swarmFolders.joined(separator: ", ")))") } |
| 160 | return list.isEmpty ? 1 : 0 |
| 161 | } |
| 162 | guard let src = pick == "board" ? board?.source : Int(pick).flatMap({ list.indices.contains($0 - 1) ? list[$0 - 1] : nil }) else { |
| 163 | err("usage: hop swarm [number|board|check]"); return 2 |
| 164 | } |
| 165 | let owners = SwarmStore.ownerNames(cfg) |
| 166 | var result: (snapshot: SwarmSnapshot?, problem: String) |
| 167 | switch src.kind { |
| 168 | case .folder(let dir): result = SwarmReader.folder(dir, owners: owners, now: Date(), cache: SwarmTranscriptCache()) |
| 169 | case .board(_, let path): |
| 170 | guard let machine = board?.machine else { return 2 } |
| 171 | switch await SwarmReader.fetch(machine, path: path, known: nil) { |
| 172 | case .text(let text, _, let total): result = SwarmReader.board(text: text, totalLines: total, title: src.title + " on " + src.place, owners: owners, now: Date()) |
| 173 | case .missing: result = (nil, "There is no board file at \(path) on \(machine.name).") |
| 174 | default: result = (nil, "I can't reach \(machine.name) right now.") |
| 175 | } |
| 176 | } |
| 177 | guard let snap = result.snapshot else { err(result.problem); return 1 } |
| 178 | print(SwarmReader.report(snap)) |
| 179 | if args.contains("--posts") { |
| 180 | for p in snap.posts.suffix(12) { |
| 181 | let to = (p.all ? ["all"] : []) + p.to.map { snap.members[$0].name } |
| 182 | print("#\(p.id)\t\(p.sender)\t-> \(to.joined(separator: ", "))\t\(SwarmReader.gist(p.text).prefix(90))") |
| 183 | } |
| 184 | } |
| 185 | return 0 |
| 186 | case "panel": // hop panel: the Omega launcher panel, a program of its own beside this one (no Swift in it) |
| 187 | let panel = program.deletingLastPathComponent().appendingPathComponent("hoppanel") |
| 188 | let p = Process(); p.executableURL = panel |
| 189 | do { try p.run() } catch { err("hop panel: cannot start \(panel.path): \(error.localizedDescription)"); return 1 } |
| 190 | p.waitUntilExit() |
| 191 | return p.terminationStatus |
| 192 | case "ask": return await ask(args, cfg) |
| 193 | case "clip": return clip(args) |
| 194 | case "open": return await open(args) |
| 195 | case "status": return await status(args, cfg) |
| 196 | case "find": |
| 197 | var words = args |
| 198 | let json = take("--json", from: &words) |
| 199 | let q = words.joined(separator: " ") |
| 200 | guard !q.isEmpty else { err("usage: hop find [--json] <words>"); return 2 } |
| 201 | let local = FileIndex(roots: cfg.indexRoots, skipNames: cfg.indexSkipNames).search(q, limit: 30) |
| 202 | var rows = local.map { ("Mac", $0.path, $0.score) } |
| 203 | var notes: [String] = [] |
| 204 | await withTaskGroup(of: (String, [FileIndex.Hit], String?).self) { g in |
| 205 | for m in cfg.machines { g.addTask { let r = await Remote.search(m, q, limit: 30); return (m.name, r.hits, r.error) } } |
| 206 | for await (name, hits, err) in g { |
| 207 | rows += hits.map { (name, $0.path, $0.score) } |
| 208 | if let err { notes.append(err) } |
| 209 | } |
| 210 | } |
| 211 | let best = rows.sorted(by: { $0.2 > $1.2 }).prefix(40) |
| 212 | if json { emit(best.map { ["machine": $0.0, "path": $0.1, "score": $0.2] as [String: Any] }) } |
| 213 | else { for r in best { print("\(r.0)\t\(r.1)") } } |
| 214 | for n in notes { FileHandle.standardError.write(Data("note: \(n)\n".utf8)) } |
| 215 | return rows.isEmpty ? 1 : 0 |
| 216 | case "run": |
| 217 | guard args.count >= 2, let m = machine(args[0], cfg) else { |
| 218 | err("usage: hop run <\(cfg.machines.map { $0.name.lowercased() }.joined(separator: "|"))> <command>"); return 2 |
| 219 | } |
| 220 | let remote = args.dropFirst().joined(separator: " ") |
| 221 | let argv = ["/usr/bin/ssh", m.ssh, remote] |
| 222 | var cargs = argv.map { strdup($0) } + [nil] |
| 223 | execv("/usr/bin/ssh", &cargs) |
| 224 | perror("hop run"); return 127 |
| 225 | case "machines": |
| 226 | var rest = args |
| 227 | let json = take("--json", from: &rest) |
| 228 | var rows: [[String: Any]] = [["name": "Mac", "reachable": true, "route": "this computer"]] |
| 229 | if !json { print("Mac\tthis computer") } |
| 230 | for m in cfg.machines { |
| 231 | let route = resolvedHost(m.ssh) |
| 232 | let label = route.hasPrefix("192.168.") ? "home network" : route.hasPrefix("100.") ? "Tailscale" : "direct" |
| 233 | let r = await Remote.run(m, "hostname", timeout: 10) |
| 234 | rows.append(["name": m.name, "ssh": m.ssh, "reachable": r.code == 0, "route": label, "address": route, "host": r.code == 0 ? r.out : ""]) |
| 235 | if !json { print("\(m.name)\t" + (r.code == 0 ? "reachable via \(label) (\(route)), host \(r.out)" : "UNREACHABLE (tried \(label) \(route))")) } |
| 236 | } |
| 237 | if json { emit(rows) } |
| 238 | return 0 |
| 239 | default: |
| 240 | return help([]) |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | static func machine(_ name: String, _ cfg: HopConfig) -> Machine? { |
| 245 | cfg.machines.first { $0.name.lowercased() == name.lowercased() || $0.ssh == name } |
| 246 | } |
| 247 | |
| 248 | /// The address ssh will actually use for an alias right now (after Hop's route choice). |
| 249 | static func resolvedHost(_ alias: String) -> String { |
| 250 | let p = Process(), out = Pipe() |
| 251 | p.executableURL = URL(fileURLWithPath: "/usr/bin/ssh") |
| 252 | p.arguments = ["-G", alias] |
| 253 | p.standardOutput = out; p.standardError = FileHandle.nullDevice |
| 254 | try? p.run(); p.waitUntilExit() |
| 255 | let text = String(decoding: out.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) |
| 256 | return text.split(separator: "\n").first { $0.hasPrefix("hostname ") }.map { String($0.dropFirst(9)) } ?? "?" |
| 257 | } |
| 258 | } |