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

1463 lines · 102023 bytes Raw Blame History
1import Foundation
2
3/// A mind Hop may hand a request to: an installed agent tool, or a model server from `models`.
4/// Written in the settings as `fusionSeats`; when that list is empty Hop works the seats out from
5/// the agents and models that are set up (see `Fusion.seats`).
6struct FusionSeat: Codable, Hashable {
7 var name: String
8 /// What to run. {prompt} is replaced by the text (one argument). Empty when `model` is used.
9 var command: [String] = []
10 /// The name of an entry in `models` (answers only, changes nothing on this Mac).
11 var model: String = ""
12 /// 1 instant, 2 fast, 3 strong, 4 frontier.
13 var tier: Int = 3
14 /// Who makes the model: local, anthropic, openai, google, xai, or any other word.
15 var family: String = "other"
16 /// What one call costs next to the others (any unit; only the order matters).
17 var cost: Int = 10
18 /// May be given work that changes files and runs tools on this Mac. It says what the seat is offered, not
19 /// what its command is able to do: any command needs the person's yes before it runs (`Fusion.Seat.needsYes`).
20 var act: Bool = false
21 /// Hop's own chat-only command (Claude's small model with its tools switched off). Never read from the
22 /// settings: a command the person wrote is never taken to be harmless on its word.
23 var chatOnly = false
24
25 enum CodingKeys: String, CodingKey { case name, command, model, tier, family, cost, act }
26
27 init(name: String, command: [String] = [], model: String = "", tier: Int = 3, family: String = "other", cost: Int = 10, act: Bool = false, chatOnly: Bool = false) {
28 self.name = name; self.command = command; self.model = model; self.tier = tier; self.family = family; self.cost = cost; self.act = act
29 self.chatOnly = chatOnly
30 }
31 init(from decoder: Decoder) throws {
32 let c = try decoder.container(keyedBy: CodingKeys.self)
33 name = try c.decode(String.self, forKey: .name)
34 command = try c.decodeIfPresent([String].self, forKey: .command) ?? []
35 model = try c.decodeIfPresent(String.self, forKey: .model) ?? ""
36 tier = try c.decodeIfPresent(Int.self, forKey: .tier) ?? 3
37 family = try c.decodeIfPresent(String.self, forKey: .family) ?? "other"
38 cost = try c.decodeIfPresent(Int.self, forKey: .cost) ?? 10
39 act = try c.decodeIfPresent(Bool.self, forKey: .act) ?? false
40 }
41}
42
43/// The small Omegese record a mind ends its reply with, so the next step is decided from numbers
44/// and not from prose:
45///
46/// note hop record
47/// fn confidence to ulong
48/// ret 870000
49/// end
50///
51/// Only `fn NAME to ulong`, `ret N`, `end` are read. Anything else after the marker ends the record.
52struct FusionRecord {
53 static let marker = "note hop record"
54 var fields: [String: UInt64] = [:]
55 var body: String = ""
56 var present: Bool { !fields.isEmpty }
57
58 static func parse(_ text: String) -> FusionRecord {
59 let lines = text.components(separatedBy: "\n")
60 guard let at = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespaces) == marker }) else {
61 return FusionRecord(fields: [:], body: text.trimmingCharacters(in: .whitespacesAndNewlines))
62 }
63 var fields: [String: UInt64] = [:]
64 var i = at + 1
65 while i + 2 < lines.count {
66 let a = lines[i].trimmingCharacters(in: .whitespaces).split(separator: " ")
67 let b = lines[i + 1].trimmingCharacters(in: .whitespaces).split(separator: " ")
68 let c = lines[i + 2].trimmingCharacters(in: .whitespaces)
69 guard a.count == 4, a[0] == "fn", a[2] == "to", a[3] == "ulong", a[1].allSatisfy({ $0.isASCII && $0.isLowercase }),
70 b.count == 2, b[0] == "ret", b[1].count <= 19, let n = UInt64(b[1]), c == "end" else { break }
71 fields[String(a[1])] = n
72 i += 3
73 }
74 var before = Array(lines[..<at])
75 while let last = before.last, last.trimmingCharacters(in: .whitespaces).isEmpty { before.removeLast() }
76 // A record put in a code fence: the fence line that opens it goes too. A fence that closes real code (an even
77 // number of fence lines so far) is part of the reply and stays.
78 let fences = before.filter { $0.trimmingCharacters(in: .whitespaces).hasPrefix("```") }.count
79 if let last = before.last, last.trimmingCharacters(in: .whitespaces).hasPrefix("```"), fences % 2 == 1 { before.removeLast() }
80 let body = before.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)
81 return FusionRecord(fields: fields, body: body)
82 }
83}
84
85/// Text that arrives in pieces from several threads, kept in order as it came.
86final class PieceBox: @unchecked Sendable {
87 private let l = NSLock()
88 private var s = ""
89 func add(_ piece: String) { l.lock(); s += piece; l.unlock() }
90 var text: String { l.lock(); defer { l.unlock() }; return s }
91}
92
93/// One line that waits to be shown until the line after it is known.
94final class Pending: @unchecked Sendable {
95 private let l = NSLock()
96 private var line: String?
97 func put(_ s: String) { l.lock(); line = s; l.unlock() }
98 func take() -> String? { l.lock(); defer { line = nil; l.unlock() }; return line }
99}
100
101/// A flag several threads may raise and read.
102final class Raised: @unchecked Sendable {
103 private let l = NSLock()
104 private var on = false
105 func raise() { l.lock(); on = true; l.unlock() }
106 var isUp: Bool { l.lock(); defer { l.unlock() }; return on }
107}
108
109/// Hop's chooser, hopfuse (Omega/hopfuse.om, contract in Omega/FUSE.md), behind plain Swift values.
110enum FuseCore {
111 static let magic: UInt64 = 1212568915
112 static let none = UInt64.max
113
114 struct Plan {
115 var verdict: UInt64 // 1 invalid, 2 refused, 3 direct, 4 single, 5 ladder, 6 fusion
116 var reason: UInt64
117 var fault: UInt64
118 var tier: UInt64
119 var level: UInt64
120 var chosen: [Int] // seat ids, in order
121 var synthesizer: Int?
122 var executor: Int?
123 var rounds: Int
124 var flags: UInt64 // 1 unknown difficulty, 2 unsure triage, 4 high stakes, 8 no fusion possible, 16 below wanted tier, 32 limited seat
125 /// Set by the host, not by the core: this plan was made among the person's own models alone (`Fusion.plan`).
126 var ownFirst = false
127 }
128 struct Judgement {
129 var verdict: UInt64 // 1 invalid, 7 consensus, 8 another round, 9 settle, 10 one voice, 11 none
130 var usable: [Int]
131 var deltas: Int
132 var dissenters: Int
133 }
134 /// One seat as the core sees it.
135 struct Row { var id: Int; var tier: Int; var family: Int; var cost: Int; var state: Int; var caps: Int }
136 /// One mind's reply to a round as the core sees it. status: 1 answered, 2 failed, 3 timed out, 4 no record.
137 struct Reply { var id: Int; var status: Int; var confidence: Int; var deltas: Int; var agree: Bool }
138
139 static func call(_ words: [UInt64]) -> (status: UInt32, verdict: UInt64, out: [UInt64]) {
140 var input = words + [UInt64](repeating: 0, count: max(0, 256 - words.count))
141 input = Array(input.prefix(256))
142 var output = [UInt64](repeating: 0, count: 256)
143 var result: UInt64 = 0
144 let status = input.withUnsafeBufferPointer { a in
145 output.withUnsafeMutableBufferPointer { b in
146 omega_hopfuse(&result, a.baseAddress, UInt64(a.count), b.baseAddress, UInt64(b.count))
147 }
148 }
149 return (status, result, output)
150 }
151
152 static func plan(_ rows: [Row], kind: Int, difficulty: Int, stakes: Int, confidence: Int, most: Int, escalations: Int, flags: Int) -> Plan {
153 var w: [UInt64] = [magic, 1, 1, UInt64(rows.count), UInt64(kind), UInt64(difficulty), UInt64(stakes), UInt64(confidence),
154 UInt64(most), UInt64(escalations), UInt64(flags), 0, 0, 0, 0, 0]
155 for r in rows { w += [r.id, r.tier, r.family, r.cost, r.state, r.caps].map { UInt64(max(0, $0)) } }
156 let (status, _, o) = rows.count > 16 ? (UInt32(32), UInt64(0), [UInt64](repeating: 0, count: 256)) : call(w)
157 guard status == 0, o[0] == magic, o[1] == 1 else { // refused or trapped: shown as invalid, never as a plan
158 return Plan(verdict: 1, reason: UInt64(status), fault: 0, tier: 0, level: 0, chosen: [], synthesizer: nil, executor: nil, rounds: 0, flags: 0)
159 }
160 let m = Int(min(o[7], 8))
161 return Plan(verdict: o[2], reason: o[3], fault: o[4], tier: o[5], level: o[6], chosen: o[16..<(16 + m)].map { Int($0) },
162 synthesizer: o[8] == none ? nil : Int(o[8]), executor: o[9] == none ? nil : Int(o[9]), rounds: Int(min(o[10], 3)), flags: o[12])
163 }
164
165 static func judge(_ replies: [Reply], round: Int, most: Int) -> Judgement {
166 var w: [UInt64] = [magic, 1, 2, UInt64(replies.count), UInt64(round), UInt64(most)] + [UInt64](repeating: 0, count: 10)
167 for r in replies { w += [UInt64(r.id), UInt64(r.status), UInt64(min(max(r.confidence, 0), 1_000_000)), UInt64(min(max(r.deltas, 0), 1000)), r.agree ? 1 : 0, 0] }
168 let (status, _, o) = replies.count > 8 ? (UInt32(32), UInt64(0), [UInt64](repeating: 0, count: 256)) : call(w)
169 guard status == 0, o[0] == magic, o[1] == 1, o[2] != 1 else { return Judgement(verdict: 1, usable: [], deltas: 0, dissenters: 0) }
170 let u = Int(min(o[5], 8))
171 return Judgement(verdict: o[2], usable: o[16..<(16 + u)].map { Int($0) }, deltas: Int(o[6]), dissenters: Int(o[8]))
172 }
173}
174
175/// Text that arrives in pieces and is shown as it comes, except what Hop must not show: the record a mind ends
176/// its reply with (FusionRecord: everything from the last marker line on), a code fence opened just for that
177/// record, the blank lines before it, blank lines before the first line, and the line end after the last line.
178/// What it has shown when the reply is over is `FusionRecord.parse(reply).body` for the replies minds give; where
179/// the two differ (spaces around the reply, a fence between two markers) `Fusion.run` puts the kept reply on screen.
180final class LiveText: @unchecked Sendable {
181 private let l = NSLock()
182 private let emit: @Sendable (String) -> Void
183 private var line = "" // the line being written
184 private var sent = 0 // how many of its characters were already shown
185 private var waiting = "" // whole lines held back until what follows is known: blank lines, a fence that opens
186 private var inCode = false // between a fence that opened and the one that closes it
187 private var done = false // the reply is over
188 private var owed = "" // line ends not shown yet: they go out with what follows, so a reply never ends in one
189 private var any = false // something was shown
190 private var all = "" // everything shown so far
191 /// What was shown so far. The run compares it with the reply it keeps and puts the kept one on screen when they differ.
192 var text: String { l.lock(); defer { l.unlock() }; return all }
193 /// From a marker line on, the text is held: it is the record unless another marker line follows, and then it
194 /// was part of the reply after all. `heldBefore` is what was waiting when the marker came.
195 private var held: String?
196 private var heldBefore = ""
197
198 init(_ emit: @escaping @Sendable (String) -> Void) { self.emit = emit }
199
200 private func show(_ s: String) {
201 var out = owed + waiting + s
202 waiting = ""; owed = ""
203 if !any { // nothing on screen yet: blank lines in front are not shown
204 while let nl = out.firstIndex(of: "\n"), out[..<nl].allSatisfy({ $0 == " " || $0 == "\t" }) { out = String(out[out.index(after: nl)...]) }
205 }
206 while out.hasSuffix("\n") { out.removeLast(); owed += "\n" }
207 if out.isEmpty { if !any { owed = "" }; return }
208 any = true
209 all += out
210 emit(out)
211 }
212 private static func isFence(_ line: String) -> Bool { line.trimmingCharacters(in: .whitespaces).hasPrefix("```") }
213
214 /// What was held turned out to be part of the reply: it is shown as it was written.
215 private func release() {
216 guard let h = held else { return }
217 for part in h.components(separatedBy: "\n") where Self.isFence(part) { inCode.toggle() }
218 waiting = heldBefore + waiting
219 held = nil; heldBefore = ""
220 show(h)
221 }
222
223 func add(_ piece: String) {
224 l.lock(); defer { l.unlock() }
225 guard !done else { return }
226 line += piece
227 while let nl = line.firstIndex(of: "\n") {
228 let whole = String(line[..<nl])
229 line = String(line[line.index(after: nl)...])
230 let trimmed = whole.trimmingCharacters(in: .whitespaces)
231 if held != nil {
232 if trimmed == FusionRecord.marker { release(); held = whole + "\n" } // a later marker: the record starts here instead
233 else { held? += whole + "\n" }
234 } else if sent > 0 { // already on screen in part: the rest follows
235 if Self.isFence(whole) { inCode.toggle() }
236 show(String(whole.dropFirst(sent)) + "\n"); sent = 0
237 } else if trimmed == FusionRecord.marker { // the record: it, a fence opened just for it and the blank lines before it stay off screen
238 held = whole + "\n"; heldBefore = waiting; waiting = ""
239 } else if trimmed.isEmpty {
240 waiting += whole + "\n"
241 } else if Self.isFence(whole) {
242 if inCode { show(whole + "\n") } // it closes code that is on screen
243 else { waiting += whole + "\n" } // it opens: code, or a wrapping of the record; the next line tells
244 inCode.toggle()
245 } else {
246 show(whole + "\n")
247 }
248 }
249 if held != nil { return }
250 // The line so far is shown as it grows, unless it may still turn out to be blank, the marker or an opening fence.
251 let trimmed = line.trimmingCharacters(in: .whitespaces)
252 if sent == 0, trimmed.isEmpty || FusionRecord.marker.hasPrefix(trimmed) || (!inCode && trimmed.hasPrefix("`")) { return }
253 show(String(line.dropFirst(sent)))
254 sent = line.count
255 }
256
257 /// The reply is over. What was held back because it might have been the start of a record is shown after all;
258 /// the record itself and blank lines at the very end are not.
259 func finish() {
260 l.lock(); defer { l.unlock() }
261 guard !done else { return }
262 done = true
263 let trimmed = line.trimmingCharacters(in: .whitespaces)
264 if held != nil {
265 if trimmed == FusionRecord.marker { release() } // the last marker is the last line: what was held before it is reply
266 return
267 }
268 if trimmed == FusionRecord.marker, sent == 0 { return }
269 if !trimmed.isEmpty { show(String(line.dropFirst(sent))) }
270 else if !waiting.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { show("") }
271 }
272}
273
274/// Hop picks the mind for a request, or several and fuses them. The Agent screen calls it through `Pick`
275/// (Sources/Pick.swift); on the command line it is `hop fuse <what you want>`.
276enum Fusion {
277 /// What the triage found. 0 means unknown, and unknown is never read as easy.
278 struct Triage: Equatable {
279 var kind = 1; var difficulty = 0; var stakes = 0; var confidence = 0; var exact: String? = nil; var by = ""
280 /// The minds that were asked to sort it and gave nothing usable, and why ("" = none were asked in vain).
281 var tried = ""
282 /// The minds found busy while sorting: they are not asked again for the answer to this message.
283 var busy: Set<String> = []
284 }
285 /// Why a mind did not answer, when it is one of these two: neither is a fault of the mind, so it is not left out afterwards.
286 static let busyWhy = "it is busy with something else", stoppedWhy = "it was stopped"
287 static let noCreditWhy = "its account has no credit left", signedOutWhy = "it is not signed in", quotaWhy = "its account is out of quota for now"
288 static let notStartedWhy = "the tool could not be started", noReplyWhy = "it gave no reply"
289 static let stillThereWhy = "a tool that Hop stopped is still running"
290 /// What a command is asked before it is given a request, when it has not shown lately that it is ready: a
291 /// question that needs no work, so a tool that is signed out or out of credit says so on this and not on the
292 /// request. The reply must hold the word.
293 static let probePrompt = "Reply with exactly one word: ready. Do not use any tools."
294 /// A tool that is signed in answers one word well within a minute; one that waits for a login never does.
295 static let probeTime: TimeInterval = 60
296 /// The answer to the test question: a line that is the word and nothing else (letter case, quotes and a full stop
297 /// aside). "not ready" and "already signed out" are not it.
298 static func saysReady(_ text: String) -> Bool {
299 text.split(whereSeparator: \.isNewline).contains { $0.trimmingCharacters(in: CharacterSet.letters.inverted).lowercased() == "ready" }
300 }
301
302 struct Seat {
303 var id: Int; var seat: FusionSeat; var endpoint: ModelEndpoint?; var ready: Bool
304 /// Why it is not ready, when Hop knows (it failed a short while ago).
305 var why = ""
306 /// May be given work that changes things on this Mac: an agent tool the settings offer for that. A model
307 /// server only answers.
308 var acts: Bool { seat.act && endpoint == nil }
309 /// A command on this Mac: it runs only after the person's yes to agent tools, whatever the settings say it
310 /// is for. The exceptions are a model server (a network request, nothing runs here) and Hop's own
311 /// chat-only command.
312 var needsYes: Bool { endpoint == nil && !seat.chatOnly }
313 /// The person's own model: a model server on this Mac or their network.
314 var own: Bool { endpoint.map { $0.place != .online } ?? false }
315 /// Hop may ask it the test question before a request: one of the agent tools Hop knows by name, with a
316 /// command that takes what it is asked as text. Such a tool does what the text says, so the question costs
317 /// it one word. Any other command (the person's own, or one with no place for the text) is run with the
318 /// request only: it might do its work whatever it is asked, and then the question would do that work once
319 /// and the request a second time.
320 /// A command with no place for what it is asked (`{prompt}`): it does its one thing every time it is run,
321 /// whatever the request. It is run once for a request, by itself, and is never part of a fusion, where every
322 /// mind is asked several things.
323 var fixed: Bool { endpoint == nil && !seat.command.contains { $0.contains("{prompt}") } }
324 var askable: Bool {
325 needsYes && seat.command.contains { $0.contains("{prompt}") } && known[((seat.command.first ?? "") as NSString).lastPathComponent] != nil
326 }
327 }
328 struct Answer {
329 var ok: Bool; var timedOut: Bool; var text: String; var seconds: Double; var why: String = ""
330 var tokens = 0 // as the server or the tool reported them; 0 when it reported none
331 var model: String? = nil // the model id it named, when it named one
332 var session: String? = nil // the tool's own session, when it has one that can be carried on
333 var shown: String? = nil // what was put on screen of it as it came (nil: it was not shown as it came)
334 }
335
336 /// Lets a run be stopped from outside: every tool it started is ended and no new one is started.
337 final class Control: @unchecked Sendable {
338 private let l = NSLock()
339 private var off = false
340 private var cancels: [UUID: @Sendable () -> Void] = [:]
341 private var working: [ObjectIdentifier: CommandRun] = [:], cut: [CommandRun] = [], kept: [CommandRun] = []
342 /// Commands that the run before this one stopped. No command of this run is started while one of them, or
343 /// anything it started, is still running (`CommandRun.isGone`).
344 let earlier: [CommandRun]
345 init(earlier: [CommandRun] = []) { self.earlier = earlier }
346 /// The commands of this run that were working when it was stopped.
347 var stoppedCommands: [CommandRun] { l.lock(); defer { l.unlock() }; return cut }
348 /// Commands of this run that Hop ended itself (their time was up, or they had only been asked the test
349 /// question) and of which something is still running all the same. No command is started while that is so,
350 /// in this run or in the next (`leftRunning` is what the next run is given).
351 var unended: [CommandRun] { l.lock(); defer { l.unlock() }; return kept }
352 func keep(_ run: CommandRun) { l.lock(); kept.append(run); l.unlock() }
353 /// Everything of this run that may still be running when it is over: what a Stop cut off, and what could not be ended.
354 var leftRunning: [CommandRun] { l.lock(); defer { l.unlock() }; return cut + kept }
355 func began(_ run: CommandRun) { l.lock(); working[ObjectIdentifier(run)] = run; l.unlock() }
356 /// A command is over: its way to be stopped and its place among the working ones go in one step.
357 func finished(_ hold: UUID, _ run: CommandRun) { l.lock(); cancels[hold] = nil; working[ObjectIdentifier(run)] = nil; l.unlock() }
358 /// Waits until the commands in `runs` and what they started are gone, `limit` seconds at most. true: gone.
359 static func gone(_ runs: [CommandRun], within limit: TimeInterval, unless stop: @Sendable () -> Bool = { false }) async -> Bool {
360 let until = Date().addingTimeInterval(limit)
361 var left = runs.filter { !$0.isGone }
362 while !left.isEmpty, Date() < until, !stop() {
363 try? await Task.sleep(nanoseconds: 200_000_000)
364 left = left.filter { !$0.isGone }
365 }
366 return left.isEmpty
367 }
368 var isStopped: Bool { l.lock(); defer { l.unlock() }; return off }
369 /// Registers how to end one piece of running work. When the run was already stopped, it is ended at once.
370 func hold(_ cancel: @escaping @Sendable () -> Void) -> UUID {
371 let id = UUID()
372 l.lock(); let stopped = off; if !stopped { cancels[id] = cancel }; l.unlock()
373 if stopped { cancel() }
374 return id
375 }
376 func release(_ id: UUID) { l.lock(); cancels[id] = nil; l.unlock() }
377 func stop() {
378 l.lock(); off = true; cut += working.values; let all = Array(cancels.values); cancels.removeAll(); l.unlock()
379 all.forEach { $0() }
380 }
381 }
382
383 /// Who answered a request and how it was sorted: where "Stronger" starts from.
384 struct Standing: Equatable {
385 var triage: Triage
386 var tier: Int // the tier of the mind that answered
387 var by: String
388 var fused: Bool // several minds were fused: nothing is stronger than that
389 var reply: String
390 }
391
392 /// One request, with what goes along with it.
393 struct Ask {
394 var text: String
395 var history: [ChatMessage] = [] // the conversation before it (user and assistant messages)
396 var brief = "" // standing instructions for a mind that acts
397 var notes = "" // what the person's knowledge base has on it ("" = nothing)
398 var notesForClaudeChat = true // false = Claude's chat-only model gets no notes (`cortex.contextForClaudeAsk`)
399 var owner = "the user"
400 var above: Standing? = nil // "Stronger": the same request again, one step above this
401 var resting: [String: String] = [:] // minds that failed a short while ago, and why: not asked again yet
402 var resume: [String: String] = [:] // a mind's own tool session that holds this conversation so far
403 var force: Triage? = nil // skip the sorting (command line)
404 var assessmentOnly = false // model/chat-only seats; never run a file-capable command
405 var proven: Set<String> = [] // commands that showed a short while ago that they are ready: not asked the test question again
406 var probeTime = Fusion.probeTime // how long a command has for the test question (the checks shorten it)
407 var previousKind: Int? = nil // how the message before this one was sorted (1 answer, 2 make, 3 act)
408 /// What is said when the yes is not given and a tool was about to run.
409 var declinedNote = "You said no to running an agent tool on this Mac, so nothing was run."
410 }
411
412 /// Tokens as the minds reported them (or, for a model server that reports none, a rough count), by where
413 /// the request went. Every call of a run is counted: the sorting, answers that were discarded, each mind of a fusion.
414 final class Meter: @unchecked Sendable {
415 private let l = NSLock()
416 private var by: [ModelEndpoint.Place: Int] = [:]
417 func add(_ tokens: Int, at place: ModelEndpoint.Place) { guard tokens > 0 else { return }; l.lock(); by[place, default: 0] += tokens; l.unlock() }
418 var totals: [ModelEndpoint.Place: Int] { l.lock(); defer { l.unlock() }; return by }
419 }
420
421 /// How a run ended, and what the caller keeps for the next one.
422 struct End {
423 /// The commands that showed in this run that they are ready (they answered the test question, or the request).
424 var proved: Set<String> = []
425 var outcome = PickOutcome(ok: false, by: "", meta: "", acted: false, strongerLeft: false)
426 var standing: Standing? = nil
427 var reply = ""
428 var usage: [ModelEndpoint.Place: Int] = [:] // tokens of every call of the run, by where it went (`Meter`)
429 var failed: [String: String] = [:] // minds that could not do it this time, and why
430 var session: (seat: String, id: String)? = nil
431 }
432
433 // MARK: seats
434
435 /// Tier, family and cost for the tools Hop knows by name. Nothing here is measured (Omega/FUSE.md, Limits).
436 static let known: [String: (tier: Int, family: String, cost: Int)] = [
437 "claude": (4, "anthropic", 100), "codex": (4, "openai", 100), "agy": (4, "google", 80), "gemini": (3, "google", 40),
438 "grok": (3, "xai", 60), "muse": (3, "meta", 50), "omp": (4, "pool", 100), "opencode": (3, "opencode", 50),
439 "cursor-agent": (3, "cursor", 60), "hermes": (3, "hermes", 50),
440 ]
441 static let families = ["local": 1, "anthropic": 2, "openai": 3, "google": 4, "xai": 5]
442 /// The chooser plans at most this many seats (Omega/FUSE.md).
443 static let mostSeats = 16
444
445 /// The seats as the settings give them: `fusionSeats` as written, or one per model server and per installed
446 /// agent. An own model (on this Mac or the person's network) comes first and costs next to nothing, so it is
447 /// the mind Hop starts with whenever it can do the work.
448 /// The model a Claude Code command names (`--model x` or `--model=x`); nil when it names none.
449 static func claudeModel(_ command: [String]) -> String? {
450 if let i = command.firstIndex(of: "--model"), i + 1 < command.count { return command[i + 1] }
451 return command.first { $0.hasPrefix("--model=") }.map { String($0.dropFirst("--model=".count)) }
452 }
453 /// The tier of a Claude model by the tool's own names for them; nil for a name Hop does not know.
454 static func claudeTier(_ model: String) -> Int? {
455 let m = model.lowercased()
456 return m.contains("haiku") ? 2 : m.contains("sonnet") ? 3 : m.contains("opus") || m.contains("fable") ? 4 : nil
457 }
458 static func list(_ cfg: HopConfig, installed: [AgentEngine]) -> [FusionSeat] {
459 if !cfg.fusionSeats.isEmpty { return cfg.fusionSeats }
460 var list: [FusionSeat] = []
461 // A model server. One marked "rewrite": false (too small to trust with text) is left out. An own model
462 // counts as strong unless the settings give it a tier; one reached online counts as fast.
463 // `preferOwnModel: false` in the settings keeps own models out of the choice.
464 for m in cfg.models where m.kind == "openai" && m.rewrite && (cfg.preferOwnModel ?? true || m.place == .online) {
465 let own = m.place != .online
466 list.append(FusionSeat(name: m.name, model: m.name, tier: m.tier ?? (own ? 3 : 2), family: own ? "local" : "online",
467 cost: own || m.cost == "free" ? 1 : 30, act: false))
468 }
469 let tools = installed.filter { !$0.isHopItself }
470 for e in tools {
471 // What the settings say about an agent wins; else Hop's table for the tool; else a strong mind of middling cost.
472 let base = (e.tool as NSString).lastPathComponent, k = known[base]
473 var command = e.command, tier = e.tier ?? k?.tier ?? 3
474 if base == "claude" {
475 // Claude Code runs whichever model its command names, or the tool's own default. Hop's table takes the
476 // tool for Claude's strong model, so the seat says which: a command that names no model is given
477 // "opus" (the tool's name for it), and one that names a model has that model's tier. So "Stronger"
478 // from Claude's middle model is another model, not the same one under another name.
479 if let named = claudeModel(e.command) { if e.tier == nil { tier = claudeTier(named) ?? tier } }
480 else { command += ["--model", "opus"] }
481 }
482 list.append(FusionSeat(name: e.name, command: command, tier: tier, family: e.family ?? k?.family ?? e.tool,
483 cost: e.cost ?? k?.cost ?? 50, act: true))
484 }
485 let chatFlags = ["--tools", "", "--strict-mcp-config", "--output-format", "stream-json", "--verbose", "--include-partial-messages"]
486 if !tools.contains(where: { ($0.tool as NSString).lastPathComponent == "claude" }) {
487 // No Claude agent in the settings, but a model entry for Claude through its CLI (what the old model list
488 // offered as "Claude (your subscription)"): it still answers, chat only, with the model it names.
489 for m in cfg.models where m.kind == "claude-cli" && m.rewrite {
490 let model = m.model.isEmpty ? "sonnet" : m.model, small = model.lowercased().contains("haiku")
491 list.append(FusionSeat(name: m.name, command: ["claude", "-p", "{prompt}", "--model", model] + chatFlags,
492 tier: m.tier ?? (small ? 2 : 3), family: "anthropic", cost: small ? 8 : 30, act: false, chatOnly: true))
493 }
494 }
495 if let claude = tools.first(where: { ($0.tool as NSString).lastPathComponent == "claude" }) {
496 // Claude's small model, chat only (no tools: it starts fast and changes nothing), for sorting and simple
497 // answers; and its middle model with the person's own Claude command, for standard work. "haiku" and
498 // "sonnet" are the tool's own names for them.
499 list.append(FusionSeat(name: "Claude Haiku", command: [claude.tool, "-p", "{prompt}", "--model", "haiku"] + chatFlags,
500 tier: 2, family: "anthropic", cost: 8, act: false, chatOnly: true))
501 if claudeModel(claude.command) == nil {
502 list.append(FusionSeat(name: "Claude Sonnet", command: claude.command + ["--model", "sonnet"], tier: 3, family: "anthropic", cost: 30, act: true))
503 }
504 }
505 return list
506 }
507
508 /// The seats for this Mac, each marked ready or not, and the names of the minds that were left out because
509 /// the chooser plans `mostSeats` at a time (minds that are ready are taken first, in the order of the settings).
510 struct Table { var seats: [Seat] = []; var leftOut: [String] = [] }
511
512 static func seats(_ cfg: HopConfig, installed: [AgentEngine], resting: [String: String] = [:]) async -> [Seat] {
513 await table(cfg, installed: installed, resting: resting).seats
514 }
515
516 /// `resting` names minds that failed a short while ago, and why: they are listed as not ready.
517 static func table(_ cfg: HopConfig, installed: [AgentEngine], resting: [String: String] = [:]) async -> Table {
518 let list = list(cfg, installed: installed)
519 var all: [Seat] = []
520 let onPath = await which(Set(list.compactMap { $0.model.isEmpty ? $0.command.first : nil }))
521 for s in list {
522 let ep = s.model.isEmpty ? nil : cfg.models.first { $0.name == s.model && $0.kind == "openai" }
523 if let why = resting[s.name] { all.append(Seat(id: 0, seat: s, endpoint: ep, ready: false, why: why)); continue }
524 if !s.model.isEmpty {
525 guard let ep else { all.append(Seat(id: 0, seat: s, endpoint: nil, ready: false, why: "no model server of that name is in the settings")); continue }
526 all.append(Seat(id: 0, seat: s, endpoint: ep, ready: await reachable(ep)))
527 } else {
528 all.append(Seat(id: 0, seat: s, endpoint: nil, ready: onPath.contains(s.command.first ?? "")))
529 }
530 }
531 var table = Table()
532 if all.count > mostSeats { // more than the chooser plans: the ready ones first, and the rest is named, never dropped in silence
533 let order = all.filter(\.ready) + all.filter { !$0.ready }
534 table.leftOut = order.dropFirst(mostSeats).map(\.seat.name)
535 let kept = Set(order.prefix(mostSeats).map(\.seat.name))
536 all = all.filter { kept.contains($0.seat.name) }
537 if all.count > mostSeats { table.leftOut += all.dropFirst(mostSeats).map(\.seat.name); all = Array(all.prefix(mostSeats)) } // two seats of one name
538 }
539 table.seats = all.enumerated().map { i, seat in var x = seat; x.id = i + 1; return x }
540 return table
541 }
542
543 /// Which of these tools the login shell can find (the same lookup the Agent screen uses).
544 static func which(_ tools: Set<String>) async -> Set<String> {
545 let list = tools.filter { !$0.isEmpty }.sorted()
546 guard !list.isEmpty else { return [] }
547 let box = LineBox()
548 let script = list.map { "command -v \(Shell.quote($0)) >/dev/null 2>&1 && echo \(Shell.quote($0))" }.joined(separator: "\n") + "\ntrue"
549 let _: Int32 = await withCheckedContinuation { c in
550 CommandRun(["sh", "-c", script]).start(onLine: { box.add($0) }, onExit: { c.resume(returning: $0) })
551 }
552 return Set(box.text.split(separator: "\n").map(String.init))
553 }
554
555 /// A model server counts as ready when it answers its model list within two seconds.
556 static func reachable(_ ep: ModelEndpoint) async -> Bool {
557 var base = ep.baseURL.trimmingCharacters(in: .whitespaces)
558 while base.hasSuffix("/") { base.removeLast() }
559 guard let url = URL(string: base + "/models") else { return false }
560 var req = URLRequest(url: url, timeoutInterval: 2)
561 if let k = ep.keychainKey, let tok = Vault.secret(k) { req.setValue("Bearer \(tok)", forHTTPHeaderField: "Authorization") }
562 guard let (_, resp) = try? await Net.session.data(for: req), let h = resp as? HTTPURLResponse else { return false }
563 return h.statusCode < 500
564 }
565
566 static func rows(_ seats: [Seat]) -> [FuseCore.Row] {
567 var extra: [String: Int] = [:]
568 var out: [FuseCore.Row] = []
569 for s in seats {
570 let f = s.seat.family.lowercased()
571 var code = families[f] ?? extra[f] ?? 0
572 if code == 0 { code = min(31, 6 + extra.count); extra[f] = code } // a family Hop has no name for gets the next free number
573 out.append(FuseCore.Row(id: s.id, tier: min(max(s.seat.tier, 1), 4), family: code, cost: min(max(s.seat.cost, 0), 1_000_000),
574 state: s.ready ? 1 : 3, caps: s.acts ? 3 : 1))
575 }
576 return out
577 }
578
579 /// The plan for a sorted request. `down` are seats that failed during this run. With `above` it is the plan
580 /// for "Stronger": only minds of a higher tier than the one that answered; when that one was already of the
581 /// highest tier that is ready, several strong minds fused; after a fusion, nothing (verdict 2, reason 82).
582 static func plan(_ t: Triage, _ seats: [Seat], down: Set<Int>, cfg: HopConfig, above: Standing? = nil) -> FuseCore.Plan {
583 let first = planned(t, seats, down: down, cfg: cfg, above: above, neverFuse: false)
584 // A fusion asks each mind several things (to propose, to fuse, to look at the draft). A command with no place
585 // for what it is asked would do its one thing each time, so it is never part of one: the fusion is planned
586 // without such commands, and when there is none without them, one mind does the work.
587 let fixed = Set(seats.filter(\.fixed).map(\.id))
588 guard first.verdict == 6, !fixed.isDisjoint(with: first.chosen + [first.synthesizer, first.executor].compactMap { $0 }) else { return first }
589 let without = planned(t, seats, down: down.union(fixed), cfg: cfg, above: above, neverFuse: false)
590 return without.verdict == 6 ? without : planned(t, seats, down: down, cfg: cfg, above: above, neverFuse: true)
591 }
592 private static func planned(_ t: Triage, _ seats: [Seat], down: Set<Int>, cfg: HopConfig, above: Standing?, neverFuse: Bool) -> FuseCore.Plan {
593 var r = rows(seats).map { row -> FuseCore.Row in var x = row; if down.contains(x.id) { x.state = 3 }; return x }
594 let most = min(max(cfg.fusionMaxSeats, 1), 8), escalations = min(max(cfg.fusionEscalations, 0), 3)
595 func core(_ flags: Int) -> FuseCore.Plan { // flag bit 2: never fuse
596 FuseCore.plan(r, kind: t.kind, difficulty: t.difficulty, stakes: t.stakes, confidence: t.confidence, most: most, escalations: escalations,
597 flags: neverFuse ? flags + (flags & 4 == 0 ? 4 : 0) : flags)
598 }
599 guard let above else {
600 // Own model first: while an own model is ready and the request is something to answer or write, the plan is
601 // made among the own models alone (every other seat counts as down, and nothing is fused). When that model
602 // fails or says it is unsure, the caller marks it down and the plan below, among all the others, follows.
603 let own = Set(seats.filter { $0.own && $0.ready && !down.contains($0.id) }.map(\.id))
604 if t.exact == nil, t.kind != 3, !own.isEmpty {
605 let only = r.map { row -> FuseCore.Row in var x = row; if !own.contains(x.id) { x.state = 3 }; return x }
606 var first = FuseCore.plan(only, kind: t.kind, difficulty: t.difficulty, stakes: t.stakes, confidence: t.confidence, most: 1, escalations: 0, flags: 4)
607 if [4, 5].contains(first.verdict) { first.ownFirst = true; return first }
608 }
609 return core(t.exact == nil ? 0 : 1)
610 }
611 let nothing = FuseCore.Plan(verdict: 2, reason: 82, fault: 0, tier: 0, level: 0, chosen: [], synthesizer: nil, executor: nil, rounds: 0, flags: 0)
612 if above.fused { return nothing }
613 let need = t.kind == 3 ? 2 : 1
614 if r.contains(where: { $0.state == 1 && $0.tier > above.tier && $0.caps & need != 0 }) {
615 r = r.map { row in var x = row; if x.tier <= above.tier { x.state = 3 }; return x }
616 return core(0)
617 }
618 if neverFuse { return nothing }
619 let fused = core(2) // flag bit 1: a fusion is asked for
620 return fused.verdict == 6 ? fused : nothing
621 }
622
623 // MARK: triage
624
625 /// A plain sum the Mac can do itself: digits, + - * / and brackets. nil for anything else.
626 static func arithmetic(_ text: String) -> String? {
627 var t = text.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
628 for lead in ["what is ", "what's ", "whats ", "calculate ", "compute "] where t.hasPrefix(lead) { t = String(t.dropFirst(lead.count)) }
629 while let l = t.last, "?= ".contains(l) { t.removeLast() }
630 t = t.replacingOccurrences(of: "×", with: "*").replacingOccurrences(of: "÷", with: "/").replacingOccurrences(of: " x ", with: " * ")
631 // A date or a number with dashes (2026-11-10, 555-01-99) is not a sum: two minus signs with no space around either.
632 if t.range(of: #"\d-\d+-\d"#, options: .regularExpression) != nil { return nil }
633 // Nor is a number that starts with 0 and another digit (555-0199, 007): people do not write sums that way.
634 if t.range(of: #"(^|[^0-9.])0[0-9]"#, options: .regularExpression) != nil { return nil }
635 let chars = Array(t.filter { $0 != " " })
636 guard chars.count >= 3, chars.count <= 80, chars.allSatisfy({ "0123456789.+-*/()".contains($0) }),
637 chars.contains(where: { "+-*/".contains($0) }), chars.contains(where: { $0.isNumber }) else { return nil }
638 var i = 0
639 // Worked out in whole-number fractions, so no step rounds: 0.1 + 0.2 is 3/10, and a large number added and
640 // taken away again leaves exactly what was there. A sum with a number of more than 15 digits, one that passes
641 // 10^15 on the way, or one whose fraction outgrows 64 bits is left to a mind.
642 struct Q { var n: Int64; var d: Int64 } // n/d, d > 0, in lowest terms
643 let limit: Int64 = 1_000_000_000_000_000
644 func q(_ n: Int64, _ d: Int64) -> Q? {
645 guard d != 0, n != .min, d != .min else { return nil }
646 var a = abs(n), b = abs(d)
647 while b != 0 { (a, b) = (b, a % b) }
648 let v = Q(n: (d < 0 ? -n : n) / a, d: abs(d) / a)
649 guard abs(v.n) / v.d < limit else { return nil }
650 return v
651 }
652 func times(_ a: Int64, _ b: Int64) -> Int64? { let (v, over) = a.multipliedReportingOverflow(by: b); return over ? nil : v }
653 func plus(_ a: Int64, _ b: Int64) -> Int64? { let (v, over) = a.addingReportingOverflow(b); return over ? nil : v }
654 func add(_ a: Q, _ b: Q, sign: Int64) -> Q? {
655 guard let x = times(a.n, b.d), let y = times(b.n, a.d), let ys = times(y, sign), let n = plus(x, ys), let d = times(a.d, b.d) else { return nil }
656 return q(n, d)
657 }
658 func number() -> Q? {
659 let start = i
660 while i < chars.count, chars[i].isNumber || chars[i] == "." { i += 1 }
661 let part = chars[start..<i], digits = part.filter(\.isNumber)
662 guard !digits.isEmpty, digits.count <= 15, part.filter({ $0 == "." }).count <= 1, digits.allSatisfy(\.isASCII), let n = Int64(String(digits)) else { return nil }
663 var d: Int64 = 1
664 if let dot = part.firstIndex(of: ".") { for _ in 0..<(part.endIndex - dot - 1) { d *= 10 } }
665 return q(n, d)
666 }
667 func factor() -> Q? {
668 guard i < chars.count else { return nil }
669 if chars[i] == "-" { i += 1; return factor().flatMap { q(-$0.n, $0.d) } }
670 if chars[i] == "(" { i += 1; guard let v = sum(), i < chars.count, chars[i] == ")" else { return nil }; i += 1; return v }
671 return number()
672 }
673 func product() -> Q? {
674 guard var v = factor() else { return nil }
675 while i < chars.count, chars[i] == "*" || chars[i] == "/" {
676 let op = chars[i]; i += 1
677 guard let r = factor() else { return nil }
678 let (rn, rd) = op == "/" ? (r.d, r.n) : (r.n, r.d)
679 guard rd != 0, let n = times(v.n, rn), let d = times(v.d, rd), let next = q(n, d) else { return nil }
680 v = next
681 }
682 return v
683 }
684 func sum() -> Q? {
685 guard var v = product() else { return nil }
686 while i < chars.count, chars[i] == "+" || chars[i] == "-" {
687 let op = chars[i]; i += 1
688 guard let r = product(), let next = add(v, r, sign: op == "+" ? 1 : -1) else { return nil }
689 v = next
690 }
691 return v
692 }
693 guard let v = sum(), i == chars.count else { return nil }
694 if v.d == 1 { return String(v.n) }
695 // Shown only when the digits shown are the whole answer (0.5, 0.3 for 0.1 + 0.2), ten after the point at
696 // most; 1/3 has no end and is left to a mind.
697 var places = 0, scale: Int64 = 1
698 while scale % v.d != 0 { guard places < 10 else { return nil }; scale *= 10; places += 1 }
699 guard let whole = times(abs(v.n), scale / v.d) else { return nil }
700 let frac = String(whole % scale)
701 return (v.n < 0 ? "-" : "") + String(whole / scale) + "." + String(repeating: "0", count: places - frac.count) + frac
702 }
703
704 /// What can be told from the words alone. It only ever raises what the triage says, never lowers it.
705 static func floor(_ text: String) -> (kind: Int, difficulty: Int) {
706 // Words are matched between spaces, so a line break or a full stop does not hide them ("Please fix.").
707 let t = " " + String(text.lowercased().map { $0.isLetter || $0.isNumber || $0 == "'" || $0 == "’" ? $0 : " " }) + " "
708 func has(_ words: [String]) -> Bool { words.contains { t.contains($0) } }
709 let words = text.split(whereSeparator: { $0 == " " || $0 == "\n" }).count
710 var d = 0, k = 0
711 // "How do I delete a branch?" asks; "can you delete the branch?" and "delete the branch" tell. Only one
712 // sentence can ask: "What a mess. Delete the branch." and "Is it green? If so, deploy it." tell, and so does
713 // "explain the failure and fix it". When in doubt the words tell (kind 3 is the careful path).
714 let lead = text.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
715 let tells = ["can you ", "could you ", "would you ", "will you ", "please ", "why don't you ", "why don’t you ", "why not "].contains { lead.hasPrefix($0) }
716 let body = String(lead.reversed().drop(while: { ".?!".contains($0) }).reversed())
717 let oneSentence = !body.contains("\n") && body.range(of: #"[.?!]\s"#, options: .regularExpression) == nil
718 let asks = !tells && oneSentence && (lead.hasSuffix("?") || ["how ", "what ", "why ", "when ", "where ", "which ", "who ", "is ", "are ", "does "].contains { lead.hasPrefix($0) })
719 if words > 40 { d = 3 }
720 if has([" build ", " implement", " refactor", " write a ", " write an ", " create a ", " draft ", " plan ", " debug", " migrate", " review "]) { d = 3 }
721 if has([" design", " website", " landing page", " brand", " logo", " strategy", " architecture", " redesign"]) { d = 5 }
722 if has([" fix ", " install ", " run ", " deploy", " commit", " rename ", " delete ", " move ", " refactor", " implement", " in the repo", " on this mac", " on my mac"]), !asks { k = 3 }
723 else if has([" write ", " draft ", " design", " compose ", " outline ", " create "]) { k = 2 }
724 return (k, d)
725 }
726
727 static let triagePrompt = """
728 You sort one request for a router. Do not answer the request. Reply with only this Omegese record, with your numbers in place of K, D, S and C:
729
730 note hop record
731 fn kind to ulong
732 ret K
733 end
734 fn difficulty to ulong
735 ret D
736 end
737 fn stakes to ulong
738 ret S
739 end
740 fn confidence to ulong
741 ret C
742 end
743
744 K: 1 a question to answer in words. 2 something to write or design in the reply (text, a plan, a page, code). 3 work that must change files or run commands on the computer.
745 D: 1 trivial (a fact, a sum, a one-line reply). 2 simple. 3 standard. 4 hard (careful reasoning or expert knowledge). 5 open-ended creative or design work where strong minds would give different good answers.
746 S: 1 low. 2 normal. 3 high (money, safety, law, hard to undo, or published under the person's name).
747 C: how sure you are, from 0 to 1000000.
748
749 Request:
750
751 """
752
753 /// The end of the conversation, for the sorting: the last four messages, each cut to 600 characters. Sorting is
754 /// a small question put to a cheap mind, so it is not given the whole conversation; the mind that answers is.
755 static func tail(_ history: [ChatMessage]) -> [ChatMessage] {
756 history.filter { $0.role == "user" || $0.role == "assistant" }.suffix(4).map {
757 ChatMessage(role: $0.role, text: $0.text.count > 600 ? String($0.text.prefix(600)) + " [cut]" : $0.text)
758 }
759 }
760
761 /// A short go-ahead and nothing else: "yes", "ok do it", "go ahead", "please do that", "run it". Six words at
762 /// most, every one of them a word of consent or of doing, at least one of them a yes or a doing word, and not a
763 /// question ("Do you know French?" and "is that ok?" are not).
764 static func goAhead(_ text: String) -> Bool {
765 let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
766 guard !trimmed.hasSuffix("?") else { return false }
767 let words = trimmed.lowercased().split(whereSeparator: { !$0.isLetter && $0 != "'" && $0 != "’" }).map(String.init)
768 guard !words.isEmpty, words.count <= 6 else { return false }
769 let yes: Set<String> = ["yes", "yep", "yeah", "ok", "okay", "sure", "alright", "proceed", "go", "do", "run", "apply", "continue"]
770 let filler: Set<String> = ["please", "it", "that", "this", "ahead", "for", "now", "then", "so", "and", "thanks", "sounds", "good", "great", "fine", "perfect", "right", "all", "let's", "let’s", "lets", "just", "on"]
771 let known = yes.union(filler)
772 return words.allSatisfy(known.contains) && words.contains(where: yes.contains)
773 }
774
775 /// Sorts one message. `history` is the conversation before it: "yes, do that" can only be sorted with it.
776 /// Only a model server or Hop's own chat-only command sorts: a command from the settings never does (it would
777 /// be one more tool that sees the request before the one that does the work). `previousKind` is how the
778 /// message before was sorted: when nobody can sort this one and it follows work that changes things, or is a
779 /// short go-ahead after any conversation, it is taken as such work too (the careful side).
780 static func triage(_ intent: String, _ seats: [Seat], cwd: String, control: Control = Control(), history: [ChatMessage] = [],
781 previousKind: Int? = nil, meter: Meter? = nil) async -> Triage {
782 if let exact = arithmetic(intent) { return Triage(kind: 1, difficulty: 1, stakes: 1, confidence: 1_000_000, exact: exact, by: "this Mac") }
783 let low = floor(intent)
784 var t = Triage(), vain: [String] = []
785 // Model servers and Hop's own chat-only command sort the request: the person's own model first, then the
786 // cheapest; the first, and one more if the first gives no usable record. A mind of the highest tier is not
787 // spent on sorting, unless it is the person's own: that one always gets the message first.
788 let maySort: (Seat) -> Bool = { $0.own ? true : $0.seat.tier <= 3 }
789 let sorters = seats.filter { $0.ready && !$0.acts && !$0.needsYes && maySort($0) }
790 .sorted { ($0.own ? 0 : 1, $0.seat.cost, $0.seat.tier) < ($1.own ? 0 : 1, $1.seat.cost, $1.seat.tier) }
791 let before = tail(history)
792 let prompt = before.isEmpty ? triagePrompt + intent
793 : String(triagePrompt.dropLast("Request:\n".count)) + talk(before)
794 + "Sort the last message below in the light of that conversation: a short yes or go-ahead after a plan to change files or run commands is work that changes things (K 3).\n\nRequest:\n" + intent
795 for s in sorters.prefix(2) where t.difficulty == 0 && !control.isStopped {
796 let a = await ask(s, prompt: prompt, timeout: 25, cwd: cwd, control: control, meter: meter)
797 let r = FusionRecord.parse(a.text)
798 if a.ok, let k = r.fields["kind"], let d = r.fields["difficulty"], let st = r.fields["stakes"], let c = r.fields["confidence"],
799 (1...3).contains(k), (1...5).contains(d), (1...3).contains(st), c <= 1_000_000 {
800 let busy = t.busy
801 t = Triage(kind: Int(k), difficulty: Int(d), stakes: Int(st), confidence: Int(c), exact: nil, by: s.seat.name)
802 t.busy = busy
803 } else {
804 vain.append("\(s.seat.name): " + (a.ok ? "no usable record" : a.timedOut ? "it ran out of time" : a.why))
805 if !a.ok, a.why == busyWhy { t.busy.insert(s.seat.name) }
806 }
807 }
808 if t.difficulty == 0 { // nobody sorted it: read the words, and say we are not sure
809 let words = intent.split(separator: " ").count
810 let busy = t.busy
811 // The careful side: a message that follows work that changed things, or a short go-ahead after anything
812 // ("yes, do that" after a plan), is taken as work that changes things. A model server never gets it then.
813 let follows = !before.isEmpty && (previousKind == 3 || goAhead(intent))
814 t = Triage(kind: low.kind == 0 ? (follows ? 3 : 1) : low.kind, difficulty: words <= 12 ? 2 : 3, stakes: 2, confidence: 650_000, exact: nil,
815 by: follows && low.kind == 0 ? "the words alone, as a go-ahead or a follow-up to work that changes things" : "the words alone")
816 t.busy = busy
817 }
818 if low.difficulty > t.difficulty { t.difficulty = low.difficulty }
819 if low.kind == 3 { t.kind = 3 } // "fix", "install", "deploy": the words say it changes things
820 t.tried = vain.joined(separator: "; ")
821 return t
822 }
823
824 // MARK: asking one seat
825
826 /// What a tool said about itself while it worked (Claude Code's stream-json names its session, model and tokens).
827 final class ToolFacts: @unchecked Sendable {
828 private let l = NSLock()
829 private var session: String?, model: String?, tokens = 0
830 func read(_ line: String) {
831 guard line.hasPrefix("{"), let j = try? JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any] else { return }
832 l.lock(); defer { l.unlock() }
833 if let s = j["session_id"] as? String, !s.isEmpty { session = s }
834 if model == nil, let m = AskRoute.reportedModel(j) { model = m }
835 if j["type"] as? String == "result", j["is_error"] as? Bool != true, let n = AppModel.claudeTokens(j) { tokens = n }
836 }
837 var all: (session: String?, model: String?, tokens: Int) { l.lock(); defer { l.unlock() }; return (session, model, tokens) }
838 }
839
840 /// The conversation so far, for a tool that takes one text.
841 static func talk(_ history: [ChatMessage]) -> String {
842 let turns = history.filter { ($0.role == "user" || $0.role == "assistant") && !$0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
843 guard !turns.isEmpty else { return "" }
844 return "The conversation so far, oldest first:\n\n" + turns.map { ($0.role == "user" ? "User: " : "Assistant: ") + $0.text.trimmingCharacters(in: .whitespacesAndNewlines) }.joined(separator: "\n\n") + "\n\n"
845 }
846
847 /// Runs one seat on one prompt and gives back what it said. `system` goes in front (a model server gets it as
848 /// its system message), `history` is the conversation before the prompt, `extra` are more arguments for a
849 /// tool. `timeout` nil = it may take as long as it needs (work that changes things; the person can stop it).
850 /// `live` gets the reply as it arrives, without the record at its end, and a tool's steps as progress lines.
851 static func ask(_ s: Seat, prompt: String, system: String = "", history: [ChatMessage] = [], extra: [String] = [],
852 timeout: TimeInterval?, cwd: String, control: Control = Control(), meter: Meter? = nil,
853 leavesNothing: Bool = false, live: (@Sendable (PickLine) -> Void)? = nil) async -> Answer {
854 let t0 = Date()
855 if control.isStopped { return Answer(ok: false, timedOut: false, text: "", seconds: 0, why: stoppedWhy) }
856 let shown = live.map { live in LiveText { live(.answer($0)) } }
857 if let ep = s.endpoint {
858 let box = PieceBox(), busy = Raised(), failure = PieceBox()
859 var messages = system.isEmpty ? [] : [ChatMessage(role: "system", text: system)]
860 messages += history.filter { $0.role == "user" || $0.role == "assistant" }
861 messages.append(ChatMessage(role: "user", text: prompt))
862 let asked = messages
863 let work = Task { () -> ModelClient.Reply? in
864 do { return try await ModelClient.streamReply(ep, history: asked) { d in box.add(d); shown?.add(d) } }
865 catch is ModelClient.Busy { busy.raise(); return nil }
866 catch { failure.add(error.localizedDescription); return nil }
867 }
868 let hold = control.hold { work.cancel() }
869 let timer = Task { if let timeout { try? await Task.sleep(nanoseconds: UInt64(timeout * 1e9)); work.cancel() } }
870 let got = await work.value
871 timer.cancel(); control.release(hold)
872 shown?.finish()
873 let text = box.text, secs = Date().timeIntervalSince(t0)
874 let ok = got != nil && !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
875 var why = ""
876 if !ok {
877 why = busy.isUp ? busyWhy : control.isStopped ? stoppedWhy
878 : got != nil ? "it gave no reply" : failure.text.isEmpty ? "it did not answer" : String(failure.text.prefix(160))
879 }
880 let counted = got?.tokens ?? 0
881 let tokens = counted > 0 ? counted : ok ? asked.reduce(Savings.estimate(text)) { $0 + Savings.estimate($1.text) } : 0
882 meter?.add(tokens, at: ep.place)
883 return Answer(ok: ok, timedOut: !ok && timeout.map { secs >= $0 } ?? false, text: text, seconds: secs, why: why, tokens: tokens, model: got?.model,
884 shown: shown?.text)
885 }
886 let whole = (system.isEmpty ? "" : system + "\n\n") + talk(history) + prompt
887 let argv = s.seat.command.map { $0 == "{prompt}" ? whole : $0.replacingOccurrences(of: "{prompt}", with: whole) } + extra
888 // A tool that Hop stopped (in the run before this one, or in this one when its time was up) is gone before
889 // another command starts: ended by itself, or by force after its grace. One that is still there after that
890 // could not be ended, and nothing is started beside it.
891 let before = control.earlier + control.unended
892 if before.contains(where: { !$0.isGone }) {
893 live?(.progress("Waiting for the tool that was stopped to be gone."))
894 let gone = await Control.gone(before, within: CommandRun.graceToEnd + 5) { control.isStopped }
895 if !gone, !control.isStopped { return Answer(ok: false, timedOut: false, text: "", seconds: Date().timeIntervalSince(t0), why: stillThereWhy) }
896 }
897 if control.isStopped { return Answer(ok: false, timedOut: false, text: "", seconds: Date().timeIntervalSince(t0), why: stoppedWhy) }
898 let launched = Date() // the time the tool itself took is counted from here, not from the wait
899 let box = LineBox(), pieces = PieceBox(), errors = PieceBox(), timedOut = Raised(), done = Raised(), facts = ToolFacts(), inPieces = Raised()
900 let toolFailed = Raised() // the tool itself reported that it failed (an error event), whatever its exit status says
901 let run = CommandRun(argv, cwd: cwd, ownGroup: true) // with everything it starts in one group, so Stop reaches all of it
902 control.began(run)
903 let hold = control.hold { run.stop() }
904 let code: Int32 = await withCheckedContinuation { c in
905 let once = OnceFlag()
906 run.start(onLine: { line in
907 for piece in line.components(separatedBy: "\n") {
908 facts.read(piece)
909 // A tool that sends its reply in small pieces (Claude Code asked for partial messages): each piece is
910 // shown as it comes, and the whole message that follows them is not shown a second time.
911 if let d = textDelta(piece) { inPieces.raise(); pieces.add(d); shown?.add(d); continue }
912 // The tool's own word that it failed (an error result event), told from the event and not from how a text begins.
913 if let failure = AgentEvents.failure(piece) { errors.add(failure + "\n"); toolFailed.raise(); continue }
914 guard let text = AgentEvents.render(piece), !text.isEmpty else { continue }
915 box.add(text)
916 for part in text.components(separatedBy: "\n") {
917 if part.hasPrefix("▸ ") { live?(.progress(part)) } // a step the tool takes, not part of its answer
918 else if !inPieces.isUp { shown?.add(part + "\n") }
919 }
920 if inPieces.isUp { pieces.add("\n"); shown?.add("\n") } // that message is whole: the next one starts on a new line
921 }
922 }, onError: { errors.add($0 + "\n") }, // the tool's error stream: kept out of the answer
923 onExit: { code in done.raise(); if once.take() { c.resume(returning: code) } })
924 if let timeout {
925 DispatchQueue.global().asyncAfter(deadline: .now() + timeout) {
926 if !done.isUp { timedOut.raise(); run.stop() }
927 }
928 }
929 }
930 let seconds = Date().timeIntervalSince(launched)
931 // A command that was ended here because its time was up, and one that was only asked the test question
932 // (`leavesNothing`), leaves nothing running: what it started is ended with it, and that is waited for before
933 // anything else is started. When it cannot be ended, the answer says so and nothing is started beside it.
934 var left = false
935 if timedOut.isUp || leavesNothing {
936 run.stop() // ended here; a Stop that comes during the wait below still finds this command among the working ones
937 left = !(await Control.gone([run], within: CommandRun.graceToEnd + 5) { control.isStopped })
938 if left, !control.isStopped { control.keep(run) } // it could not be ended: it stays known, so nothing is started beside it later either
939 }
940 // The command is over: it leaves the working ones and can no longer be stopped, in one step. A Stop finds it
941 // either working (and ends it) or not at all, never listed without a way to end it.
942 control.finished(hold, run)
943 shown?.finish()
944 let all = box.text
945 let text = inPieces.isUp ? pieces.text : all.components(separatedBy: "\n").filter { !$0.hasPrefix("▸ ") }.joined(separator: "\n")
946 let ok = code == 0 && !timedOut.isUp && !left && !toolFailed.isUp && !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !control.isStopped
947 let said = facts.all
948 meter?.add(said.tokens, at: .online)
949 return Answer(ok: ok, timedOut: timedOut.isUp, text: text, seconds: seconds,
950 why: ok ? "" : control.isStopped ? stoppedWhy : left ? stillThereWhy : reason(errors.text, code: toolFailed.isUp && code == 0 ? 1 : code),
951 tokens: said.tokens, model: said.model, session: said.session, shown: shown?.text)
952 }
953
954 /// The text of one small piece of a reply, when the line is such a piece (Claude Code's stream-json
955 /// `stream_event` with a `content_block_delta`); nil for any other line.
956 static func textDelta(_ line: String) -> String? {
957 guard line.hasPrefix("{"), line.contains("\"stream_event\""), let j = try? JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any],
958 j["type"] as? String == "stream_event", let ev = j["event"] as? [String: Any], ev["type"] as? String == "content_block_delta",
959 let t = (ev["delta"] as? [String: Any])?["text"] as? String else { return nil }
960 return t
961 }
962
963 /// One short line on why a tool failed, from what it wrote to its error stream.
964 static func reason(_ errors: String, code: Int32) -> String {
965 let low = errors.lowercased()
966 if low.contains("status: 402") || low.contains("payment required") || low.contains("insufficient") || low.contains("credits are depleted") { return noCreditWhy }
967 if low.contains("status: 401") || low.contains("status: 403") || low.contains("(401)") || low.contains("not logged in") || low.contains("unauthorized")
968 || low.contains("/login") || low.contains("missing meta credentials") || low.contains("expired credentials") { return signedOutWhy }
969 if low.contains("status: 429") || low.contains("rate limit") || low.contains("quota") { return quotaWhy }
970 if code == 127 { return notStartedWhy }
971 if code == 0 { return noReplyWhy }
972 let first = errors.split(separator: "\n").map { $0.trimmingCharacters(in: .whitespaces) }.first { !$0.isEmpty && !$0.hasPrefix("at ") } ?? ""
973 return first.isEmpty ? "it stopped with exit \(code)" : String(first.prefix(160))
974 }
975
976 // MARK: the words Hop sends
977
978 static let recordAsk = """
979
980
981 End your reply with exactly this block, with your own number (0 to 1000000, how sure you are that the reply is right and complete):
982
983 note hop record
984 fn confidence to ulong
985 ret N
986 end
987 """
988 static let deltaAsk = """
989
990
991 End your reply with exactly this block. D is how many changes you ask for (0 when the draft should stand), A is 1 when you agree with the draft as it is and 0 when you do not, N is how sure you are (0 to 1000000):
992
993 note hop record
994 fn deltas to ulong
995 ret D
996 end
997 fn agree to ulong
998 ret A
999 end
1000 fn confidence to ulong
1001 ret N
1002 end
1003 """
1004
1005 static func workPrompt(_ intent: String, brief: String, kind: Int) -> String {
1006 (brief.isEmpty ? "" : brief + "\n\n") + "Request: " + intent + (kind == 3 ? "" : recordAsk)
1007 }
1008 static func proposalPrompt(_ intent: String, brief: String, kind: Int) -> String {
1009 let rule = kind == 3
1010 ? "You are one of several minds asked the same thing. Do not change any file and do not run anything that changes this computer. Give your complete plan: the exact steps, commands and file contents you would use, and what could go wrong."
1011 : "You are one of several minds asked the same thing. Work alone and give your complete, best answer. Another mind will fuse the answers, so say what you are sure of and what you are not."
1012 return (brief.isEmpty ? "" : brief + "\n\n") + rule + "\n\nRequest: " + intent + recordAsk
1013 }
1014 static func fusePrompt(_ intent: String, proposals: [String], kind: Int) -> String {
1015 var s = "Several minds answered the same request, each alone. Fuse their answers into one that is better than any of them: keep what is strongest in each, settle where they disagree by reasoning (say so in one line where it matters), drop what is wrong, and do not mention the minds or this process. Give the finished "
1016 s += kind == 3 ? "plan, ready to carry out." : "answer."
1017 s += "\n\nRequest: " + intent
1018 for (i, p) in proposals.enumerated() { s += "\n\n=== Mind \(i + 1) ===\n" + p }
1019 return s
1020 }
1021 static func deltaPrompt(_ intent: String, draft: String) -> String {
1022 "This draft was fused from several answers to the request below, yours among them. Silence is agreement: if the draft should stand, write nothing but the block. Otherwise write only what must change, numbered, each with its reason. Do not rewrite the draft.\n\nRequest: " + intent + "\n\n=== Draft ===\n" + draft + deltaAsk
1023 }
1024 static func mergePrompt(_ intent: String, draft: String, deltas: [String], last: Bool) -> String {
1025 var s = "Here is a draft and the changes other minds ask for. Apply the changes that are right, refuse the ones that are wrong, and give the finished text in full. Do not mention the minds or this process."
1026 if last { s += " Where a disagreement could not be settled, say so in one plain line at the end." }
1027 s += "\n\nRequest: " + intent + "\n\n=== Draft ===\n" + draft
1028 for (i, d) in deltas.enumerated() { s += "\n\n=== Changes asked \(i + 1) ===\n" + d }
1029 return s
1030 }
1031
1032 // MARK: the run
1033
1034 static func why(_ p: FuseCore.Plan, _ t: Triage, strength: Bool = true) -> String {
1035 let level = ["", "trivial", "simple", "standard", "hard", "open-ended"][Int(min(p.level, 5))]
1036 var notes: [String] = []
1037 if p.flags & 1 != 0 { notes.append("it could not be sorted, so it is treated as standard at least") }
1038 if p.flags & 2 != 0 { notes.append("the sorting was unsure, so it is taken one step harder") }
1039 if p.flags & 4 != 0 { notes.append("the stakes are high, so it is taken one step harder") }
1040 // `strength: false` is for a plan made among the person's own models alone, where these two say nothing true.
1041 if strength, p.flags & 8 != 0 { notes.append("fewer than two strong minds are ready, so there is no fusion") }
1042 if strength, p.flags & 16 != 0 { notes.append("no mind of the wanted strength is ready, so the strongest one is used") }
1043 if p.flags & 32 != 0 { notes.append("a mind that is nearly out of quota is used") }
1044 return "sorted as \(level) by \(t.by)" + (notes.isEmpty ? "" : "; " + notes.joined(separator: "; "))
1045 }
1046
1047 /// What a mind is told before the request. One that acts gets the standing briefing and the knowledge-base
1048 /// notes; one that only answers gets the short-answer rule and the notes.
1049 static func system(for s: Seat, _ ask: Ask) -> String {
1050 if s.acts {
1051 return ask.brief + (ask.notes.isEmpty ? "" : (ask.brief.isEmpty ? "" : "\n\n") + "From \(ask.owner)'s knowledge base (Cortex), use if relevant:\n" + ask.notes)
1052 }
1053 let claudeChat = s.endpoint == nil && ((s.seat.command.first ?? "") as NSString).lastPathComponent == "claude"
1054 let notes = claudeChat && !ask.notesForClaudeChat ? "" : ask.notes
1055 return "Answer short. Plain words. No preamble." + (notes.isEmpty ? "" : "\n\n" + AppModel.cortexNotesHeader + notes)
1056 }
1057
1058 /// The request as a mind gets it. For "Stronger" it also says who replied before and what.
1059 static func request(_ ask: Ask) -> String {
1060 guard let above = ask.above, !above.reply.isEmpty else { return ask.text }
1061 return ask.text + "\n\n(\(above.by) already replied to this, and \(ask.owner) asked for a stronger mind. Its reply is below. Give your own complete reply; where it was wrong, say so in one line. If things were already changed on this computer, look at what is there before you change anything more.)\n\n=== Earlier reply ===\n" + above.reply
1062 }
1063
1064 /// The line for under a reply: where it ran (a model server), tokens when they were reported, time, who answered.
1065 static func meta(_ s: Seat, _ a: Answer) -> String {
1066 if let ep = s.endpoint { return AppModel.answerMeta(ep, tokens: a.tokens, seconds: a.seconds, who: AskRoute.who(ep, reported: a.model)) }
1067 let who = "answered by " + s.seat.name + (a.model.map { " (\($0))" } ?? "")
1068 return ([a.tokens > 0 ? "\(Savings.short(a.tokens)) tokens" : nil, String(format: "%.0f s", a.seconds), who] as [String?]).compactMap { $0 }.joined(separator: " · ")
1069 }
1070
1071 /// The whole thing: sort the request, plan, ask, hand on or fuse. `say` gets what there is to show as it
1072 /// comes. `mayAct` is asked once, before the first command on this Mac is started (the person's yes to agent
1073 /// tools; a model server and Hop's own chat-only command need none). With `planOnly` nothing is asked beyond
1074 /// the sorting and the plan is printed.
1075 static func run(_ ask: Ask, cfg: HopConfig, installed: [AgentEngine], planOnly: Bool = false, control: Control = Control(),
1076 mayAct: @escaping @Sendable (String) async -> Bool,
1077 say: @escaping @Sendable (PickLine) -> Void) async -> End {
1078 let cwd = cfg.agentWorkingDirectory, t0 = Date()
1079 var end = End()
1080 let meter = Meter()
1081 func close() -> End { end.usage = meter.totals; return end }
1082 let table = await table(cfg, installed: installed, resting: ask.resting)
1083 let seats = table.seats.filter { !ask.assessmentOnly || !$0.needsYes }
1084 var t: Triage
1085 if ask.assessmentOnly {
1086 t = Triage(kind: 2, difficulty: 3, stakes: 2, confidence: 1_000_000, by: "parking lot assessment")
1087 } else if let above = ask.above { t = above.triage; t.busy = [] } else if let force = ask.force { t = force }
1088 else { t = await triage(ask.text, seats, cwd: cwd, control: control, history: ask.history, previousKind: ask.previousKind, meter: meter) }
1089 guard !seats.isEmpty || t.exact != nil else {
1090 say(.problem(ask.assessmentOnly ? "No chat model is available to sort these ideas. Your parking lot is saved; file-changing tools will not be used." : "Hop has no mind to hand this to: no agent tool is installed and no model server is set in the settings.")); return close()
1091 }
1092 if !table.leftOut.isEmpty, !planOnly {
1093 say(.progress("Hop plans \(mostSeats) minds at a time and \(seats.count + table.leftOut.count) are set up. Not considered for this message: \(table.leftOut.joined(separator: ", ")). Fewer agents in the settings, or a `fusionSeats` list of your own, brings them back."))
1094 }
1095 // A mind that fails while it is asked is marked down and the chooser is asked again.
1096 var down: Set<Int> = []
1097 // No seat is given the request twice in one run: once it was given it, it counts as down in every plan that
1098 // follows (a later rung that turns out not to be ready must not send the request back to the first rung).
1099 var asked: Set<Int> = []
1100 /// The answer of the last mind that was not sure of it. It stands when nobody stronger can take the request.
1101 var unsure: (seat: Seat, answer: Answer, record: FusionRecord)?
1102 // One that was busy a moment ago, when it was asked to sort this message, is not asked again for the answer.
1103 for s in seats where t.busy.contains(s.seat.name) {
1104 down.insert(s.id); end.failed[s.seat.name] = busyWhy
1105 if !planOnly { say(.progress("\(s.seat.name) is busy with something else, so another mind is asked.")) }
1106 }
1107 /// After an answer that was not sure, only a mind of a higher tier follows it: "a stronger mind" is one that is
1108 /// stronger in Hop's own table, never one of the same tier that happens to be left. Every plan that is made
1109 /// after such an answer, and every rung that is still to come, is held to this one rule.
1110 func stronger(_ s: Seat) -> Bool { unsure.map { s.seat.tier > $0.seat.seat.tier } ?? true }
1111 func notStronger() -> Set<Int> { Set(seats.filter { !stronger($0) }.map(\.id)) }
1112 func makePlan() -> FuseCore.Plan { plan(t, seats, down: down.union(asked).union(notStronger()), cfg: cfg, above: ask.above) }
1113 var p = makePlan()
1114 func seat(_ id: Int) -> Seat? { seats.first { $0.id == id } }
1115 func names(_ ids: [Int]) -> String { ids.compactMap { seat($0)?.seat.name }.joined(separator: ", ") }
1116 if planOnly {
1117 for s in seats { say(.answer("seat \(s.id)\t\(s.seat.name)\ttier \(s.seat.tier)\t\(s.seat.family)\tcost \(s.seat.cost)\t\(s.ready ? "ready" : "not ready\(s.why.isEmpty ? "" : " (\(s.why))")")\t\(s.acts ? "acts" : "answers")\(s.own ? "\tyour own" : "")\n")) }
1118 if !table.leftOut.isEmpty { say(.answer("left out\t\(table.leftOut.joined(separator: ", "))\n")) }
1119 say(.answer("triage\tkind \(t.kind)\tdifficulty \(t.difficulty)\tstakes \(t.stakes)\tconfidence \(t.confidence)\tby \(t.by)\(t.tried.isEmpty ? "" : "\tasked in vain: " + t.tried)\n"))
1120 say(.answer("plan\tverdict \(p.verdict)\treason \(p.reason)\ttier \(p.tier)\tlevel \(p.level)\tchosen \(p.chosen)\(p.ownFirst ? " (your own model first)" : "")\tfused by \(p.synthesizer.map(String.init) ?? "-")\tcarried out by \(p.executor.map(String.init) ?? "-")\trounds \(p.rounds)\tflags \(p.flags)\n"))
1121 end.outcome.ok = p.verdict != 1
1122 return close()
1123 }
1124 func stopped() -> End { say(.problem("Stopped.")); return close() }
1125 func failed(_ s: Seat, _ a: Answer) -> String {
1126 let because = a.timedOut ? "it ran out of time" : a.why
1127 end.failed[s.seat.name] = because
1128 return because
1129 }
1130 // The person's yes to agent tools, asked once and only when a command is about to run.
1131 var consent: Bool? = nil
1132 var ranTool = false // a command ran on this Mac in this run (so its result is not kept for replay)
1133 func allowed(_ s: Seat) async -> Bool {
1134 guard s.needsYes else { return true }
1135 if consent == nil { consent = await mayAct(s.seat.name) }
1136 if consent == false {
1137 end.outcome.declined = true
1138 say(.problem(ask.declinedNote))
1139 }
1140 if consent == true { ranTool = true }
1141 return consent == true
1142 }
1143 func allowed(_ group: [Seat]) async -> Bool {
1144 for s in group where s.needsYes { return await allowed(s) }
1145 return true
1146 }
1147 /// Nothing but a record is not an answer.
1148 func heard(_ a: Answer) -> Answer {
1149 guard a.ok, FusionRecord.parse(a.text).body.isEmpty else { return a }
1150 var gone = a; gone.ok = false; gone.why = noReplyWhy
1151 return gone
1152 }
1153 /// A tool that Hop stopped (in the run before this one, or because its time was up) is still running and
1154 /// could not be ended: no command is started beside it, and the run ends.
1155 func blocked(_ a: Answer) -> Bool {
1156 guard a.why == stillThereWhy else { return false }
1157 say(.problem("A tool that Hop stopped is still running and could not be ended, so no tool was started beside it. End it yourself (Activity Monitor), then ask again."))
1158 return true
1159 }
1160 /// A command that was given the request and failed: nobody is started in its place, whatever the request
1161 /// and whatever the failure says. It may have changed something, Hop cannot see what, and a second tool
1162 /// would do it over. (A model server changes nothing: after one of those the next mind is asked.)
1163 func endsHere(_ s: Seat, _ because: String, doing: String = "stopped part way") -> Bool {
1164 guard s.needsYes else { return false }
1165 say(.problem("\(s.seat.name) \(doing): \(because). It may have changed things on this Mac, so no other tool was started. Look at what it did before asking again."))
1166 return true
1167 }
1168 /// Before an agent tool Hop knows (`Seat.askable`) is given the request it shows, on a question that asks
1169 /// for no work, that it is there and signed in with credit left; one that did so a short while ago
1170 /// (`Ask.proven`) is not asked again. A tool that is not ready is marked down and has not been given the
1171 /// request, so the next mind can take it. Whatever the question started is ended before anything else
1172 /// starts. false: not ready, choose again. nil: the run ends here.
1173 func ready(_ s: Seat) async -> Bool? {
1174 let name = s.seat.name
1175 guard s.askable, !ask.proven.contains(name), !end.proved.contains(name) else { return true }
1176 say(.progress("Hop is checking that \(name) is ready."))
1177 // Its reply to this is not part of the answer; a line about waiting for a stopped tool is passed on.
1178 let a = await Fusion.ask(s, prompt: probePrompt, timeout: ask.probeTime, cwd: cwd, control: control, meter: meter, leavesNothing: true,
1179 live: { line in if case .progress = line { say(line) } })
1180 if control.isStopped { return nil }
1181 if blocked(a) { return nil }
1182 if a.ok, saysReady(a.text) { end.proved.insert(name); return true }
1183 var gone = a
1184 if a.ok { gone.ok = false; gone.why = "it did not answer a test question" }
1185 down.insert(s.id)
1186 say(.progress("\(name) is not ready: \(failed(s, gone)). Choosing again."))
1187 return false
1188 }
1189 func halt() -> End { control.isStopped ? stopped() : close() }
1190 /// One mind's answer is the reply. `shownAgain`: it was taken off the screen when a stronger mind was asked, and
1191 /// is put back.
1192 func took(_ s: Seat, _ a: Answer, _ r: FusionRecord, shownAgain: Bool) -> End {
1193 let standing = Standing(triage: t, tier: min(max(s.seat.tier, 1), 4), by: s.seat.name, fused: false, reply: r.body)
1194 // What is on screen is the reply that is kept, to the letter.
1195 if shownAgain { say(.restart); say(.answer(r.body)) } else if let seen = a.shown, seen != r.body { say(.restart); say(.answer(r.body)) }
1196 end.outcome = PickOutcome(ok: true, by: s.seat.name, meta: meta(s, a), acted: ranTool, strongerLeft: strongerLeft(standing))
1197 end.standing = standing; end.reply = r.body
1198 if let sid = a.session { end.session = (s.seat.name, sid) }
1199 if s.needsYes { end.proved.insert(s.seat.name) }
1200 return close()
1201 }
1202 /// The run has no answer to give (and no command failed on the request). When a mind answered before and was
1203 /// not sure, that answer stands and is put back on screen; else the reason is all there is.
1204 func noAnswer(_ why: String) -> End {
1205 guard let u = unsure else { say(.problem(why)); return close() }
1206 say(.progress("\(why) So \(u.seat.seat.name)'s answer stands."))
1207 return took(u.seat, u.answer, u.record, shownAgain: true)
1208 }
1209 /// Is there anything stronger than what just answered? Asked of the chooser itself, with the same rules "Stronger" runs by.
1210 func strongerLeft(_ standing: Standing) -> Bool { [4, 5, 6].contains(plan(t, seats, down: down, cfg: cfg, above: standing).verdict) }
1211 func chose(_ s: Seat, _ i: Int) -> String {
1212 if i > 0 { return "the answer before was not sure enough" }
1213 if ask.above != nil { return "a stronger mind was asked for" }
1214 if p.ownFirst { return "your own model takes it first (\(why(p, t, strength: false)))" }
1215 return why(p, t)
1216 }
1217 // Every new plan follows a seat that was marked down, so the chooser is asked at most once per seat and
1218 // once more: it runs out of seats, not out of tries. The count below is that bound, kept as a guard.
1219 let most = seats.count + 1
1220 var tries = 0
1221 attempt: while true {
1222 tries += 1
1223 if tries > 1 { p = makePlan() }
1224 if control.isStopped { return stopped() }
1225 guard tries <= most + 1 else { return noAnswer("No mind could do it.") }
1226 if p.verdict == 2, unsure != nil { return noAnswer("No stronger mind could take it.") } // the answer that was not sure stands
1227 switch p.verdict {
1228 case 3:
1229 say(.answer(t.exact ?? ""))
1230 end.outcome = PickOutcome(ok: true, by: "this Mac", meta: "⚡ instant · worked out on this Mac, no model asked", acted: false, strongerLeft: false)
1231 end.reply = t.exact ?? ""
1232 return close()
1233 case 4, 5:
1234 for (i, id) in p.chosen.enumerated() {
1235 guard let s = seat(id) else { continue }
1236 if !stronger(s) { continue } // not stronger than the answer that was not sure
1237 guard await allowed(s) else { return close() }
1238 if control.isStopped { return stopped() }
1239 guard let isReady = await ready(s) else { return halt() }
1240 if !isReady { continue attempt }
1241 say(.progress("Hop chose \(s.seat.name): \(chose(s, i))"))
1242 // A tool that holds this conversation in its own session carries on there; any other mind is told it.
1243 let session = ask.above == nil ? ask.resume[s.seat.name] : nil
1244 asked.insert(id) // it is given the request now: never a second time in this run
1245 let a = await Fusion.ask(s, prompt: workPrompt(request(ask), brief: "", kind: t.kind), system: system(for: s, ask),
1246 history: session == nil ? ask.history : [], extra: session.map { ["--resume", $0] } ?? [],
1247 timeout: t.kind == 3 ? nil : 1800, cwd: cwd, control: control, meter: meter, live: say)
1248 if control.isStopped { return stopped() }
1249 if blocked(a) { return close() }
1250 let r = FusionRecord.parse(a.text)
1251 if !a.ok || r.body.isEmpty {
1252 let because = failed(s, heard(a))
1253 if endsHere(s, because) { return close() }
1254 down.insert(id)
1255 if !a.text.isEmpty { say(.restart) }
1256 say(.progress("\(s.seat.name) could not do it: \(because). Choosing again."))
1257 continue attempt
1258 }
1259 // An answer is taken unless its own record says it is unsure and a stronger mind is left to ask.
1260 let sure = t.kind == 3 || !r.present || (r.fields["confidence"] ?? 0) >= 700_000
1261 let last = i == p.chosen.count - 1
1262 if sure { return took(s, a, r, shownAgain: false) }
1263 unsure = (s, a, r)
1264 if last {
1265 // The last rung stands, unsure or not. The own model that went first is no rung of a ladder: after it
1266 // the plan among the stronger minds follows, when one of them can take the request.
1267 guard p.ownFirst, [4, 5, 6].contains(makePlan().verdict) else { return took(s, a, r, shownAgain: false) }
1268 }
1269 say(.progress("\(s.seat.name) was not sure of its answer. Asking a stronger mind."))
1270 say(.restart)
1271 if last { continue attempt }
1272 }
1273 return noAnswer(unsure == nil ? "No mind gave an answer." : "No stronger mind could take it.")
1274 case 6:
1275 let minds = p.chosen.compactMap(seat)
1276 guard await allowed(minds) else { return close() }
1277 // Every command among them shows first that it is ready. One that is not has not seen the request: it is
1278 // marked down and the chooser is asked again.
1279 var allReady = true
1280 for s in minds {
1281 guard let isReady = await ready(s) else { return halt() }
1282 if !isReady { allReady = false }
1283 }
1284 if !allReady { continue attempt }
1285 say(.progress("Hop is fusing \(minds.count) minds: \(names(p.chosen)) (\(ask.above != nil ? "a stronger answer was asked for" : why(p, t)))."))
1286 let question = request(ask)
1287 var got: [(Seat, Answer, FusionRecord)] = []
1288 await withTaskGroup(of: (Seat, Answer).self) { g in
1289 for s in minds {
1290 g.addTask { (s, await Fusion.ask(s, prompt: proposalPrompt(question, brief: "", kind: t.kind), system: system(for: s, ask), history: ask.history,
1291 timeout: 900, cwd: cwd, control: control, meter: meter)) }
1292 }
1293 for await (s, said) in g {
1294 if control.isStopped { continue }
1295 let a = heard(said)
1296 say(.progress("\(s.seat.name) \(a.ok ? "answered in \(Int(a.seconds)) s" : a.timedOut ? "ran out of time" : "did not answer: \(a.why)")."))
1297 got.append((s, a, FusionRecord.parse(a.text)))
1298 }
1299 }
1300 if control.isStopped { return stopped() }
1301 asked.formUnion(minds.map(\.id)) // each of them was given the request: none is given it again as a single mind
1302 got.sort { $0.0.id < $1.0.id }
1303 if let b = got.first(where: { $0.1.why == stillThereWhy }) { _ = blocked(b.1); return close() }
1304 for x in got where !x.1.ok { down.insert(x.0.id); _ = failed(x.0, x.1) }
1305 // A command that was given the request and failed: nobody is started after it, not a mind that fuses either.
1306 for x in got where !x.1.ok { if endsHere(x.0, end.failed[x.0.seat.name] ?? x.1.why, doing: "did not finish") { return close() } }
1307 if !got.contains(where: { $0.1.ok }) { // nobody answered (model servers: a command that fails ends the run above): the chooser is asked again without them
1308 say(.progress("None of the minds answered. Choosing again."))
1309 continue attempt
1310 }
1311 // One answer among failures is one mind's answer (the core says so below): that mind is not asked again.
1312 func reply(_ x: (Seat, Answer, FusionRecord), delta: Bool) -> FuseCore.Reply {
1313 let status = x.1.ok ? (delta && !x.2.present ? 4 : 1) : (x.1.timedOut ? 3 : 2)
1314 return FuseCore.Reply(id: x.0.id, status: status, confidence: Int(min(x.2.fields["confidence"] ?? 0, 1_000_000)),
1315 deltas: delta ? Int(min(x.2.fields["deltas"] ?? 0, 1000)) : 0, agree: delta && x.2.fields["agree"] == 1)
1316 }
1317 let first = FuseCore.judge(got.map { reply($0, delta: false) }, round: 0, most: max(p.rounds, 1))
1318 let usable = got.filter { first.usable.contains($0.0.id) }
1319 guard first.verdict != 1, first.verdict != 11, !usable.isEmpty else {
1320 return noAnswer("None of the minds answered, so there is nothing to fuse.")
1321 }
1322 // The seat that fuses and the one that carries out come from the plan. A seat that has failed while it was
1323 // asked is not asked again: the chooser is asked again with it marked down (Omega/FUSE.md).
1324 func again(_ id: Int?, _ role: (FuseCore.Plan) -> Int?, acting: Bool = false) -> Seat? {
1325 if let id, !down.contains(id) { return seat(id) }
1326 // The proposals are there. Any mind that gave one and has not failed since can take the role (for carrying
1327 // out: one that may act); no new fusion has to be formed for that, so one such mind is enough.
1328 if let s = usable.map(\.0).first(where: { !down.contains($0.id) && (acting ? $0.acts : true) }) { return s }
1329 // Within a fusion the minds that proposed may fuse and carry out: only the ones that failed are left out,
1330 // and the ones that are no stronger than an answer that was not sure (the own model that went first).
1331 let q = plan(t, seats, down: down.union(notStronger()), cfg: cfg, above: ask.above)
1332 return q.verdict == 6 ? role(q).flatMap(seat) : nil
1333 }
1334 /// The seat for a role: the plan's, or the chooser's next when that one is down. It is asked for under the
1335 /// yes like any other, and a command shows first that it is ready. `stop`: the run ends here.
1336 func taken(_ start: Int?, _ role: (FuseCore.Plan) -> Int?, acting: Bool = false) async -> (seat: Seat?, stop: Bool) {
1337 var id = start
1338 while true {
1339 guard let s = again(id, role, acting: acting) else { return (nil, false) }
1340 guard await allowed(s) else { return (nil, true) }
1341 guard let isReady = await ready(s) else { return (nil, true) }
1342 if isReady { return (s, false) }
1343 id = s.id // it is marked down now: the chooser names another, until none is left
1344 }
1345 }
1346 var draft: String
1347 var fusedBy = ""
1348 // For work that changes things: did the minds agree on the plan (or were the changes they asked for put in)?
1349 // A plan that was not looked at again, or whose corrections could not be put in, is never carried out.
1350 var agreed = false
1351 let one = first.verdict == 10
1352 if one {
1353 say(.progress("Only \(usable[0].0.seat.name) answered, so this is one mind's answer, not a fusion."))
1354 draft = usable[0].2.body
1355 } else {
1356 var fuser: Seat, f: Answer
1357 var from = p.synthesizer
1358 while true {
1359 let pick = await taken(from, { $0.synthesizer })
1360 if pick.stop { return halt() }
1361 guard let s = pick.seat else { return noAnswer("No mind that is ready can fuse the answers.") }
1362 fuser = s
1363 f = heard(await Fusion.ask(fuser, prompt: fusePrompt(question, proposals: usable.map { $0.2.body }, kind: t.kind), system: system(for: fuser, ask),
1364 history: ask.history, timeout: 900, cwd: cwd, control: control, meter: meter))
1365 if control.isStopped { return stopped() }
1366 if f.ok { break }
1367 if blocked(f) { return close() }
1368 let because = failed(fuser, f)
1369 if endsHere(fuser, because, doing: "could not fuse the answers") { return close() }
1370 down.insert(fuser.id)
1371 say(.progress("\(fuser.seat.name) could not fuse the answers: \(because). Choosing again."))
1372 from = fuser.id
1373 }
1374 draft = FusionRecord.parse(f.text).body
1375 fusedBy = fuser.seat.name
1376 say(.progress("Fused by \(fuser.seat.name) in \(Int(f.seconds)) s."))
1377 let voters = usable.filter { !down.contains($0.0.id) } // a seat that failed fusing is not asked for changes
1378 var round = 1
1379 while round <= p.rounds, !control.isStopped {
1380 var back: [(Seat, Answer, FusionRecord)] = []
1381 let askDraft = draft
1382 await withTaskGroup(of: (Seat, Answer).self) { g in
1383 for x in voters where x.0.id != fuser.id || voters.count < 3 {
1384 g.addTask { (x.0, await Fusion.ask(x.0, prompt: deltaPrompt(question, draft: askDraft), system: system(for: x.0, ask), history: ask.history,
1385 timeout: 600, cwd: cwd, control: control, meter: meter)) }
1386 }
1387 for await (s, a) in g { back.append((s, a, FusionRecord.parse(a.text))) }
1388 }
1389 if control.isStopped { return stopped() }
1390 back.sort { $0.0.id < $1.0.id }
1391 // A command that looked at the draft and failed: nobody is started after it either.
1392 for x in back where !x.1.ok && x.0.needsYes {
1393 if endsHere(x.0, failed(x.0, x.1), doing: "did not finish looking at the draft") { return close() }
1394 }
1395 let j = FuseCore.judge(back.map { reply($0, delta: true) }, round: round, most: p.rounds)
1396 if j.verdict == 7 { agreed = true; say(.progress("Round \(round): the minds agree with the draft.")); break }
1397 let asked = back.filter { $0.1.ok && $0.2.present && ($0.2.fields["agree"] != 1 || ($0.2.fields["deltas"] ?? 0) > 0) && !$0.2.body.isEmpty }.map { $0.2.body }
1398 if j.verdict == 10 || j.verdict == 11 || j.verdict == 1 || asked.isEmpty {
1399 agreed = false
1400 say(.progress("Round \(round): too few minds came back, so the draft stands as it is, not looked at again.")); break
1401 }
1402 say(.progress("Round \(round): \(j.dissenters) of \(j.usable.count) ask for changes (\(j.deltas) in all)."))
1403 let m = heard(await Fusion.ask(fuser, prompt: mergePrompt(question, draft: draft, deltas: asked, last: j.verdict == 9), system: system(for: fuser, ask),
1404 history: ask.history, timeout: 900, cwd: cwd, control: control, meter: meter))
1405 if control.isStopped { return stopped() }
1406 if m.ok { draft = FusionRecord.parse(m.text).body; agreed = true }
1407 else {
1408 if blocked(m) { return close() }
1409 // A command that was given the changes to put in and failed may have changed things: the run ends, as after any command that fails.
1410 if endsHere(fuser, failed(fuser, m), doing: "could not put the changes in") { return close() }
1411 // A model server: no mind is asked after this, and the draft is shown as it is.
1412 agreed = false; say(.progress("\(fuser.seat.name) could not put the changes in, so the draft stands without them.")); break
1413 }
1414 if j.verdict == 9 { break }
1415 round += 1
1416 }
1417 if control.isStopped { return stopped() }
1418 }
1419 let voices = names(usable.map { $0.0.id })
1420 var meta = "", by = one ? usable[0].0.seat.name : "\(usable.count) minds"
1421 if t.kind == 3, !one, !agreed {
1422 // A plan the minds did not agree on is given to no tool to carry out. The plan is shown, and said to be only that.
1423 // (Hop says what it did: it cannot say that the tools that planned changed nothing.)
1424 say(.problem("The minds did not settle on this plan, so Hop gave it to no tool to carry out. The plan is below, for you to read; say what to change, or ask again."))
1425 say(.answer(draft))
1426 meta = "\(Int(Date().timeIntervalSince(t0))) s · a plan from \(voices)" + (fusedBy.isEmpty ? "" : ", put together by \(fusedBy)") + " · given to no tool to carry out"
1427 } else if t.kind == 3 {
1428 let pick = await taken(p.executor, { $0.executor }, acting: true)
1429 if pick.stop { return halt() }
1430 guard let doer = pick.seat else { say(.problem("No mind that can act is ready.")); return close() }
1431 say(.progress("\(doer.seat.name) carries out \(one ? "that plan" : "the agreed plan")."))
1432 let e = heard(await Fusion.ask(doer, prompt: "Carry out this plan. It was \(one ? "made" : "agreed by several minds") for the request below; if a step is wrong when you look at the real files, say so and do what is right.\n\nRequest: " + question + "\n\n=== Plan ===\n" + draft,
1433 system: system(for: doer, ask), history: ask.history, timeout: nil, cwd: cwd, control: control, meter: meter, live: say))
1434 if control.isStopped { return stopped() }
1435 // A mind that carries out a plan and says nothing, or nothing but a record, has not shown that it did.
1436 if !e.ok { say(.problem("\(doer.seat.name) did not finish: \(failed(doer, e)). Look at what it did before asking again.")); return close() }
1437 draft = FusionRecord.parse(e.text).body
1438 if e.shown != draft { say(.restart); say(.answer(draft)) } // what is on screen is the reply that is kept
1439 by = doer.seat.name
1440 meta = "\(Int(Date().timeIntervalSince(t0))) s · planned by \(voices)" + (fusedBy.isEmpty ? "" : ", put together by \(fusedBy)") + " · carried out by \(doer.seat.name)" + (e.model.map { " (\($0))" } ?? "")
1441 if let sid = e.session { end.session = (doer.seat.name, sid) }
1442 } else {
1443 say(.answer(draft))
1444 // One mind's answer gets that mind's own line: where it ran, its tokens, the model it named.
1445 meta = one ? Fusion.meta(usable[0].0, usable[0].1) : "\(Int(Date().timeIntervalSince(t0))) s · fused from \(voices)" + (fusedBy.isEmpty ? "" : " by \(fusedBy)")
1446 }
1447 let standing = Standing(triage: t, tier: one ? min(max(usable[0].0.seat.tier, 1), 4) : 4, by: one ? usable[0].0.seat.name : voices, fused: !one, reply: draft)
1448 end.outcome = PickOutcome(ok: true, by: by, meta: meta, acted: ranTool, strongerLeft: strongerLeft(standing))
1449 end.standing = standing; end.reply = draft
1450 return close()
1451 case 2:
1452 let resting = seats.filter { !$0.why.isEmpty }.map { "\($0.seat.name) (\($0.why))" }
1453 let also = resting.isEmpty ? "" : " Not asked: " + resting.joined(separator: ", ") + "."
1454 say(.problem(p.reason == 82 ? "No stronger mind than \(ask.above?.by ?? "that one") is ready."
1455 : p.reason == 81 ? "No mind that is ready can do this: it needs one that can change things on this Mac." + also
1456 : "No mind is ready: every agent and model server Hop knows of is missing or not answering." + also))
1457 return close()
1458 default:
1459 say(.problem("Hop's chooser refused its own input (reason \(p.reason) at word \(p.fault)). Nothing was run.")); return close()
1460 }
1461 }
1462 }
1463}