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

487 lines · 28520 bytes Raw Blame History
1import Foundation
2
3struct ChatMessage: Identifiable, Hashable {
4 let id = UUID()
5 var role: String // "user" | "assistant" | "system" | "note"
6 var text: String
7 var meta: String? = nil // small chip under a reply: tokens, time, "instant"
8 /// Agent screen only. `detail` is the least `AgentDetail` at which the message is shown (nil = always), and
9 /// `more` is what a "tool" message adds from "commands" on: the command, file or search behind the step.
10 var detail: AgentDetail? = nil
11 var more: String? = nil
12 /// The id the agent gave one tool call; the message with what came back carries the same id.
13 var call: String? = nil
14 /// Generated request context for the agent; the conversation shows the short human request.
15 var requestText: String? = nil
16 var assessmentOnly = false
17}
18
19/// How much of the agent's work the Agent screen shows (`agentDetail` in the settings). Each level shows what the
20/// one before it shows, and more. Everything is kept as it arrives, so changing the level changes what is on the
21/// screen at once, for the work already done too.
22enum AgentDetail: String, CaseIterable, Comparable {
23 case answers, steps, commands, output
24 static func < (a: AgentDetail, b: AgentDetail) -> Bool { allCases.firstIndex(of: a)! < allCases.firstIndex(of: b)! }
25 /// The setting as written in the config; a word Hop does not know is "steps", what Hop showed before the setting.
26 init(setting: String) { self = AgentDetail(rawValue: setting.lowercased()) ?? .steps }
27 var title: String {
28 switch self {
29 case .answers: return "Answers only"
30 case .steps: return "Steps"
31 case .commands: return "Commands"
32 case .output: return "Commands and output"
33 }
34 }
35 /// The messages of a transcript this level shows, each with the text it has at this level.
36 /// What came back is headed by the step it belongs to ("◂ Bash: pwd"), found by the call's id and never by
37 /// its place in the list: an agent may run several tools at once and their results arrive in any order.
38 func shown(_ log: [ChatMessage]) -> [ChatMessage] {
39 var steps: [String: String] = [:] // call id -> "Bash: pwd"
40 return log.compactMap { m in
41 let isStep = m.role == "tool" && m.detail == .steps
42 if isStep, let id = m.call {
43 let first = m.more?.split(separator: "\n").first.map(String.init) ?? ""
44 steps[id] = String(m.text.dropFirst(2)) + (first.isEmpty ? "" : ": " + first)
45 }
46 if let d = m.detail, d > self { return nil }
47 var out = m
48 if isStep, self >= .commands, let more = m.more, !more.isEmpty { out.text = m.text + "\n" + more }
49 if m.role == "tool", m.detail == .output {
50 let head = m.call.flatMap { steps[$0] } ?? "a step that is not in this list"
51 out.text = "◂ " + head + "\n" + m.text
52 }
53 return out
54 }
55 }
56}
57
58/// The one network session Hop uses for model servers, Cortex and the factory. It keeps nothing on disk: no
59/// response cache, no cookies, no saved credentials. (The default macOS session writes answers it fetched into
60/// ~/Library/Caches/<app id>, which would put chat text and notes on disk.)
61enum Net {
62 static let session: URLSession = {
63 let c = URLSessionConfiguration.ephemeral
64 c.urlCache = nil
65 c.requestCachePolicy = .reloadIgnoringLocalCacheData
66 c.httpCookieStorage = nil
67 c.urlCredentialStorage = nil
68 return URLSession(configuration: c)
69 }()
70}
71
72/// Streams a reply from any OpenAI-compatible server (llama.cpp, vLLM, Ollama, LM Studio, OpenRouter...).
73enum ModelClient {
74 /// The server handles one generation at a time and something else has it.
75 enum Busy: Error { case busy }
76
77 /// Servers that refused the usage option; asked again without it. Several requests may run at once (a fusion
78 /// asks minds in parallel), so the set is read and changed under a lock.
79 private static let noUsageLock = NSLock()
80 nonisolated(unsafe) private static var noUsageSet: Set<String> = []
81 static func refusesUsage(_ base: String) -> Bool { noUsageLock.lock(); defer { noUsageLock.unlock() }; return noUsageSet.contains(base) }
82 static func noteRefusesUsage(_ base: String) { noUsageLock.lock(); noUsageSet.insert(base); noUsageLock.unlock() }
83
84 /// What a server said about one reply: the tokens it counted (0 if none) and the model id it named (nil if none).
85 struct Reply { var tokens = 0; var model: String? = nil; var finished = false }
86
87 /// Streams the reply; returns total tokens the server reported (0 if it reported none).
88 @discardableResult
89 static func stream(_ ep: ModelEndpoint, history: [ChatMessage],
90 onDelta: @escaping @MainActor (String) -> Void) async throws -> Int {
91 try await streamReply(ep, history: history, onDelta: onDelta).tokens
92 }
93
94 /// Streams the reply; returns the tokens and the model id as the server reported them.
95 static func streamReply(_ ep: ModelEndpoint, history: [ChatMessage],
96 onDelta: @escaping @MainActor (String) -> Void) async throws -> Reply {
97 // Whether to ask again without the usage option depends on what this request sent, not on what another
98 // request to the same server found out meanwhile.
99 let withUsage = !refusesUsage(ep.baseURL)
100 do { return try await streamOnce(ep, history: history, usage: withUsage, onDelta: onDelta) }
101 catch let e as NSError where e.domain == "Hop" && e.code == 400 && withUsage {
102 noteRefusesUsage(ep.baseURL)
103 return try await streamOnce(ep, history: history, usage: false, onDelta: onDelta)
104 }
105 }
106
107 private static func streamOnce(_ ep: ModelEndpoint, history: [ChatMessage], usage: Bool,
108 onDelta: @escaping @MainActor (String) -> Void) async throws -> Reply {
109 var base = ep.baseURL.trimmingCharacters(in: .whitespaces)
110 while base.hasSuffix("/") { base.removeLast() }
111 guard let url = URL(string: base + "/chat/completions") else { throw URLError(.badURL) }
112 var req = URLRequest(url: url, timeoutInterval: 120)
113 req.httpMethod = "POST"
114 req.setValue("application/json", forHTTPHeaderField: "Content-Type")
115 if let k = ep.keychainKey, let tok = Vault.secret(k) { req.setValue("Bearer \(tok)", forHTTPHeaderField: "Authorization") }
116 let msgs = history.filter { $0.role == "user" || $0.role == "assistant" || $0.role == "system" }
117 .map { ["role": $0.role, "content": $0.text] }
118 var body: [String: Any] = ["model": ep.model, "messages": msgs, "stream": true]
119 if usage { body["stream_options"] = ["include_usage": true] }
120 req.httpBody = try JSONSerialization.data(withJSONObject: body)
121 let (bytes, resp) = try await Net.session.bytes(for: req)
122 if let h = resp as? HTTPURLResponse, h.statusCode >= 300 {
123 var body = ""; for try await l in bytes.lines { body += l; if body.count > 400 { break } }
124 if h.statusCode == 429 || h.statusCode == 503 || body.contains("server_busy") { throw Busy.busy }
125 throw NSError(domain: "Hop", code: h.statusCode, userInfo: [NSLocalizedDescriptionKey: "HTTP \(h.statusCode): \(body)"])
126 }
127 var out = Reply()
128 for try await line in bytes.lines {
129 // Some engines answer "busy" with a 200 and a single JSON error line.
130 if line.hasPrefix("{"), line.contains("server_busy") { throw Busy.busy }
131 guard line.hasPrefix("data:") else { continue }
132 let payload = line.dropFirst(5).trimmingCharacters(in: .whitespaces)
133 if payload == "[DONE]" { out.finished = true; break }
134 guard let d = payload.data(using: .utf8),
135 let j = try? JSONSerialization.jsonObject(with: d) as? [String: Any] else { continue }
136 if let u = j["usage"] as? [String: Any], let t = u["total_tokens"] as? Int { out.tokens = t }
137 if out.model == nil { out.model = AskRoute.reportedModel(j) }
138 guard let ch = (j["choices"] as? [[String: Any]])?.first else { continue }
139 if let reason = ch["finish_reason"] as? String, !reason.isEmpty { out.finished = true }
140 guard let delta = ch["delta"] as? [String: Any] else { continue }
141 if let t = delta["content"] as? String, !t.isEmpty { await onDelta(t) }
142 }
143 return out
144 }
145}
146
147/// Runs a local command through the user's login shell (so PATH matches Terminal) and streams stdout lines.
148final class CommandRun: @unchecked Sendable {
149 private let proc = Process()
150 private var buffer = Data()
151
152 /// Folders where command-line tools are commonly installed. A login shell that is not interactive does not
153 /// read ~/.zshrc, so a tool whose folder is added to PATH only there would look "not installed". These folders
154 /// are searched AFTER the login shell's own PATH (the user's own order always wins); no rc file is sourced.
155 nonisolated(unsafe) static var extraPath: [String] = {
156 let h = NSHomeDirectory(), fm = FileManager.default
157 var dirs = [h + "/.local/bin", h + "/.claude/local", "/opt/homebrew/bin", "/usr/local/bin", h + "/.bun/bin",
158 h + "/.npm-global/bin", h + "/.cargo/bin", h + "/.opencode/bin", h + "/.volta/bin", h + "/.asdf/shims",
159 h + "/.local/share/mise/shims", h + "/bin"]
160 // Node version managers keep one bin folder per version; newest first.
161 for root in [h + "/.nvm/versions/node", h + "/Library/Application Support/Herd/config/nvm/versions/node"] {
162 let versions = ((try? fm.contentsOfDirectory(atPath: root)) ?? []).sorted { $0.compare($1, options: .numeric) == .orderedDescending }
163 dirs += versions.map { root + "/" + $0 + "/bin" }
164 }
165 return dirs.filter { !$0.contains(":") }
166 }()
167
168 /// The first argument with which Hop starts itself only to put a command into a process group of its own and
169 /// then become that command (the first lines of main.swift). Nothing else of Hop runs in that process.
170 static let ownGroupFlag = "--hop-own-group"
171 /// The command leads a process group of its own: everything it starts stays in that group unless it leaves it
172 /// itself, so Stop reaches also what is started while the command is ending.
173 private let grouped: Bool
174
175 /// `ownGroup`: run the command as the leader of a process group of its own (an agent tool, which starts
176 /// processes of its own and must be stoppable with all of them). A command in a group of its own does not get
177 /// the terminal's Ctrl-C; whoever starts it that way stops it on a signal (`hop fuse` does).
178 init(_ argv: [String], cwd: String? = nil, ownGroup: Bool = false) {
179 let shell = ["/bin/zsh", "-lc", "[ -n \"$HOP_EXTRA_PATH\" ] && PATH=\"$PATH:$HOP_EXTRA_PATH\"; unset HOP_EXTRA_PATH; exec \"$@\"", "hop"] + argv
180 if ownGroup, let me = Bundle.main.executablePath {
181 grouped = true
182 proc.executableURL = URL(fileURLWithPath: me)
183 proc.arguments = [Self.ownGroupFlag] + shell
184 } else {
185 grouped = false
186 proc.executableURL = URL(fileURLWithPath: shell[0])
187 proc.arguments = Array(shell.dropFirst())
188 }
189 if let cwd { proc.currentDirectoryURL = URL(fileURLWithPath: cwd) }
190 var env = ProcessInfo.processInfo.environment
191 env["TERM"] = "dumb"; env["NO_COLOR"] = "1"
192 env["HOP_EXTRA_PATH"] = Self.extraPath.joined(separator: ":")
193 proc.environment = env
194 }
195
196 private var keepAlive: CommandRun? // the run owns itself until the command ends
197 /// Everything the command says, and its end, is handed over on this one queue, in order: a line is never
198 /// delivered after `onExit`, and never while another line is being delivered.
199 private let q = DispatchQueue(label: "hop.command-run")
200 private var outDone = false, errDone = false, status: Int32?, finished = false // only touched on `q`
201 private let stateLock = NSLock()
202 private var started = false, stopAsked = false // under `stateLock`
203 /// What was there when the command was asked to end: its process id, and the processes below it.
204 private var atStop: (root: Int32, seen: [Running])? // under `stateLock`
205
206 /// Appends bytes and hands back every complete line. Called on `q` only.
207 private func take(_ d: Data, flush: Bool = false) -> [String] {
208 buffer.append(d)
209 var lines: [String] = []
210 while let nl = buffer.firstIndex(of: 10) {
211 lines.append(String(decoding: buffer[buffer.startIndex..<nl], as: UTF8.self))
212 buffer.removeSubrange(buffer.startIndex...nl)
213 }
214 if flush, !buffer.isEmpty { lines.append(String(decoding: buffer, as: UTF8.self)); buffer.removeAll() }
215 return lines
216 }
217
218 /// `onLine` gets each line the command writes, `onExit` its exit status once, after the last line. What the
219 /// command writes to its error stream goes to `onError`; without one it goes to `onLine` with "! " in front
220 /// (which a line of the command's own may also start with). All are called on one private queue.
221 func start(onLine: @escaping @Sendable (String) -> Void, onError: (@Sendable (String) -> Void)? = nil, onExit: @escaping @Sendable (Int32) -> Void) {
222 let complain: @Sendable (String) -> Void = { text in if let onError { onError(text) } else { onLine("! " + text) } }
223 let out = Pipe(), err = Pipe()
224 proc.standardOutput = out; proc.standardError = err; proc.standardInput = FileHandle.nullDevice
225 keepAlive = self
226 // The end: the command has exited and both of its streams are read to their end. A background child that
227 // keeps a stream open would hold that up for ever, so two seconds after the exit the run ends anyway.
228 let finish: @Sendable (Bool) -> Void = { [self] force in // on `q`
229 guard !finished, let status, (outDone && errDone) || force else { return }
230 finished = true
231 out.fileHandleForReading.readabilityHandler = nil
232 err.fileHandleForReading.readabilityHandler = nil
233 take(Data(), flush: true).forEach(onLine)
234 onExit(status)
235 keepAlive = nil
236 }
237 out.fileHandleForReading.readabilityHandler = { [self] fh in
238 let d = fh.availableData
239 q.sync {
240 guard !finished else { return }
241 if d.isEmpty { fh.readabilityHandler = nil; outDone = true; finish(false) }
242 else { take(d).forEach(onLine) }
243 }
244 }
245 err.fileHandleForReading.readabilityHandler = { [self] fh in
246 let d = fh.availableData
247 q.sync {
248 guard !finished else { return }
249 if d.isEmpty { fh.readabilityHandler = nil; errDone = true; finish(false) }
250 else { complain(String(decoding: d, as: UTF8.self).trimmingCharacters(in: .newlines)) }
251 }
252 }
253 proc.terminationHandler = { [self] p in
254 let code = p.terminationStatus
255 q.async { [self] in status = code; finish(false) }
256 q.asyncAfter(deadline: .now() + 2) { finish(true) }
257 }
258 // Launching and "was it stopped?" are one step: a stop() that came first means the command is never
259 // launched, and one that comes after finds it running and ends it. There is no moment in between.
260 stateLock.lock()
261 if stopAsked {
262 stateLock.unlock()
263 out.fileHandleForReading.readabilityHandler = nil
264 err.fileHandleForReading.readabilityHandler = nil
265 q.async { [self] in
266 guard !finished else { return }
267 finished = true
268 onExit(Self.notStarted)
269 keepAlive = nil
270 }
271 return
272 }
273 do {
274 defer { stateLock.unlock() }
275 try proc.run()
276 started = true
277 } catch {
278 out.fileHandleForReading.readabilityHandler = nil
279 err.fileHandleForReading.readabilityHandler = nil
280 q.async { [self] in
281 guard !finished else { return }
282 finished = true
283 complain("could not start: \(error.localizedDescription)"); onExit(127)
284 keepAlive = nil
285 }
286 }
287 }
288
289 /// The exit status given for a command that was stopped before it was started: it never ran.
290 static let notStarted: Int32 = 130
291
292 /// Ends the command. Asked before `start`, the command is never launched (`onExit` gets `notStarted`). Asked
293 /// after the command has ended by itself, what it left running in its group is ended. `isGone` says when it and
294 /// what it started are gone.
295 func stop() {
296 stateLock.lock(); stopAsked = true; let running = started; stateLock.unlock()
297 if running { end() }
298 }
299
300 /// How long a command gets to end by itself after it was asked to, before it is ended by force.
301 static let graceToEnd: TimeInterval = 5
302
303 /// Asks the command and every process it started to end (SIGTERM: the processes below it, the deepest first,
304 /// and its process group when it has its own). Whatever of them is still there after `graceToEnd` is ended by
305 /// force (SIGKILL), see `leftBehind`. The command itself may have ended already: what it left running in its
306 /// group is ended all the same.
307 private func end() {
308 let root = proc.processIdentifier, alive = proc.isRunning
309 let all = Self.processes()
310 let seen = alive ? Self.descendants(of: [root], in: all) : []
311 stateLock.lock()
312 let before = atStop?.seen ?? [] // asked to end a second time: what the first look saw is kept
313 atStop = (root, before + seen.filter { p in !before.contains { $0.pid == p.pid && $0.started == p.started } })
314 stateLock.unlock()
315 for p in seen.reversed() { kill(p.pid, SIGTERM) }
316 if alive {
317 if grouped { kill(-root, SIGTERM) } // the group exists as long as the command runs, so the number is ours
318 proc.terminate()
319 } else {
320 for p in groupMembers(root, in: all) { kill(p.pid, SIGTERM) }
321 }
322 DispatchQueue.global().asyncAfter(deadline: .now() + Self.graceToEnd) { [self] in
323 for p in leftBehind().reversed() { kill(p.pid, SIGKILL) }
324 }
325 }
326
327 /// The members of the command's process group, as long as the group is still the command's own. A group keeps
328 /// its number while one member lives, and no new process is given a number that a group still has. So when
329 /// the command has ended and a process with its number is there, the old group is gone and the number is
330 /// somebody else's.
331 private func groupMembers(_ root: Int32, in now: [Running]) -> [Running] {
332 guard grouped else { return [] }
333 if !proc.isRunning, now.contains(where: { $0.pid == root }) { return [] }
334 return now.filter { $0.group == root }
335 }
336
337 /// What is still running of a command that was asked to end: the command itself; the processes that were below
338 /// it at the stop (when the process id still belongs to the same process); the members of its process group,
339 /// which holds also what was started while it was ending and what it left behind when it ended; and
340 /// everything below any of these. Parents first. A process that left both the command's tree and its group
341 /// before it was looked for is not found.
342 func leftBehind() -> [Running] {
343 stateLock.lock(); let at = atStop; stateLock.unlock()
344 guard let at else { return [] }
345 let now = Self.processes()
346 var mine: [Running] = [], have = Set<Int32>()
347 func add(_ list: [Running]) { for p in list where !have.contains(p.pid) { have.insert(p.pid); mine.append(p) } }
348 if proc.isRunning, let leader = now.first(where: { $0.pid == at.root }) { add([leader]) }
349 add(at.seen.filter { was in now.contains { $0.pid == was.pid && $0.started == was.started } }) // not a new process under an old number
350 add(groupMembers(at.root, in: now))
351 add(Self.descendants(of: mine.map(\.pid), in: now))
352 return mine
353 }
354
355 /// The command is not running, and when it was asked to end, what it started is gone too (as far as `leftBehind`
356 /// can see). A command that ended by itself and was never asked to end counts as gone.
357 var isGone: Bool { !proc.isRunning && leftBehind().isEmpty }
358
359 struct Running: Equatable { var pid: Int32; var parent: Int32; var group: Int32; var started: String }
360
361 /// Every process on this Mac that is still running (not one that has ended and only waits to be collected): its
362 /// id, its parent, its process group and when it started (as `ps` prints it).
363 static func processes() -> [Running] {
364 let p = Process(), pipe = Pipe()
365 p.executableURL = URL(fileURLWithPath: "/bin/ps"); p.arguments = ["-axo", "pid=,ppid=,pgid=,stat=,lstart="]
366 p.standardOutput = pipe; p.standardError = FileHandle.nullDevice
367 guard (try? p.run()) != nil else { return [] }
368 let text = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
369 p.waitUntilExit()
370 return text.split(separator: "\n").compactMap { line in
371 let f = line.split(separator: " ", maxSplits: 4, omittingEmptySubsequences: true)
372 guard f.count == 5, let pid = Int32(f[0]), let parent = Int32(f[1]), let group = Int32(f[2]), !f[3].hasPrefix("Z") else { return nil }
373 return Running(pid: pid, parent: parent, group: group, started: f[4].trimmingCharacters(in: .whitespaces))
374 }
375 }
376
377 /// The processes started by any of `roots`, directly or through others, parents before children. The roots
378 /// themselves are not in the list.
379 static func descendants(of roots: [Int32], in all: [Running]) -> [Running] {
380 var found: [Running] = [], next = roots, seen = Set(roots)
381 while let parent = next.first {
382 next.removeFirst()
383 for c in all where c.parent == parent && !seen.contains(c.pid) { seen.insert(c.pid); found.append(c); next.append(c.pid) }
384 }
385 return found
386 }
387}
388
389/// Personal agent on this Mac (default: Claude Code using the user's existing subscription login).
390/// Understands Claude Code's stream-json events; any other command's output is shown as plain text.
391enum AgentEvents {
392 /// How many lines of one tool's output are kept for the screen; the rest is counted, not shown.
393 static let outputLines = 60
394
395 /// One line of an agent's output as transcript messages, in order. A line that is not one of the Claude CLI's
396 /// JSON events (another agent's plain text) is shown as it is, at every level.
397 /// what the agent says "assistant", always shown
398 /// a tool it uses "tool" from "steps" on: "▸ Bash"; `more` holds the command, file or search
399 /// what a tool gave back "tool" at "output": the first `outputLines` lines (`AgentDetail.shown` heads it)
400 /// What the agent says in one event stays one message, as it was before the levels: words are split only
401 /// where a tool step stands between them.
402 /// an error that ends the run "note", always shown
403 static func messages(_ line: String) -> [ChatMessage] {
404 guard line.hasPrefix("{"), let d = line.data(using: .utf8),
405 let j = try? JSONSerialization.jsonObject(with: d) as? [String: Any] else {
406 return line.isEmpty ? [] : [ChatMessage(role: line.hasPrefix("!") ? "note" : "assistant", text: line)]
407 }
408 let parts = ((j["message"] as? [String: Any])?["content"] as? [[String: Any]]) ?? []
409 switch j["type"] as? String {
410 case "assistant":
411 var out: [ChatMessage] = [], words: [String] = []
412 func flush() { if !words.isEmpty { out.append(ChatMessage(role: "assistant", text: words.joined(separator: "\n"))); words = [] } }
413 for p in parts {
414 switch p["type"] as? String {
415 case "text": if let t = p["text"] as? String, !t.isEmpty { words.append(t) }
416 case "tool_use":
417 flush()
418 out.append(ChatMessage(role: "tool", text: "▸ " + (p["name"] as? String ?? "tool"), detail: .steps,
419 more: behind(p["input"] as? [String: Any] ?? [:]), call: p["id"] as? String))
420 default: break
421 }
422 }
423 flush()
424 return out
425 case "user": // what the tools gave back
426 return parts.compactMap { p -> ChatMessage? in
427 guard p["type"] as? String == "tool_result" else { return nil }
428 // Text is shown; anything else that came back (a picture, a document) is named, never passed over.
429 let text = (p["content"] as? String)
430 ?? ((p["content"] as? [[String: Any]]) ?? []).map { b in
431 (b["text"] as? String) ?? "(\(b["type"] as? String ?? "other") content, not shown)"
432 }.joined(separator: "\n")
433 let lines = text.split(separator: "\n", omittingEmptySubsequences: false)
434 let kept = lines.prefix(outputLines).joined(separator: "\n")
435 let rest = lines.count > outputLines ? "\n(\(lines.count - outputLines) more lines)" : ""
436 let failed = p["is_error"] as? Bool == true
437 return ChatMessage(role: "tool", text: (failed ? "failed\n" : "") + (kept.isEmpty ? "(nothing)" : kept) + rest, detail: .output,
438 call: p["tool_use_id"] as? String)
439 }
440 case "result":
441 if j["is_error"] as? Bool == true { return [ChatMessage(role: "note", text: "! " + (j["result"] as? String ?? "agent error"))] }
442 return [] // the final text was already streamed as an assistant message
443 default:
444 return []
445 }
446 }
447
448
449 /// What the tool says went wrong, when the line is its own report of a failure (Claude Code's result event with
450 /// `is_error`); nil for every other line, also for a text that merely starts like an error.
451 static func failure(_ line: String) -> String? {
452 guard line.hasPrefix("{"), let d = line.data(using: .utf8), let j = try? JSONSerialization.jsonObject(with: d) as? [String: Any],
453 j["type"] as? String == "result", j["is_error"] as? Bool == true else { return nil }
454 return j["result"] as? String ?? "agent error"
455 }
456 static func render(_ line: String) -> String? {
457 guard line.hasPrefix("{"), let d = line.data(using: .utf8),
458 let j = try? JSONSerialization.jsonObject(with: d) as? [String: Any] else { return line }
459 switch j["type"] as? String {
460 case "assistant":
461 let parts = ((j["message"] as? [String: Any])?["content"] as? [[String: Any]]) ?? []
462 let s = parts.compactMap { p -> String? in
463 switch p["type"] as? String {
464 case "text": return p["text"] as? String
465 case "tool_use": return "▸ " + (p["name"] as? String ?? "tool")
466 default: return nil
467 }
468 }.joined(separator: "\n")
469 return s.isEmpty ? nil : s
470 case "result":
471 if j["is_error"] as? Bool == true { return "! " + (j["result"] as? String ?? "agent error") }
472 return nil // the final text was already streamed as an assistant message
473 default:
474 return nil
475 }
476 }
477}
478
479enum Shell {
480 /// Single-quotes a string for a POSIX shell.
481 static func quote(_ s: String) -> String { "'" + s.replacingOccurrences(of: "'", with: "'\\''") + "'" }
482
483 /// Runs a command on another computer over ssh (the user's own ssh setup decides the route).
484 static func ssh(host: String, _ remote: String) -> CommandRun {
485 CommandRun(["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=8", "-o", "ServerAliveInterval=15", host, remote])
486 }
487}