hop
Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.
Brought by drakestapleton
| 1 | import Foundation |
| 2 | |
| 3 | /// One thing Hop says while it works on a request. |
| 4 | enum PickLine: Equatable { |
| 5 | case progress(String) // one small line: who was chosen and why, or a step a tool takes |
| 6 | case answer(String) // a piece of the reply; append it to the reply being written (pieces carry their own line breaks) |
| 7 | case restart // a stronger mind took over: drop the reply written so far in this run |
| 8 | case problem(String) // a note in plain words; nothing more comes from that mind |
| 9 | } |
| 10 | |
| 11 | /// How one request ended. |
| 12 | struct PickOutcome: Equatable { |
| 13 | var ok: Bool // a reply was given |
| 14 | var by: String // the mind that gave it ("" when none did) |
| 15 | var meta: String // the line for under the reply: where it ran, tokens when known, time, who answered |
| 16 | var acted: Bool // a command ran on this Mac for it (an agent tool, not only model servers) |
| 17 | var strongerLeft: Bool // a stronger mind than this one is ready: the Stronger button has something to do |
| 18 | var declined = false // the person said no to running an agent tool on this Mac: nothing ran, give the request back |
| 19 | } |
| 20 | |
| 21 | /// What `Pick` needs from the app around it. The Agent screen's model is one; the checks use a stand-in. |
| 22 | @MainActor |
| 23 | protocol PickHost: AnyObject { |
| 24 | var config: HopConfig { get set } |
| 25 | var learnFromAgent: Bool { get } |
| 26 | /// Asked once, before the first agent tool runs: may tools like this one work on this Mac? |
| 27 | var confirmAgentRun: (String) -> Bool { get } |
| 28 | /// Writes the settings back (the yes to agent tools is kept there). |
| 29 | func saveConfig() |
| 30 | /// What the person's knowledge base has on a message ("" = nothing, or no knowledge base). |
| 31 | func known(for text: String) async -> String |
| 32 | /// Keeps what a tool was asked and what came of it. |
| 33 | func learn(title: String, content: String) |
| 34 | } |
| 35 | |
| 36 | extension AppModel: PickHost { |
| 37 | func saveConfig() { config.save() } |
| 38 | func known(for text: String) async -> String { |
| 39 | guard config.cortex.enabled else { return "" } // switched off in the settings in use now: nobody is asked |
| 40 | return await cortex.context(for: text) // it gets under a second |
| 41 | } |
| 42 | func learn(title: String, content: String) { cortex.learn(title: title, content: content, source: "hop/agent") } |
| 43 | } |
| 44 | |
| 45 | /// Where answers are kept for an instant repeat and tokens are counted. The app uses `Savings`; the checks their own. |
| 46 | @MainActor |
| 47 | struct PickMemory { |
| 48 | var lookup: (String) -> String? |
| 49 | var store: (String, String) -> Void |
| 50 | var hit: (Int) -> Void |
| 51 | var spent: (Int, ModelEndpoint.Place) -> Void |
| 52 | static var savings: PickMemory { |
| 53 | PickMemory(lookup: { Savings.shared.lookup($0) }, store: { Savings.shared.store($0, $1) }, |
| 54 | hit: { Savings.shared.hit(saved: $0) }, spent: { Savings.shared.spent($0, at: $1) }) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | /// Hop picks who does the work. The person never chooses a model or an agent: every request is sorted, handed to |
| 59 | /// the person's own model first when it is there and the request is something to answer, else to the cheapest |
| 60 | /// mind that should do it right, and handed on to a stronger one when the reply is not sure or the mind fails. |
| 61 | /// `stronger: true` is the Stronger button: the same request again, one step up from whoever answered last. The |
| 62 | /// choosing itself is `Fusion.run` (Omega/FUSE.md); this class keeps what lasts from one message to the next. |
| 63 | @MainActor |
| 64 | final class Pick { |
| 65 | private unowned let host: PickHost |
| 66 | private let memory: PickMemory |
| 67 | /// The run that is at work (nil: none). A run that was stopped may still be winding down while the next one works. |
| 68 | private var control: Fusion.Control? |
| 69 | var running: Bool { control != nil } |
| 70 | /// The time, for what expires here. The checks move it. |
| 71 | var now: () -> Date = { Date() } |
| 72 | /// Who answered the last request and how it was sorted: where the Stronger button starts from. |
| 73 | private var last: Fusion.Standing? |
| 74 | private var lastAssessmentOnly = false |
| 75 | /// Minds that failed a short while ago (signed out, no credit, not answering) and why. They are left out |
| 76 | /// until `restFor` has passed, so a request does not wait on them again each time. |
| 77 | private var resting: [String: (why: String, until: Date)] = [:] |
| 78 | static let restFor: TimeInterval = 600 |
| 79 | /// The tool session of the mind that answered the last request, when its tool keeps one. A follow-up that |
| 80 | /// goes to the same mind within `sessionFor` carries on there. |
| 81 | private var session: (seat: String, id: String, at: Date)? |
| 82 | static let sessionFor: TimeInterval = 900 |
| 83 | /// Who gave each answer that is kept in memory, so that Stronger still works on an answer shown from there. |
| 84 | private var remembered: [String: (standing: Fusion.Standing, strongerLeft: Bool)] = [:] |
| 85 | /// The tools that were working when a run was stopped, and the ones Hop ended itself and could not end. The |
| 86 | /// next run starts no command while one of them, or anything it started, is still running: two tools are never |
| 87 | /// at work on the same files because of a Stop or a time that was up. |
| 88 | private var stoppedTools: [CommandRun] = [] |
| 89 | /// The commands that showed a short while ago that they are ready (signed in, with credit): they are given a |
| 90 | /// request without the test question first. Known for as long as a failure is (`restFor`): an account's state |
| 91 | /// is taken as it was found, good or bad, for ten minutes. |
| 92 | private var proven: [String: Date] = [:] |
| 93 | |
| 94 | convenience init(model: AppModel) { self.init(host: model, memory: .savings) } |
| 95 | init(host: PickHost, memory: PickMemory) { self.host = host; self.memory = memory } |
| 96 | |
| 97 | /// The minds that are resting now, and why (for the checks and for anyone who wants to show it). |
| 98 | var restingNow: [String: String] { resting.filter { $0.value.until > now() }.mapValues(\.why) } |
| 99 | |
| 100 | func start(_ text: String, history: [ChatMessage], stronger: Bool, assessmentOnly: Bool = false, |
| 101 | say: @escaping @MainActor (PickLine) -> Void, |
| 102 | done: @escaping @MainActor (PickOutcome) -> Void) { |
| 103 | let nothing = PickOutcome(ok: false, by: "", meta: "", acted: false, strongerLeft: false) |
| 104 | if let working = control, !working.isStopped { // one message at a time; the caller is always told how it ended |
| 105 | say(.problem("Hop is still working on the message before this one. Stop it first, or wait for it.")) |
| 106 | done(nothing) |
| 107 | return |
| 108 | } |
| 109 | // A run that was stopped and is still winding down does not hold this one up: its end changes nothing here. |
| 110 | if stronger, last == nil { // nothing was answered yet in this conversation: there is no step up to take |
| 111 | say(.problem("There is no answer yet to go stronger from.")) |
| 112 | done(nothing) |
| 113 | return |
| 114 | } |
| 115 | let assessmentOnly = assessmentOnly || (stronger && lastAssessmentOnly) |
| 116 | let cfg = host.config, learn = host.learnFromAgent, memory = self.memory |
| 117 | let at = now() |
| 118 | resting = resting.filter { $0.value.until > at } |
| 119 | proven = proven.filter { $0.value > at } |
| 120 | if !stoppedTools.isEmpty { stoppedTools = stoppedTools.filter { !$0.isGone } } |
| 121 | var ask = Fusion.Ask(text: text, history: history.filter { $0.role == "user" || $0.role == "assistant" }, |
| 122 | brief: Remote.agentBriefing(cfg), notesForClaudeChat: cfg.cortex.contextForClaudeAsk, owner: cfg.owner, |
| 123 | above: stronger ? last : nil, resting: resting.mapValues(\.why), |
| 124 | proven: Set(proven.keys), previousKind: last?.triage.kind) |
| 125 | ask.assessmentOnly = assessmentOnly |
| 126 | if let s = session, at.timeIntervalSince(s.at) < Self.sessionFor { ask.resume = [s.seat: s.id] } |
| 127 | // The same message after the same conversation, answered before by minds that only answer: from memory. |
| 128 | // No tokens, no wait. What a tool did is never replayed from memory, and Stronger always asks afresh. |
| 129 | let cacheKey = Savings.key(model: assessmentOnly ? "hop assessment" : "hop picks", history: ask.history + [ChatMessage(role: "user", text: text)]) |
| 130 | if !stronger, let cached = memory.lookup(cacheKey) { |
| 131 | let tokens = Savings.estimate(cached) + Savings.estimate(text) |
| 132 | memory.hit(tokens) |
| 133 | last = remembered[cacheKey]?.standing; lastAssessmentOnly = assessmentOnly; session = nil |
| 134 | say(.answer(cached)) |
| 135 | done(PickOutcome(ok: true, by: "memory", meta: "⚡ instant · from memory, no model asked · \(Savings.short(tokens)) tokens saved", |
| 136 | acted: false, strongerLeft: remembered[cacheKey]?.strongerLeft ?? false)) |
| 137 | return |
| 138 | } |
| 139 | let control = Fusion.Control(earlier: stoppedTools) |
| 140 | self.control = control |
| 141 | // What a run says is handed over in the order it was said; the outcome comes after the last line. |
| 142 | let (lines, feed) = AsyncStream<PickLine>.makeStream() |
| 143 | let shown = Task { @MainActor in for await line in lines { say(line) } } |
| 144 | Task { @MainActor [weak self] in |
| 145 | let installed = await AppModel.detectEngines(cfg) |
| 146 | ask.notes = await self?.host.known(for: text) ?? "" |
| 147 | let end = await Fusion.run(ask, cfg: cfg, installed: installed, control: control, |
| 148 | mayAct: { [weak self] name in await self?.mayAct(name) ?? false }, |
| 149 | say: { feed.yield($0) }) |
| 150 | feed.finish() |
| 151 | await shown.value |
| 152 | guard let self else { done(end.outcome); return } |
| 153 | if self.control === control { self.control = nil } |
| 154 | for (place, tokens) in end.usage { memory.spent(tokens, place) } // what was used was used, stopped or not |
| 155 | self.remember(control.leftRunning) // a tool that could not be ended is not forgotten |
| 156 | // What was found out about a tool's account holds whether the run was stopped or not. |
| 157 | for name in end.proved { self.proven[name] = self.now().addingTimeInterval(Self.restFor) } |
| 158 | for name in end.failed.keys { self.proven[name] = nil } |
| 159 | if !control.isStopped { // a stopped run leaves nothing behind for the next message |
| 160 | // A mind that was busy or was stopped is asked again next time; one that failed is left out for a while. |
| 161 | for (name, why) in end.failed where why != Fusion.stoppedWhy && why != Fusion.busyWhy { |
| 162 | self.resting[name] = (why, self.now().addingTimeInterval(Self.restFor)) |
| 163 | } |
| 164 | if end.outcome.ok { |
| 165 | self.last = end.standing |
| 166 | self.lastAssessmentOnly = assessmentOnly |
| 167 | self.session = end.session.map { ($0.seat, $0.id, self.now()) } |
| 168 | if !end.outcome.acted, let standing = end.standing, !end.reply.isEmpty { |
| 169 | memory.store(cacheKey, end.reply) |
| 170 | self.remembered[cacheKey] = (standing, end.outcome.strongerLeft) |
| 171 | self.remembered = self.remembered.filter { memory.lookup($0.key) != nil } |
| 172 | } |
| 173 | if end.outcome.acted, learn, !end.reply.isEmpty { |
| 174 | // Remember what was asked and what came of it. Queued on disk, sent in the background. |
| 175 | self.host.learn(title: "Hop agent (\(end.outcome.by)): \(text.prefix(90))", content: "Request: \(text)\n\nResult: \(end.reply)") |
| 176 | } |
| 177 | } |
| 178 | } |
| 179 | done(end.outcome) |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | /// The person's yes to agent tools that can read and change files on this Mac: asked once, then kept. |
| 184 | private func mayAct(_ name: String) -> Bool { |
| 185 | if host.config.agentToolsAllowed { return true } |
| 186 | guard host.confirmAgentRun(name) else { return false } |
| 187 | host.config.agentConfirmed = true |
| 188 | host.config.agentConsentVersion = HopConfig.currentAgentConsentVersion |
| 189 | host.saveConfig() |
| 190 | return true |
| 191 | } |
| 192 | |
| 193 | /// Stops the run: every tool it started is asked to end, and nothing more is started. `done` still arrives |
| 194 | /// (ok false), after a "Stopped." line; the next `start` does not have to wait for that. When a tool was working, |
| 195 | /// the next run starts no command until that tool and what it started are gone. |
| 196 | func stop() { |
| 197 | guard let control, !control.isStopped else { return } |
| 198 | control.stop() |
| 199 | remember(control.leftRunning) |
| 200 | } |
| 201 | |
| 202 | /// Tools of a run that may still be running after it: the next run starts no command while they are. |
| 203 | private func remember(_ tools: [CommandRun]) { |
| 204 | for t in tools where !stoppedTools.contains(where: { $0 === t }) { stoppedTools.append(t) } |
| 205 | } |
| 206 | |
| 207 | /// A new conversation: nothing of the last one is carried on. Which minds are resting is kept. |
| 208 | func forget() { last = nil; lastAssessmentOnly = false; session = nil } |
| 209 | |
| 210 | /// The commands known to be ready now (for the checks). |
| 211 | var provenNow: Set<String> { Set(proven.filter { $0.value > now() }.keys) } |
| 212 | } |