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

122 lines · 7528 bytes Raw Blame History
1import Foundation
2import AppKit
3
4/// The user's other computers, treated as part of one box. Optional: none are set up by default.
5/// Routing (home network or VPN) is left to the user's ssh configuration, so Hop only ever says "ssh <alias>".
6struct Machine: Codable, Hashable, Identifiable {
7 var id: String { name }
8 var name: String // shown in results, e.g. "Server"
9 var ssh: String // ssh alias, e.g. "server"
10 var roots: [String] // folders indexed for Find
11 var skip: [String] = [".git", "node_modules", "target", "__pycache__", "venv", ".venv",
12 "site-packages", "build", "dist", "proc"]
13 var homeDir: String? = nil // shown as "~" in results
14
15 init(name: String, ssh: String, roots: [String], homeDir: String? = nil) {
16 self.name = name; self.ssh = ssh; self.roots = roots; self.homeDir = homeDir
17 }
18 enum CodingKeys: String, CodingKey { case name, ssh, roots, skip, homeDir }
19 init(from decoder: Decoder) throws {
20 let c = try decoder.container(keyedBy: CodingKeys.self)
21 name = try c.decode(String.self, forKey: .name)
22 ssh = try c.decode(String.self, forKey: .ssh)
23 roots = try c.decodeIfPresent([String].self, forKey: .roots) ?? []
24 if let s = try c.decodeIfPresent([String].self, forKey: .skip) { skip = s }
25 homeDir = try c.decodeIfPresent(String.self, forKey: .homeDir)
26 }
27}
28
29enum Remote {
30 /// The file list is kept as 20 shards so a search uses all cores (30M paths: ~3.4 s -> well under 1 s).
31 static let shardDir = "~/.cache/hop/shards"
32 static let shards = 20
33
34 /// Runs a command on a machine (one shared, auto-routed ssh connection) and returns stdout.
35 static func run(_ m: Machine, _ remote: String, timeout: TimeInterval = 20) async -> (code: Int32, out: String) {
36 await withCheckedContinuation { c in
37 let box = LineBox()
38 let run = CommandRun(["ssh", "-o", "BatchMode=yes", m.ssh, remote])
39 let once = OnceFlag()
40 run.start(onLine: { if !$0.hasPrefix("! ") { box.add($0) } }, onExit: { code in
41 if once.take() { c.resume(returning: (code, box.text)) }
42 })
43 DispatchQueue.global().asyncAfter(deadline: .now() + timeout) {
44 if once.take() { run.stop(); c.resume(returning: (124, box.text)) }
45 }
46 }
47 }
48
49 /// Starts a background, lowest-priority rebuild of the machine's file list if it is older
50 /// than 30 minutes. The list lives on that machine; Hop never copies it.
51 static func refreshIndex(_ m: Machine) async {
52 let prune = m.skip.map { "-name " + Shell.quote($0) }.joined(separator: " -o ")
53 let roots = m.roots.map(Shell.quote).joined(separator: " ")
54 let build = RemoteIndex.build(roots: roots, prune: prune, shards: shards)
55 let script = """
56 mkdir -p ~/.cache/hop; f=\(shardDir)/s00
57 if [ -d ~/.cache/hop/building ] && [ -n "$(find ~/.cache/hop/building -maxdepth 0 -mmin +180 2>/dev/null)" ]; then rmdir ~/.cache/hop/building; fi
58 if [ ! -f $f ] || [ -n "$(find $f -mmin +30 2>/dev/null)" ]; then
59 if mkdir ~/.cache/hop/building 2>/dev/null; then
60 nohup nice -n 19 ionice -c3 sh -c \(Shell.quote(build)) >/dev/null 2>&1 &
61 fi
62 fi
63 echo ok
64 """
65 _ = await run(m, script)
66 }
67
68 /// Searches the machine's file list on the machine itself and ranks the results here.
69 static func search(_ m: Machine, _ query: String, limit: Int = 25) async -> (hits: [FileIndex.Hit], error: String?) {
70 let terms = query.lowercased().split(separator: " ").map(String.init).filter { !$0.isEmpty }
71 guard let first = terms.max(by: { $0.count < $1.count }) else { return ([], nil) }
72 var filter = "LC_ALL=C grep -F -i -- \(Shell.quote(first)) \"$s\""
73 for t in terms where t != first { filter += " | LC_ALL=C grep -F -i -- \(Shell.quote(t))" }
74 let cmd = "d=\(shardDir); [ -f $d/s00 ] || { echo HOP-NO-INDEX; exit 0; }; " +
75 // each shard writes its own file (parallel writers to one pipe can split lines)
76 "t=$(mktemp -d /dev/shm/hop.XXXXXX 2>/dev/null || mktemp -d); " +
77 "for s in $d/s*; do ( \(filter) | head -300 > \"$t/${s##*/}\" ) & done; wait; cat \"$t\"/*; rm -rf \"$t\""
78 let r = await run(m, cmd, timeout: 12)
79 if r.code == 255 || r.code == 124 { return ([], "\(m.name) is unreachable right now") }
80 if r.out.hasPrefix("HOP-NO-INDEX") {
81 await refreshIndex(m) // first use on this machine: start building its list
82 return ([], "\(m.name) is building its file list…")
83 }
84 // All the lines in one request to the core (one round trip, not one a path).
85 let lines = r.out.split(separator: "\n").map(String.init)
86 let scores = FileIndex.scores(paths: lines.map { $0.hasSuffix("/") ? String($0.dropLast()) : $0 }, terms: terms)
87 let hits = zip(lines, scores).compactMap { p, s in s.map { FileIndex.Hit(path: p, machine: m.name, score: $0) } }
88 return (Array(hits.sorted { $0.score > $1.score }.prefix(limit)), nil)
89 }
90
91 /// Brings a remote file to this Mac (cache folder) and returns where it landed.
92 static func fetch(_ m: Machine, _ path: String) async throws -> URL {
93 let size = await run(m, "stat -c %s -- \(Shell.quote(path))")
94 guard size.code == 0, let bytes = Int64(size.out.trimmingCharacters(in: .whitespacesAndNewlines)) else {
95 throw NSError(domain: "Hop", code: 1, userInfo: [NSLocalizedDescriptionKey: "Couldn't read that file on \(m.name)."])
96 }
97 guard bytes <= 2_000_000_000 else {
98 throw NSError(domain: "Hop", code: 2, userInfo: [NSLocalizedDescriptionKey: "That file is \(bytes / 1_000_000_000) GB; too big to open over the network. Its path is on your clipboard."])
99 }
100 let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
101 let dest = caches.appendingPathComponent("Hop/remote/\(m.name)" + path)
102 try FileManager.default.createDirectory(at: dest.deletingLastPathComponent(), withIntermediateDirectories: true)
103 let code: Int32 = await withCheckedContinuation { c in
104 CommandRun(["scp", "-q", "-o", "BatchMode=yes", "\(m.ssh):\(path)", dest.path]).start(onLine: { _ in }, onExit: { c.resume(returning: $0) })
105 }
106 guard code == 0 else { throw NSError(domain: "Hop", code: 3, userInfo: [NSLocalizedDescriptionKey: "Copying from \(m.name) failed (exit \(code))."]) }
107 return dest
108 }
109
110 /// Standing instructions for the personal agent: who it works for and, when set up, the other machines and the factory.
111 static func agentBriefing(_ cfg: HopConfig) -> String {
112 // Kept tiny on purpose: this rides along on every agent call, so every word costs tokens.
113 let owner = cfg.owner
114 var s = owner.prefix(1).uppercased() + owner.dropFirst() + "'s agent."
115 if !cfg.machines.isEmpty {
116 let hosts = cfg.machines.map { "\($0.name): ssh \($0.ssh) '<cmd>'" }.joined(separator: "; ")
117 s += " All machines = one box; never ask which. Mac = here. \(hosts) (auto-routed). Find files anywhere: hop find <words>."
118 }
119 if cfg.factoryEnabled { s += " Factory: \(cfg.factoryURL)." }
120 return s + " Never delete agent files. Back up before destructive changes. Reply short, plain words."
121 }
122}