hop
Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.
Brought by drakestapleton
hop / Sources / PickChecks.swift
| 1 | import Foundation |
| 2 | |
| 3 | /// Self-test rows for how Hop picks who answers (`Fusion`, `Pick`) and for the "answered by" line. The model |
| 4 | /// servers here are stubs on this Mac's loopback address and the agent tools are one-line shell stand-ins, all |
| 5 | /// started inside the test; nothing else is contacted, no real tool or account is used, and no setting is read or |
| 6 | /// written. `tools/check-pick.sh` builds changed copies of the code and requires these rows to fail on them. |
| 7 | @MainActor |
| 8 | enum PickChecks { |
| 9 | static let own = "Own test model" |
| 10 | |
| 11 | /// A stub model server. `chat` is the status its chat endpoint answers with (503 = busy), `says` what it |
| 12 | /// replies, `reports` the model id its chat stream names (nil: none). |
| 13 | static func stub(chat: Int = 200, says: String = "ready", reports: String?, gate: Gate? = nil) -> SelfTestServer? { |
| 14 | var chunk: [String: Any] = ["object": "chat.completion.chunk", "choices": [["index": 0, "delta": ["content": says]]]] |
| 15 | var last: [String: Any] = ["object": "chat.completion.chunk", "choices": [], "usage": ["total_tokens": 7]] |
| 16 | if let reports { chunk["model"] = reports; last["model"] = reports } |
| 17 | func line(_ o: [String: Any]) -> String { "data: " + String(decoding: (try? JSONSerialization.data(withJSONObject: o)) ?? Data(), as: UTF8.self) + "\n\n" } |
| 18 | let sse = line(chunk) + line(last) + "data: [DONE]\n\n" |
| 19 | return SelfTestServer(respondToBody: { first, body in |
| 20 | // With a gate the server refuses every chat request that asks for usage (`stream_options`), as some |
| 21 | // servers do, and holds the first such request until a second one has come too. |
| 22 | guard let gate, first.hasPrefix("POST /v1/chat/completions "), body.contains("stream_options") else { return nil } |
| 23 | gate.arrive() |
| 24 | return (400, "application/json", "{\"error\":\"unknown field stream_options\"}") |
| 25 | }, respond: { first in |
| 26 | if first.hasPrefix("GET /health ") { return (200, "application/json", "{\"status\":\"ok\"}") } |
| 27 | if first.hasPrefix("GET /v1/models ") { return (200, "application/json", "{\"data\":[]}") } |
| 28 | if first.hasPrefix("POST /v1/chat/completions ") { |
| 29 | return chat == 200 ? (200, "text/event-stream", sse) : (chat, "application/json", "{\"error\":{\"type\":\"server_busy\"}}") |
| 30 | } |
| 31 | return (404, "text/plain", "not here") |
| 32 | }) |
| 33 | } |
| 34 | |
| 35 | /// A stub model server that answers each chat request with what `reply` makes of the request's body (nil: it |
| 36 | /// is busy, 503). Reached through the address `online` gives it (this Mac's own address written the long way, as |
| 37 | /// an IPv6 address that stands for 127.0.0.1), it counts as a server online by Hop's rule for addresses, not as |
| 38 | /// the person's own model. Nothing leaves this Mac. |
| 39 | static func scripted(_ reply: @escaping @Sendable (String) -> String?) -> SelfTestServer? { |
| 40 | SelfTestServer(respondToBody: { first, body in |
| 41 | guard first.hasPrefix("POST /v1/chat/completions ") else { return nil } |
| 42 | guard let says = reply(body) else { return (503, "application/json", "{\"error\":{\"type\":\"server_busy\"}}") } |
| 43 | func line(_ o: [String: Any]) -> String { "data: " + String(decoding: (try? JSONSerialization.data(withJSONObject: o)) ?? Data(), as: UTF8.self) + "\n\n" } |
| 44 | let chunk: [String: Any] = ["object": "chat.completion.chunk", "choices": [["index": 0, "delta": ["content": says]]]] |
| 45 | let last: [String: Any] = ["object": "chat.completion.chunk", "choices": [], "usage": ["total_tokens": 7]] |
| 46 | return (200, "text/event-stream", line(chunk) + line(last) + "data: [DONE]\n\n") |
| 47 | }, respond: { first in |
| 48 | first.hasPrefix("GET /v1/models ") ? (200, "application/json", "{\"data\":[]}") : (404, "text/plain", "not here") |
| 49 | }) |
| 50 | } |
| 51 | static func online(_ name: String, _ port: Int) -> ModelEndpoint { ModelEndpoint(name: name, baseURL: "http://[::ffff:127.0.0.1]:\(port)/v1", model: "configured-id") } |
| 52 | |
| 53 | /// Holds the first request that arrives until a second one has arrived too (three seconds at most), so that two |
| 54 | /// requests sent at once are answered at the same moment. |
| 55 | final class Gate: @unchecked Sendable { |
| 56 | private let c = NSCondition() |
| 57 | private var n = 0 |
| 58 | func arrive() { |
| 59 | c.lock(); defer { c.unlock() } |
| 60 | n += 1 |
| 61 | if n >= 2 { c.broadcast() } else { _ = c.wait(until: Date().addingTimeInterval(3)) } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | static func ownModel(_ port: Int, host: String = "127.0.0.1") -> ModelEndpoint { |
| 66 | ModelEndpoint(name: own, baseURL: "http://\(host):\(port)/v1", model: "configured-id") |
| 67 | } |
| 68 | |
| 69 | /// What a stand-in tool does with the question Hop asks a command before it gives it a request: it says "ready" |
| 70 | /// and nothing else of its script runs, as a real tool that is signed in would. |
| 71 | static let answersTest = "case \"$1\" in *'exactly one word: ready'*) echo ready; exit 0;; esac; " |
| 72 | /// A stand-in agent tool: a shell line that gets the whole prompt as $1 (and anything Hop adds after it). |
| 73 | /// `signedIn` false: it has no answer of its own to the test question; its script gets that too. |
| 74 | /// `known`: the stand-in is started through a file with the name of a tool Hop knows (`knownShell`), so Hop |
| 75 | /// asks it the test question before a request, as it asks a real tool. Without it the stand-in is a command of |
| 76 | /// the person's own, which is never asked that question. |
| 77 | static func tool(_ name: String, _ script: String, tier: Int, family: String, cost: Int, signedIn: Bool = true, known: Bool = false) -> AgentEngine { |
| 78 | var e = AgentEngine(name: name, command: [known ? knownShell : "/bin/sh", "-c", (signedIn ? answersTest : "") + script, "sh", "{prompt}"]) |
| 79 | e.tier = tier; e.family = family; e.cost = cost |
| 80 | return e |
| 81 | } |
| 82 | /// The same as a seat written in the settings (`fusionSeats`), which may be one that only answers. |
| 83 | static func seat(_ name: String, _ script: String, tier: Int, family: String, cost: Int, act: Bool, signedIn: Bool = true, known: Bool = false) -> FusionSeat { |
| 84 | FusionSeat(name: name, command: [known ? knownShell : "/bin/sh", "-c", (signedIn ? answersTest : "") + script, "sh", "{prompt}"], tier: tier, family: family, cost: cost, act: act) |
| 85 | } |
| 86 | /// A shell under the file name of an agent tool Hop knows ("codex"), made in the checks' own folder when they start. |
| 87 | static var knownShell = "/bin/sh" |
| 88 | static func record(_ confidence: Int) -> String { "note hop record\\nfn confidence to ulong\\nret \(confidence)\\nend\\n" } |
| 89 | |
| 90 | /// What one run said, in order. |
| 91 | final class Lines: @unchecked Sendable { |
| 92 | private let l = NSLock() |
| 93 | private var all: [PickLine] = [] |
| 94 | func add(_ x: PickLine) { l.lock(); all.append(x); l.unlock() } |
| 95 | var list: [PickLine] { l.lock(); defer { l.unlock() }; return all } |
| 96 | /// The reply as a screen would show it: the answer pieces after the last restart. |
| 97 | var reply: String { |
| 98 | var s = "" |
| 99 | for x in list { if case .answer(let p) = x { s += p } else if x == .restart { s = "" } } |
| 100 | return s |
| 101 | } |
| 102 | var notes: String { list.compactMap { if case .progress(let s) = $0 { return s } else if case .problem(let s) = $0 { return "! " + s } else { return nil } }.joined(separator: " | ") } |
| 103 | var problems: [String] { list.compactMap { if case .problem(let s) = $0 { return s } else { return nil } } } |
| 104 | } |
| 105 | |
| 106 | /// A stand-in for the app around `Pick`: settings in memory, a yes that is counted, nothing saved anywhere. |
| 107 | final class Host: PickHost { |
| 108 | var config: HopConfig |
| 109 | var learnFromAgent = true |
| 110 | var yes = true, asked: [String] = [], saved = 0, learned: [String] = [] |
| 111 | var confirmAgentRun: (String) -> Bool { { [unowned self] name in self.asked.append(name); return self.yes } } |
| 112 | init(_ config: HopConfig) { self.config = config } |
| 113 | func saveConfig() { saved += 1 } |
| 114 | func known(for text: String) async -> String { "" } |
| 115 | func learn(title: String, content: String) { learned.append(title) } |
| 116 | } |
| 117 | /// Answers kept and tokens counted in memory only, so the checks leave the person's own counts alone. |
| 118 | final class Kept { |
| 119 | var answers: [String: String] = [:], hits = 0, spent: [ModelEndpoint.Place: Int] = [:] |
| 120 | var memory: PickMemory { |
| 121 | PickMemory(lookup: { [unowned self] in self.answers[$0] }, store: { [unowned self] in self.answers[$0] = $1 }, |
| 122 | hit: { [unowned self] _ in self.hits += 1 }, spent: { [unowned self] n, place in self.spent[place, default: 0] += n }) |
| 123 | } |
| 124 | } |
| 125 | /// One message through `Pick`, as the Agent screen sends it: what it said, and how it ended. |
| 126 | static func send(_ pick: Pick, _ text: String, history: [ChatMessage] = [], stronger: Bool = false) async -> (outcome: PickOutcome, lines: Lines) { |
| 127 | let lines = Lines() |
| 128 | let outcome: PickOutcome = await withCheckedContinuation { c in |
| 129 | pick.start(text, history: history, stronger: stronger, say: { lines.add($0) }, done: { c.resume(returning: $0) }) |
| 130 | } |
| 131 | return (outcome, lines) |
| 132 | } |
| 133 | static func alive(_ pid: Int32) -> Bool { pid > 0 && kill(pid, 0) == 0 } |
| 134 | |
| 135 | static func go(_ ask: Fusion.Ask, _ cfg: HopConfig, _ tools: [AgentEngine] = [], control: Fusion.Control = Fusion.Control(), |
| 136 | mayAct: @escaping @Sendable (String) async -> Bool = { _ in true }) async -> (end: Fusion.End, lines: Lines) { |
| 137 | let lines = Lines() |
| 138 | let end = await Fusion.run(ask, cfg: cfg, installed: tools, control: control, mayAct: mayAct) { lines.add($0) } |
| 139 | return (end, lines) |
| 140 | } |
| 141 | |
| 142 | static func run(_ report: (String, Bool, String) -> Void) async { |
| 143 | let fm = FileManager.default |
| 144 | let dir = fm.temporaryDirectory.appendingPathComponent("hop-pick-checks-\(UUID().uuidString)") |
| 145 | try? fm.createDirectory(at: dir, withIntermediateDirectories: true) |
| 146 | defer { try? fm.removeItem(at: dir) } |
| 147 | func path(_ name: String) -> String { dir.appendingPathComponent(name).path } |
| 148 | func read(_ name: String) -> String { (try? String(contentsOfFile: path(name), encoding: .utf8)) ?? "" } |
| 149 | func config() -> HopConfig { var c = HopConfig(); c.models = []; c.agentEngines = []; c.agentWorkingDirectory = dir.path; return c } |
| 150 | // A shell that Hop takes for an agent tool it knows, by its file name: it runs what it is given, like /bin/sh. |
| 151 | let bin = dir.appendingPathComponent("bin") |
| 152 | try? fm.createDirectory(at: bin, withIntermediateDirectories: true) |
| 153 | knownShell = bin.appendingPathComponent("codex").path |
| 154 | try? Data("#!/bin/sh\nexec /bin/sh \"$@\"\n".utf8).write(to: URL(fileURLWithPath: knownShell)) |
| 155 | try? fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: knownShell) |
| 156 | defer { knownShell = "/bin/sh" } |
| 157 | let question = Fusion.Triage(kind: 1, difficulty: 2, stakes: 2, confidence: 1_000_000, by: "the test") |
| 158 | let change = Fusion.Triage(kind: 3, difficulty: 2, stakes: 2, confidence: 1_000_000, by: "the test") |
| 159 | func strong(_ mark: String) -> AgentEngine { tool("Strong tool", "echo ran >> \(Shell.quote(path(mark))); echo from the strong tool", tier: 4, family: "anthropic", cost: 100) } |
| 160 | |
| 161 | // 1. Nothing set up: Hop says so and asks nobody. A fresh install's settings have no own model. |
| 162 | let none = await go(Fusion.Ask(text: "hello", force: question), config()) |
| 163 | let sum = await go(Fusion.Ask(text: "what is 17 * 23?"), config()) |
| 164 | report("With no model server and no agent tool, Hop says so and asks nobody; a plain sum it still does", |
| 165 | !none.end.outcome.ok && none.lines.problems.count == 1 && none.lines.problems[0].contains("no mind") |
| 166 | // A fresh install's settings name no own model: with no agent tool found, what is left is the model list's Claude entry, chat only. |
| 167 | && Fusion.list(HopConfig(), installed: []).map(\.name) == ["Claude (your subscription)"] && Fusion.list(config(), installed: []).isEmpty |
| 168 | && sum.end.outcome.ok && sum.lines.reply == "391" && sum.end.outcome.by == "this Mac" |
| 169 | // Worked out exactly or not at all: no rounding on the way, and nothing shown that is not the whole answer. |
| 170 | && Fusion.arithmetic("100000000000000 + 0.1 - 100000000000000") == "0.1" && Fusion.arithmetic("0.1 + 0.2") == "0.3" |
| 171 | && Fusion.arithmetic("1 / 3") == nil && Fusion.arithmetic("10 / 4") == "2.5" && Fusion.arithmetic("-3 * (2 - 0.5)") == "-4.5" |
| 172 | && Fusion.arithmetic("999999999999999 * 999999999999999") == nil && Fusion.arithmetic("5 / 0") == nil && Fusion.arithmetic("1.0000000000001 * 1") == nil, |
| 173 | none.lines.notes + " | 17 * 23 = " + sum.lines.reply + " | 100000000000000 + 0.1 - 100000000000000 = " + (Fusion.arithmetic("100000000000000 + 0.1 - 100000000000000") ?? "left to a mind") + " | 1 / 3: " + (Fusion.arithmetic("1 / 3") ?? "left to a mind")) |
| 174 | |
| 175 | // 2. An own model that answers takes a question first, although a stronger tool is installed. |
| 176 | guard let well = stub(reports: "stub-reported-7b"), let wp = await well.start() else { |
| 177 | report("Your own model answers first when it is there", false, "could not start a stub server on this Mac's loopback address") |
| 178 | return |
| 179 | } |
| 180 | defer { well.stop() } |
| 181 | var cfg = config(); cfg.models = [ownModel(wp)] |
| 182 | let first = await go(Fusion.Ask(text: "hello", force: question), cfg, [strong("m2")]) |
| 183 | let hard = await go(Fusion.Ask(text: "prove it", force: Fusion.Triage(kind: 2, difficulty: 5, stakes: 3, confidence: 1_000_000, by: "the test")), cfg, [strong("m2")]) |
| 184 | report("Your own model answers first when it is there", |
| 185 | first.end.outcome.ok && first.end.outcome.by == own && first.lines.reply == "ready" && !first.end.outcome.acted |
| 186 | && hard.end.outcome.ok && hard.end.outcome.by == own && hard.lines.notes.contains("your own model takes it first") && !hard.lines.notes.contains("fusing") |
| 187 | && first.end.outcome.meta.hasPrefix("๐ on this Mac") && first.end.outcome.meta.contains("answered by stub-reported-7b") |
| 188 | && first.end.outcome.strongerLeft && read("m2").isEmpty && well.requests.contains { $0.hasPrefix("POST /v1/chat/completions ") }, |
| 189 | "\(first.end.outcome.by): โ\(first.lines.reply)โ ยท \(first.end.outcome.meta) ยท stronger left: \(first.end.outcome.strongerLeft) ยท the strong tool ran: \(!read("m2").isEmpty) ยท open-ended, high stakes: \(hard.lines.notes)") |
| 190 | |
| 191 | // 3. It is busy, or nothing listens there: the next mind answers, and a busy one is said to be busy. |
| 192 | var fell: [String] = [] |
| 193 | if let busy = stub(chat: 503, reports: nil), let bp = await busy.start() { |
| 194 | var c = config(); c.models = [ownModel(bp)] |
| 195 | let a = await go(Fusion.Ask(text: "hello", force: question), c, [strong("m3")]) |
| 196 | busy.stop() |
| 197 | try? await Task.sleep(nanoseconds: 200_000_000) |
| 198 | let b = await go(Fusion.Ask(text: "hello", force: question), c, [strong("m3")]) // the port is closed now |
| 199 | if a.end.outcome.ok, a.end.outcome.by == "Strong tool", a.end.failed[own] == Fusion.busyWhy, a.lines.notes.contains("busy") { fell.append("busy: " + a.lines.notes) } |
| 200 | if b.end.outcome.ok, b.end.outcome.by == "Strong tool", b.end.failed.isEmpty, !b.lines.notes.contains("could not") { fell.append("closed: " + b.lines.notes) } |
| 201 | } |
| 202 | report("Your own model busy or gone: the next mind answers", fell.count == 2 && read("m3").split(separator: "\n").count == 2, |
| 203 | fell.isEmpty ? "neither a busy server nor a closed port led to the next mind" : fell.joined(separator: " || ")) |
| 204 | |
| 205 | // 4. Work that changes things goes to an agent tool, never to a model server; with no tool Hop refuses. |
| 206 | let n4 = well.requests.count |
| 207 | let act = await go(Fusion.Ask(text: "rename it", force: change), cfg, [strong("m4")]) |
| 208 | let cannot = await go(Fusion.Ask(text: "rename it", force: change), cfg) |
| 209 | report("Work that changes things never goes to a model server", |
| 210 | act.end.outcome.ok && act.end.outcome.by == "Strong tool" && act.end.outcome.acted && !read("m4").isEmpty |
| 211 | && !cannot.end.outcome.ok && cannot.lines.problems.contains { $0.contains("change things") } |
| 212 | && !well.requests[n4...].contains { $0.hasPrefix("POST ") }, |
| 213 | "with a tool: \(act.end.outcome.by); without: \(cannot.lines.problems.first ?? "no refusal"); chat requests to the server meanwhile: \(well.requests[n4...].filter { $0.hasPrefix("POST ") }.count)") |
| 214 | |
| 215 | // 5. The settings: "preferOwnModel": false keeps own models out; "tier" is taken as written; a model marked |
| 216 | // "rewrite": false is left out; only an address on this Mac or the person's network counts as own. |
| 217 | var mixed = HopConfig() |
| 218 | mixed.models = [ModelEndpoint(name: "Online", baseURL: "https://api.example.com/v1", model: "m"), |
| 219 | ModelEndpoint(name: "Box", baseURL: "http://box.local:8080/v1", model: "m"), |
| 220 | ModelEndpoint(name: "Here", baseURL: "http://localhost:9/v1", model: "m"), |
| 221 | ModelEndpoint(name: "Tiny", baseURL: "http://localhost:9/v1", model: "m", rewrite: false), |
| 222 | ModelEndpoint(name: "Claude", baseURL: "", model: "sonnet", kind: "claude-cli")] |
| 223 | let seats = Fusion.list(mixed, installed: []) |
| 224 | var off = mixed; off.preferOwnModel = false |
| 225 | let tiered = try? JSONDecoder().decode(ModelEndpoint.self, from: Data("{\"name\":\"t\",\"baseURL\":\"http://127.0.0.1:1/v1\",\"model\":\"m\",\"tier\":2}".utf8)) |
| 226 | var withTier = HopConfig(); withTier.models = tiered.map { [$0] } ?? [] |
| 227 | func says(_ s: FusionSeat) -> String { "\(s.name) tier \(s.tier) \(s.family) cost \(s.cost)" } |
| 228 | report("Which model servers Hop may pick, and how strong they count", |
| 229 | seats.map(says) == ["Online tier 2 online cost 30", "Box tier 3 local cost 1", "Here tier 3 local cost 1", "Claude tier 3 anthropic cost 30"] && seats.allSatisfy { !$0.act } |
| 230 | // The model list's Claude entry (through its CLI) still answers when no Claude agent is set: chat only, tools off, its own model. |
| 231 | && seats.last?.chatOnly == true && seats.last?.command.starts(with: ["claude", "-p", "{prompt}", "--model", "sonnet", "--tools", ""]) == true |
| 232 | && !Fusion.list(mixed, installed: [AgentEngine(name: "Claude Code", command: ["claude", "-p", "{prompt}"])]).contains { $0.name == "Claude" } |
| 233 | && Fusion.list(off, installed: []).map(\.name) == ["Online", "Claude"] |
| 234 | && Fusion.list(withTier, installed: []).map(says) == ["t tier 2 local cost 1"], |
| 235 | seats.map(says).joined(separator: "; ") + " | preferOwnModel false: " + Fusion.list(off, installed: []).map(\.name).joined(separator: ", ") |
| 236 | + " | tier written: " + Fusion.list(withTier, installed: []).map(says).joined(separator: ", ")) |
| 237 | |
| 238 | // 6. Agent tools: Hop's table for the ones it knows, the settings' own words first, and never Hop itself. |
| 239 | var mine = AgentEngine(name: "Mine", command: ["mytool", "{prompt}"]); mine.tier = 2; mine.family = "xai"; mine.cost = 7 |
| 240 | let toolSeats = Fusion.list(HopConfig(), installed: [ |
| 241 | AgentEngine(name: "Claude Code", command: ["claude", "-p", "{prompt}", "--verbose"]), AgentEngine(name: "Muse", command: ["muse", "exec", "{prompt}"]), |
| 242 | AgentEngine(name: "Unknown", command: ["sometool", "{prompt}"]), mine, |
| 243 | AgentEngine(name: "Hop picks", command: [AgentEngine.selfTool, "fuse", "{prompt}"]), |
| 244 | AgentEngine(name: "Preview", command: ["env", "X=1", "/Users/x/Hop.app/Contents/MacOS/Hop", "fuse", "{prompt}"])]) |
| 245 | let sonnet = toolSeats.first { $0.name == "Claude Sonnet" }, haiku = toolSeats.first { $0.name == "Claude Haiku" } |
| 246 | let namesHaiku = Fusion.list(HopConfig(), installed: [AgentEngine(name: "Claude Code", command: ["claude", "-p", "{prompt}", "--model=haiku"])]) |
| 247 | var strongSaid = AgentEngine(name: "Claude Code", command: ["claude", "-p", "{prompt}", "--model", "haiku"]); strongSaid.tier = 4 |
| 248 | let tierSaid = Fusion.list(HopConfig(), installed: [strongSaid]) |
| 249 | report("Which agent tools Hop may pick: its table, your own words first, never Hop itself", |
| 250 | toolSeats.map(says) == ["Claude Code tier 4 anthropic cost 100", "Muse tier 3 meta cost 50", "Unknown tier 3 sometool cost 50", "Mine tier 2 xai cost 7", |
| 251 | "Claude Haiku tier 2 anthropic cost 8", "Claude Sonnet tier 3 anthropic cost 30"] |
| 252 | && sonnet?.command == ["claude", "-p", "{prompt}", "--verbose", "--model", "sonnet"] && sonnet?.act == true |
| 253 | // Claude Code itself is asked for Claude's strong model by name, so Stronger from the middle one is another model; |
| 254 | // a command that names a model has that model's tier, and no middle-model seat is made beside it. |
| 255 | && toolSeats.first?.command == ["claude", "-p", "{prompt}", "--verbose", "--model", "opus"] |
| 256 | && namesHaiku.map(says) == ["Claude Code tier 2 anthropic cost 100", "Claude Haiku tier 2 anthropic cost 8"] && namesHaiku.first?.command == ["claude", "-p", "{prompt}", "--model=haiku"] |
| 257 | && tierSaid.first.map(says) == "Claude Code tier 4 anthropic cost 100" |
| 258 | && haiku?.act == false && haiku?.command.contains("--tools") == true, |
| 259 | toolSeats.map(says).joined(separator: "; ")) |
| 260 | |
| 261 | // 7. Under an answer: the model id as the server reported it, and where it ran. |
| 262 | let ep = ownModel(wp) |
| 263 | var said = "" |
| 264 | do { |
| 265 | let r = try await ModelClient.streamReply(ep, history: [ChatMessage(role: "user", text: "hi")]) { said += $0 } |
| 266 | let meta = AppModel.answerMeta(ep, tokens: r.tokens, seconds: 1, who: AskRoute.who(ep, reported: r.model)) |
| 267 | report("Under an answer: the model the server named, and where it ran", |
| 268 | said == "ready" && r.model == "stub-reported-7b" && meta.hasPrefix("๐ on this Mac") |
| 269 | && meta.contains("answered by stub-reported-7b") && !meta.contains("configured"), |
| 270 | meta) |
| 271 | } catch { |
| 272 | report("Under an answer: the model the server named, and where it ran", false, error.localizedDescription) |
| 273 | } |
| 274 | |
| 275 | // 8. A server that names no model: the configured name, and the line says it is the configured name. |
| 276 | if let quiet = stub(reports: nil), let qp = await quiet.start() { |
| 277 | var c = config(); c.models = [ownModel(qp)] |
| 278 | let q = await go(Fusion.Ask(text: "hello", force: question), c) |
| 279 | report("No model id reported: the configured name, said to be that", |
| 280 | q.end.outcome.meta.contains("answered by \(own) (the configured name; the server reported no model id)") && !q.end.outcome.strongerLeft, q.end.outcome.meta) |
| 281 | quiet.stop() |
| 282 | } else { |
| 283 | report("No model id reported: the configured name, said to be that", false, "could not start a stub server") |
| 284 | } |
| 285 | |
| 286 | // 9. An agent tool that says who it is (Claude Code's stream-json): its session, model and tokens are read |
| 287 | // from what it prints, shown under the reply, and a follow-up carries on in that session. |
| 288 | let stream = "{\\\"type\\\":\\\"system\\\",\\\"subtype\\\":\\\"init\\\",\\\"model\\\":\\\"claude-test-model-1\\\",\\\"session_id\\\":\\\"sess-1\\\"}\\n" |
| 289 | + "{\\\"type\\\":\\\"assistant\\\",\\\"message\\\":{\\\"content\\\":[{\\\"type\\\":\\\"tool_use\\\",\\\"name\\\":\\\"Bash\\\"},{\\\"type\\\":\\\"text\\\",\\\"text\\\":\\\"Done.\\\"}]}}\\n" |
| 290 | + "{\\\"type\\\":\\\"result\\\",\\\"is_error\\\":false,\\\"result\\\":\\\"Done.\\\",\\\"session_id\\\":\\\"sess-1\\\",\\\"usage\\\":{\\\"input_tokens\\\":5,\\\"output_tokens\\\":7}}\\n" |
| 291 | let teller = tool("Teller", "printf '%s' \"$1\" > \(Shell.quote(path("p9"))); echo \"$2 $3\" > \(Shell.quote(path("a9"))); printf \"\(stream)\"", tier: 4, family: "anthropic", cost: 100) |
| 292 | let told = await go(Fusion.Ask(text: "rename it", history: [ChatMessage(role: "user", text: "My dog is Rex"), ChatMessage(role: "assistant", text: "Noted.")], |
| 293 | brief: "BRIEFING", notes: "NOTE-1", force: change), config(), [teller]) |
| 294 | let firstPrompt = read("p9"), firstArgs = read("a9").trimmingCharacters(in: .whitespacesAndNewlines) |
| 295 | let onward = await go(Fusion.Ask(text: "and again", history: [ChatMessage(role: "user", text: "My dog is Rex")], resume: ["Teller": "sess-1"], force: change), config(), [teller]) |
| 296 | let steps = told.lines.list.contains(.progress("โธ Bash")) |
| 297 | report("An agent tool's own session, model and tokens are read; a follow-up carries on in its session", |
| 298 | told.end.outcome.ok && told.lines.reply == "Done." && steps && told.end.session?.id == "sess-1" && told.end.usage == [.online: 12] |
| 299 | && told.end.outcome.meta.hasPrefix("12 tokens ยท ") && told.end.outcome.meta.hasSuffix("answered by Teller (claude-test-model-1)") |
| 300 | && firstPrompt.hasPrefix("BRIEFING") && firstPrompt.contains("NOTE-1") && firstPrompt.contains("User: My dog is Rex") && firstPrompt.contains("Assistant: Noted.") |
| 301 | && firstPrompt.hasSuffix("Request: rename it") && firstArgs.isEmpty |
| 302 | && onward.end.outcome.ok && read("a9").trimmingCharacters(in: .whitespacesAndNewlines) == "--resume sess-1" && !read("p9").contains("conversation so far"), |
| 303 | "\(told.end.outcome.meta); its step shown as progress: \(steps); follow-up arguments: \(read("a9").trimmingCharacters(in: .whitespacesAndNewlines))") |
| 304 | |
| 305 | // 10. The plan: the own model first for anything to answer or write, never for work that changes things; and |
| 306 | // Stronger: a higher tier when one is ready; from the top, several strong minds fused; after that, nothing. |
| 307 | func mind(_ id: Int, _ tier: Int, _ family: String, _ cost: Int, act: Bool = true, ready: Bool = true, own: Bool = false) -> Fusion.Seat { |
| 308 | Fusion.Seat(id: id, seat: FusionSeat(name: "S\(id)", command: own ? [] : ["x", "{prompt}"], model: own ? "S\(id)" : "", tier: tier, family: family, cost: cost, act: act), |
| 309 | endpoint: own ? ModelEndpoint(name: "S\(id)", baseURL: "http://127.0.0.1:1/v1", model: "m") : nil, ready: ready) |
| 310 | } |
| 311 | let three = [mind(1, 3, "local", 1, act: false, own: true), mind(2, 4, "anthropic", 100), mind(3, 4, "openai", 100)] |
| 312 | func sorted(_ kind: Int, _ difficulty: Int) -> Fusion.Triage { Fusion.Triage(kind: kind, difficulty: difficulty, stakes: 2, confidence: 1_000_000, by: "the test") } |
| 313 | func above(_ tier: Int, fused: Bool = false) -> Fusion.Standing { Fusion.Standing(triage: question, tier: tier, by: "x", fused: fused, reply: "") } |
| 314 | let c10 = HopConfig() |
| 315 | let usual = Fusion.plan(question, three, down: [], cfg: c10) |
| 316 | let hardPlan = Fusion.plan(sorted(1, 4), three, down: [], cfg: c10), openPlan = Fusion.plan(sorted(2, 5), three, down: [], cfg: c10) |
| 317 | let work = Fusion.plan(sorted(3, 2), three, down: [], cfg: c10) |
| 318 | let ownDown = Fusion.plan(sorted(1, 4), three, down: [1], cfg: c10) |
| 319 | let ownNotReady = Fusion.plan(question, [mind(1, 3, "local", 1, act: false, ready: false, own: true), three[1], three[2]], down: [], cfg: c10) |
| 320 | let up = Fusion.plan(question, three, down: [], cfg: c10, above: above(3)) |
| 321 | let top = Fusion.plan(question, three, down: [], cfg: c10, above: above(4)) |
| 322 | let after = Fusion.plan(question, three, down: [], cfg: c10, above: above(4, fused: true)) |
| 323 | let alone = Fusion.plan(question, [three[0]], down: [], cfg: c10, above: above(3)) |
| 324 | let lower = Fusion.plan(question, three, down: [], cfg: c10, above: above(1)) |
| 325 | report("The plan: your own model first unless the work changes things; Stronger goes a tier up, then fuses, then nothing", |
| 326 | usual.ownFirst && usual.chosen == [1] && hardPlan.ownFirst && hardPlan.chosen == [1] && openPlan.ownFirst && openPlan.chosen == [1] |
| 327 | && !work.ownFirst && work.chosen.first == 2 && !ownDown.ownFirst && ownDown.chosen.first == 2 && !ownNotReady.ownFirst && ownNotReady.chosen.first == 2 |
| 328 | && [4, 5].contains(up.verdict) && up.chosen.first == 2 && !up.chosen.contains(1) && !up.ownFirst |
| 329 | && top.verdict == 6 && top.chosen.count >= 2 && after.verdict == 2 && after.reason == 82 && alone.verdict == 2 && alone.reason == 82 |
| 330 | && lower.chosen.first == 1, |
| 331 | "a question: seat \(usual.chosen); hard: \(hardPlan.chosen); open-ended: \(openPlan.chosen); work that changes things: \(work.chosen); own model down: \(ownDown.chosen); above tier 3: \(up.chosen); above tier 4: verdict \(top.verdict) seats \(top.chosen); after a fusion: verdict \(after.verdict) reason \(after.reason); nothing higher and nothing to fuse: verdict \(alone.verdict)") |
| 332 | |
| 333 | // 11. A reply that says it is unsure is handed to a stronger mind; the record at its end is never shown. The |
| 334 | // same when it is the person's own model that is unsure. |
| 335 | var c11 = config() |
| 336 | c11.fusionSeats = [seat("Quick", "printf 'quick guess\\n\\n\(record(300_000))'", tier: 2, family: "a", cost: 1, act: false), |
| 337 | seat("Careful", "printf 'careful answer\\n\\n```\\n\(record(950_000))```\\n'", tier: 4, family: "b", cost: 50, act: false)] |
| 338 | let handed = await go(Fusion.Ask(text: "hello", force: question), c11) |
| 339 | let restarts = handed.lines.list.filter { $0 == .restart }.count |
| 340 | let everShown = handed.lines.list.compactMap { if case .answer(let p) = $0 { return p } else { return nil } }.joined() |
| 341 | var ownUnsure = "could not start a stub server" |
| 342 | var ownHandsOn = false |
| 343 | if let unsure = stub(says: "a guess\n\nnote hop record\nfn confidence to ulong\nret 200000\nend\n", reports: nil), let up = await unsure.start() { |
| 344 | var c = config(); c.models = [ownModel(up)] |
| 345 | let r = await go(Fusion.Ask(text: "hello", force: question), c, [strong("m11")]) |
| 346 | let onlyOwn = await go(Fusion.Ask(text: "hello", force: question), c) |
| 347 | unsure.stop() |
| 348 | ownHandsOn = r.end.outcome.ok && r.end.outcome.by == "Strong tool" && r.lines.reply == "from the strong tool" && r.lines.list.filter { $0 == .restart }.count == 1 |
| 349 | && onlyOwn.end.outcome.ok && onlyOwn.end.outcome.by == own && onlyOwn.lines.reply == "a guess" |
| 350 | ownUnsure = "\(r.lines.notes) | with nobody else to ask the unsure answer stands: โ\(onlyOwn.lines.reply)โ" |
| 351 | } |
| 352 | // The first rung is not sure and the next turns out not to be ready: the first is not given the request a second |
| 353 | // time. With a mind above them that one answers; with none, the first answer stands. |
| 354 | func rungs(_ mark: String, top: Bool) -> HopConfig { |
| 355 | var c = config() |
| 356 | c.fusionSeats = [FusionSeat(name: "First", command: ["/bin/sh", "-c", "echo ran >> \(Shell.quote(path(mark))); printf 'a first guess\\n\\n\(record(300_000))'"], tier: 2, family: "a", cost: 1, act: false), |
| 357 | seat("Not ready", "echo 'not logged in' >&2; exit 1", tier: 3, family: "b", cost: 5, act: false, signedIn: false, known: true)] |
| 358 | + (top ? [seat("Top", "echo from the top", tier: 4, family: "c", cost: 50, act: false)] : []) |
| 359 | return c |
| 360 | } |
| 361 | let replay = await go(Fusion.Ask(text: "hello", force: question), rungs("m11b", top: true)) |
| 362 | // ...and a mind of the same tier as the unsure one is not "a stronger mind": it is not asked, the first answer stands. |
| 363 | var c11d = rungs("m11d", top: false) |
| 364 | c11d.fusionSeats.append(seat("Same tier", "echo ran >> \(Shell.quote(path("s11d"))); echo a confident answer", tier: 2, family: "c", cost: 2, act: false)) |
| 365 | let sideways = await go(Fusion.Ask(text: "hello", force: question), c11d) |
| 366 | let stands = await go(Fusion.Ask(text: "hello", force: question), rungs("m11c", top: false)) |
| 367 | let onceEach = replay.end.outcome.ok && replay.end.outcome.by == "Top" && replay.lines.reply == "from the top" && read("m11b").split(separator: "\n").count == 1 |
| 368 | && replay.lines.notes.contains("Not ready is not ready") |
| 369 | && stands.end.outcome.ok && stands.end.outcome.by == "First" && stands.lines.reply == "a first guess" && stands.end.reply == "a first guess" |
| 370 | && read("m11c").split(separator: "\n").count == 1 && stands.lines.notes.contains("answer stands") |
| 371 | && sideways.end.outcome.ok && sideways.end.outcome.by == "First" && sideways.lines.reply == "a first guess" && read("s11d").isEmpty && read("m11d").split(separator: "\n").count == 1 |
| 372 | report("An unsure reply is handed on, and the record at a reply's end is never shown", |
| 373 | handed.end.outcome.ok && handed.end.outcome.by == "Careful" && handed.lines.reply == "careful answer" && restarts == 1 |
| 374 | && everShown.contains("quick guess") && !everShown.contains("hop record") && !everShown.contains("ret ") && !everShown.contains("```") |
| 375 | && handed.end.reply == "careful answer" && !handed.end.outcome.strongerLeft && ownHandsOn && onceEach, |
| 376 | "\(handed.lines.notes) | shown at the end: โ\(handed.lines.reply)โ | own model unsure: \(ownUnsure) | an unsure first rung, a second that is not ready, a third: \(replay.lines.notes); the first ran \(read("m11b").split(separator: "\n").count) time | the same without a third: \(stands.lines.notes); the first ran \(read("m11c").split(separator: "\n").count) time | with a third of the first one's tier: answered by \(sideways.end.outcome.by), the third ran: \(!read("s11d").isEmpty)") |
| 377 | |
| 378 | // 12. A command is asked a test question before it is given a request. One that is signed out says so on |
| 379 | // that: it is passed over with the reason, has not seen the request, and is not asked again while it rests. |
| 380 | // A reply that is nothing but a record is no answer: a model server that gives one is passed over, and after |
| 381 | // a command that gives one to the request nobody else is started (it ran, and what it did is not known). |
| 382 | var c12 = config() |
| 383 | c12.fusionSeats = [seat("Signed out", "echo x >> \(Shell.quote(path("m12"))); echo 'Unauthorized (401): expired credentials' >&2; exit 1", tier: 2, family: "a", cost: 1, act: false, signedIn: false, known: true), |
| 384 | seat("Works", "echo ran >> \(Shell.quote(path("w12"))); echo fine", tier: 3, family: "b", cost: 5, act: false, known: true)] |
| 385 | let passed = await go(Fusion.Ask(text: "hello", force: question), c12) |
| 386 | let workedOnce = read("w12").split(separator: "\n").count // the test question is not the request: the tool's own work ran once |
| 387 | let rested = await go(Fusion.Ask(text: "hello", resting: passed.end.failed, force: question), c12) |
| 388 | // A tool that gives no answer to the test question is not given the request; one known to be ready is not asked it. |
| 389 | var c12c = config() |
| 390 | c12c.fusionSeats = [seat("Plain", "echo x >> \(Shell.quote(path("n12"))); echo fine", tier: 3, family: "a", cost: 1, act: false, signedIn: false, known: true)] |
| 391 | let unproven = await go(Fusion.Ask(text: "hello", force: question), c12c) |
| 392 | let asksBefore = read("n12").split(separator: "\n").count |
| 393 | let knownReady = await go(Fusion.Ask(text: "hello", force: question, proven: ["Plain"]), c12c) |
| 394 | // Five tools, four of them signed out: the fifth still gets the request. No number of tries cuts that short. |
| 395 | var c12d = config() |
| 396 | c12d.fusionSeats = (1...4).map { seat("Out \($0)", "echo 'not logged in' >&2; exit 1", tier: 3, family: "f\($0)", cost: $0, act: false, signedIn: false, known: true) } |
| 397 | + [seat("Fifth", "echo from the fifth", tier: 3, family: "z", cost: 9, act: false, known: true)] |
| 398 | let fifth = await go(Fusion.Ask(text: "hello", force: question), c12d) |
| 399 | // The test question is for the tools Hop knows, with a command that takes text. A command of the person's own, |
| 400 | // and a command with no place for the text, are run with the request only: what they do, they do once. |
| 401 | var c12e = config() |
| 402 | c12e.fusionSeats = [FusionSeat(name: "Fixed", command: [knownShell, "-c", "echo changed >> \(Shell.quote(path("f12"))); echo ready"], tier: 3, family: "a", cost: 1, act: true)] |
| 403 | let fixed = await go(Fusion.Ask(text: "rename it", force: change), c12e) |
| 404 | var c12f = config() |
| 405 | c12f.fusionSeats = [seat("Their own", "echo changed >> \(Shell.quote(path("o12"))); echo ready", tier: 3, family: "a", cost: 1, act: true, signedIn: false)] |
| 406 | let theirOwn = await go(Fusion.Ask(text: "rename it", force: change), c12f) |
| 407 | // "not ready" is not the word: that tool is passed over like one that failed. |
| 408 | var c12g = config() |
| 409 | c12g.fusionSeats = [seat("Says no", "echo saw >> \(Shell.quote(path("g12"))); echo 'not ready: please sign in'", tier: 3, family: "a", cost: 1, act: false, signedIn: false, known: true), |
| 410 | seat("Works", "echo fine", tier: 3, family: "b", cost: 5, act: false, known: true)] |
| 411 | let saysNo = await go(Fusion.Ask(text: "hello", force: question), c12g) |
| 412 | let words = ["ready", "Ready.", "**ready**", "Loaded cached credentials.\nready\n"].filter { !Fusion.saysReady($0) } |
| 413 | + ["not ready", "already signed out", "not ready: please sign in", "ready to help", ""].filter { Fusion.saysReady($0) } |
| 414 | var c12b = config() |
| 415 | c12b.fusionSeats = [seat("Mute", "printf '\(record(990_000))'", tier: 2, family: "a", cost: 1, act: false), |
| 416 | seat("Works", "echo ran >> \(Shell.quote(path("m12b"))); echo fine", tier: 3, family: "b", cost: 5, act: false)] |
| 417 | let mute = await go(Fusion.Ask(text: "hello", force: question), c12b) |
| 418 | var muteServer = false, muteNotes = "could not start a stub server" |
| 419 | if let m = stub(says: "note hop record\nfn confidence to ulong\nret 990000\nend\n", reports: nil), let mp = await m.start() { |
| 420 | var c = config(); c.models = [ownModel(mp)] |
| 421 | let r = await go(Fusion.Ask(text: "hello", force: question), c, [tool("Works", "echo fine", tier: 3, family: "b", cost: 5)]) |
| 422 | m.stop() |
| 423 | muteServer = r.end.outcome.ok && r.end.outcome.by == "Works" && r.end.failed == [own: Fusion.noReplyWhy] && r.lines.reply == "fine" |
| 424 | muteNotes = r.lines.notes |
| 425 | } |
| 426 | report("A mind that fails is passed over with the reason, and rests", |
| 427 | passed.end.outcome.ok && passed.end.outcome.by == "Works" && passed.end.failed == ["Signed out": "it is not signed in"] |
| 428 | && passed.lines.notes.contains("Signed out is not ready: it is not signed in") && passed.end.proved == ["Works"] && workedOnce == 1 |
| 429 | && rested.end.outcome.ok && rested.end.outcome.by == "Works" && read("m12").split(separator: "\n").count == 1 && !rested.lines.notes.contains("not ready") |
| 430 | && !unproven.end.outcome.ok && asksBefore == 1 && unproven.lines.notes.contains("Plain is not ready: it did not answer a test question") |
| 431 | && knownReady.end.outcome.ok && knownReady.lines.reply == "fine" && read("n12").split(separator: "\n").count == 2 && !knownReady.lines.notes.contains("checking") |
| 432 | && fifth.end.outcome.ok && fifth.end.outcome.by == "Fifth" && fifth.end.failed.count == 4 |
| 433 | && fixed.end.outcome.ok && read("f12").split(separator: "\n").count == 1 && !fixed.lines.notes.contains("checking") |
| 434 | && theirOwn.end.outcome.ok && read("o12").split(separator: "\n").count == 1 && !theirOwn.lines.notes.contains("checking") |
| 435 | && saysNo.end.outcome.ok && saysNo.end.outcome.by == "Works" && read("g12").split(separator: "\n").count == 1 && words.isEmpty |
| 436 | && muteServer |
| 437 | && !mute.end.outcome.ok && mute.end.failed == ["Mute": "it gave no reply"] && read("m12b").isEmpty |
| 438 | && mute.lines.problems.count == 1 && mute.lines.problems[0].contains("no other tool was started"), |
| 439 | "\(passed.lines.notes) | asked \(read("m12").split(separator: "\n").count) time(s) over two requests | a model server's reply that is only a record: \(muteNotes) | a command's: \(mute.lines.notes) | a tool with no answer to the test question: \(unproven.lines.notes); the same tool known to be ready: โ\(knownReady.lines.reply)โ | four tools signed out, then a fifth: answered by \(fifth.end.outcome.by) | a command with no place for the text ran \(read("f12").split(separator: "\n").count) time, a command of the person's own \(read("o12").split(separator: "\n").count) time | a tool that answers โnot readyโ: \(saysNo.lines.notes) | replies read wrongly: \(words)") |
| 440 | |
| 441 | // 13. Stop ends the tool that is working, the processes it started and a tool that ignores the request to |
| 442 | // end; nothing more is started; and a stop that comes before the tool is running still ends it. |
| 443 | func pid(_ file: String) -> Int32 { Int32(read(file).trimmingCharacters(in: .whitespacesAndNewlines)) ?? -1 } |
| 444 | func stopRun(_ script: String, started: String, limit: Double, afterEndOf ended: String? = nil) async -> (lines: Lines, end: Fusion.End, took: Double, stillThere: Bool, wasEnded: Bool) { |
| 445 | let control = Fusion.Control(), t = Date() |
| 446 | let running = Task { await go(Fusion.Ask(text: "rename it", force: change), config(), [tool("Slow", script, tier: 4, family: "a", cost: 1), strong("m13b")], control: control) } |
| 447 | var waited = 0 |
| 448 | while read(started).isEmpty, waited < 100 { try? await Task.sleep(nanoseconds: 100_000_000); waited += 1 } |
| 449 | // `afterEndOf`: the stop comes only when the tool itself (the process whose id is in that file) has ended. |
| 450 | var polls = 0 |
| 451 | if let ended { while alive(pid(ended)), polls < 300 { try? await Task.sleep(nanoseconds: 10_000_000); polls += 1 } } |
| 452 | let wasEnded = ended.map { !alive(pid($0)) } ?? false |
| 453 | control.stop() |
| 454 | let r = await running.value |
| 455 | return (r.lines, r.end, Date().timeIntervalSince(t), control.stoppedCommands.contains { !$0.isGone }, wasEnded) |
| 456 | } |
| 457 | let plain = await stopRun("echo $$ > \(Shell.quote(path("p13"))); sleep 30; echo late >> \(Shell.quote(path("late13")))", started: "p13", limit: 15) |
| 458 | let child = await stopRun("sleep 300 & echo $! > \(Shell.quote(path("c13"))); echo $$ > \(Shell.quote(path("p13c"))); wait", started: "p13c", limit: 15) |
| 459 | let stubborn = await stopRun("trap '' TERM; echo $$ > \(Shell.quote(path("p13s"))); while :; do sleep 1; done", started: "p13s", limit: 15) |
| 460 | // A tool that ends when asked, with a child that does not: the child would write its mark 9 s on. |
| 461 | let orphan = await stopRun("(trap '' TERM; sleep 9; echo late > \(Shell.quote(path("lc13")))) & echo $! > \(Shell.quote(path("cc13"))); echo $$ > \(Shell.quote(path("p13d"))); wait", started: "p13d", limit: 15) |
| 462 | let orphanAliveAtStop = alive(pid("cc13")) |
| 463 | // A tool that, asked to end, starts one more process that ignores the request, and then ends itself. |
| 464 | let lateBorn = await stopRun("trap \"(trap '' TERM; sleep 9; echo late > \(Shell.quote(path("lt13")))) & echo \\$! > \(Shell.quote(path("ct13"))); exit 0\" TERM; echo $$ > \(Shell.quote(path("p13t"))); while :; do sleep 1; done", started: "p13t", limit: 15) |
| 465 | var w13 = 0 |
| 466 | while read("ct13").isEmpty, w13 < 30 { try? await Task.sleep(nanoseconds: 100_000_000); w13 += 1 } |
| 467 | let lateBornAlive = alive(pid("ct13")) |
| 468 | // A tool that has ended by itself and left a process running that still holds its output and ignores the |
| 469 | // request to end. Stop comes while Hop still reads that output. |
| 470 | let leftover = await stopRun("(trap '' TERM; sleep 9; echo late > \(Shell.quote(path("lx13")))) & echo $! > \(Shell.quote(path("cx13"))); echo $$ > \(Shell.quote(path("p13x"))); exit 0", started: "p13x", limit: 15, afterEndOf: "p13x") |
| 471 | let leftoverAlive = alive(pid("cx13")), leftoverSeen = leftover.stillThere && leftover.wasEnded |
| 472 | try? await Task.sleep(nanoseconds: UInt64((CommandRun.graceToEnd + 2) * 1e9)) // until the ones that would not end were ended by force |
| 473 | let orphanGone = !alive(pid("cc13")), lateBornGone = !alive(pid("ct13")), leftoverGone = !alive(pid("cx13")) |
| 474 | try? await Task.sleep(nanoseconds: 5_000_000_000) // past the moment the children would have written |
| 475 | let early = Fusion.Control(); early.stop() |
| 476 | let never = await go(Fusion.Ask(text: "rename it", force: change), config(), [tool("Slow", "echo ran > \(Shell.quote(path("e13")))", tier: 4, family: "a", cost: 1)], control: early) |
| 477 | let preStopped = CommandRun(["/bin/sh", "-c", "echo ran > \(Shell.quote(path("e13b"))); sleep 30"]) |
| 478 | preStopped.stop() |
| 479 | let t13 = Date() |
| 480 | let preCode: Int32 = await withCheckedContinuation { c in preStopped.start(onLine: { _ in }, onExit: { c.resume(returning: $0) }) } |
| 481 | let preTook = Date().timeIntervalSince(t13) |
| 482 | // A command that ended by itself and was never asked to end is gone: it cannot hold up the next message. |
| 483 | let quick = CommandRun(["/bin/sh", "-c", "true"], ownGroup: true) |
| 484 | let goneBefore = quick.isGone // not started yet: nothing of it runs |
| 485 | _ = await withCheckedContinuation { (c: CheckedContinuation<Int32, Never>) in quick.start(onLine: { _ in }, onExit: { c.resume(returning: $0) }) } |
| 486 | let quickGone = goneBefore && quick.isGone |
| 487 | report("Stop ends the tool that is working, what it started and a tool that will not end; nothing more starts", |
| 488 | !plain.end.outcome.ok && plain.lines.problems == ["Stopped."] && plain.took < 15 && !alive(pid("p13")) && read("late13").isEmpty && read("m13b").isEmpty && plain.end.failed.isEmpty |
| 489 | && !alive(pid("c13")) && !alive(pid("p13c")) && child.took < 15 |
| 490 | && !alive(pid("p13s")) && stubborn.took < CommandRun.graceToEnd + 8 && stubborn.took >= CommandRun.graceToEnd - 1 |
| 491 | && !never.end.outcome.ok && read("e13").isEmpty && never.lines.problems == ["Stopped."] |
| 492 | && !orphan.end.outcome.ok && orphan.took < 15 && orphanAliveAtStop && orphanGone && read("lc13").isEmpty |
| 493 | && !lateBorn.end.outcome.ok && lateBornAlive && lateBornGone && read("lt13").isEmpty |
| 494 | && !leftover.end.outcome.ok && leftoverAlive && leftoverSeen && leftoverGone && read("lx13").isEmpty |
| 495 | && preCode == CommandRun.notStarted && preTook < 2 && read("e13b").isEmpty && quickGone, |
| 496 | "a waiting tool: ended after \(String(format: "%.1f", plain.took)) s with \(plain.lines.notes); its child: gone \(!alive(pid("c13"))); one that ignores the request: gone after \(String(format: "%.1f", stubborn.took)) s (by force after \(Int(CommandRun.graceToEnd)) s); a child that ignores the request while its tool ends: alive at the stop \(orphanAliveAtStop), gone after the wait \(orphanGone), wrote nothing \(read("lc13").isEmpty); a process started while its tool was ending, which ignores the request: alive then \(lateBornAlive), gone after the wait \(lateBornGone), wrote nothing \(read("lt13").isEmpty); a process left running by a tool that had already ended (the tool was gone at the stop: \(leftover.wasEnded)): alive at the stop \(leftoverAlive), known to be still there \(leftoverSeen), gone after the wait \(leftoverGone), wrote nothing \(read("lx13").isEmpty); stopped before it began: ran nothing \(read("e13").isEmpty); a command stopped before it was started: never launched (wrote nothing: \(read("e13b").isEmpty)), ended after \(String(format: "%.1f", preTook)) s with exit \(preCode)") |
| 497 | |
| 498 | // 14. The person's yes is asked once, before the first command runs, whatever the settings say the command |
| 499 | // is for; a no runs nothing (a command never sorts either); a model server needs no yes. |
| 500 | final class Count: @unchecked Sendable { let l = NSLock(); var n = 0; func up() { l.lock(); n += 1; l.unlock() }; var now: Int { l.lock(); defer { l.unlock() }; return n } } |
| 501 | let asked = Count() |
| 502 | let no = await go(Fusion.Ask(text: "rename it", force: change), cfg, [strong("m14")], mayAct: { _ in asked.up(); return false }) |
| 503 | let askedForTool = asked.now |
| 504 | let talk = await go(Fusion.Ask(text: "hello", force: question), cfg, [strong("m14")], mayAct: { _ in asked.up(); return false }) |
| 505 | var c14 = config() // a command the settings call harmless (act false, the default) is still a command |
| 506 | c14.fusionSeats = [seat("Called harmless", "echo ran >> \(Shell.quote(path("m14b"))); echo hi", tier: 2, family: "a", cost: 1, act: false)] |
| 507 | let quiet = Count() |
| 508 | let harmless = await go(Fusion.Ask(text: "hello there friend"), c14, mayAct: { _ in quiet.up(); return false }) // not sorted beforehand: the sorting must not run it either |
| 509 | let yes = Count() |
| 510 | let twice = await go(Fusion.Ask(text: "design it", force: Fusion.Triage(kind: 2, difficulty: 5, stakes: 2, confidence: 1_000_000, by: "the test")), |
| 511 | { var c = config(); c.fusionSeats = [seat("A", "echo a", tier: 4, family: "a", cost: 1, act: false), seat("B", "echo b", tier: 4, family: "b", cost: 2, act: false)]; return c }(), |
| 512 | mayAct: { _ in yes.up(); return true }) |
| 513 | report("The yes to agent tools is asked once, before any command runs, whatever the settings call it; a no runs nothing", |
| 514 | !no.end.outcome.ok && no.end.outcome.declined && askedForTool == 1 && read("m14").isEmpty && no.lines.problems.count == 1 |
| 515 | && talk.end.outcome.ok && talk.end.outcome.by == own && asked.now == 1 |
| 516 | && !harmless.end.outcome.ok && harmless.end.outcome.declined && quiet.now == 1 && read("m14b").isEmpty |
| 517 | && twice.end.outcome.ok && yes.now == 1 && twice.end.outcome.acted, |
| 518 | "a request for a tool: asked \(askedForTool) time(s), ran nothing: \(read("m14").isEmpty), said โ\(no.lines.problems.first ?? "")โ; a question the own model answers: not asked (\(asked.now - askedForTool)); a command marked as answering only: asked \(quiet.now), ran \(read("m14b").split(separator: "\n").count) times; several commands in one request: asked \(yes.now) time") |
| 519 | |
| 520 | // 15. "Stronger" asks the next mind up and tells it what was replied before. |
| 521 | let again = await go(Fusion.Ask(text: "hello", above: Fusion.Standing(triage: question, tier: 3, by: own, fused: false, reply: "EARLIER-REPLY")), |
| 522 | cfg, [tool("Reader", "printf '%s' \"$1\" > \(Shell.quote(path("p15"))); echo second opinion", tier: 4, family: "anthropic", cost: 100)]) |
| 523 | report("Stronger asks the next mind up and shows it the earlier reply", |
| 524 | again.end.outcome.ok && again.end.outcome.by == "Reader" && read("p15").contains("EARLIER-REPLY") && read("p15").contains("asked for a stronger mind") |
| 525 | && again.lines.notes.contains("a stronger mind was asked for") && again.end.standing?.tier == 4, |
| 526 | again.lines.notes) |
| 527 | |
| 528 | // 16. Several strong minds, fused: each answers alone, one fuses, the others agree, the fused text is the |
| 529 | // reply. For work that changes things the agreed plan is carried out by one tool; a plan the minds did not |
| 530 | // look at again is shown and NOT carried out. |
| 531 | func voice(_ review: String, mark: String, fuse: String = "echo FUSED-TEXT", merge: String = "echo MERGED-TEXT", carry: String = "echo carried out", |
| 532 | propose: String? = nil) -> String { |
| 533 | "case \"$1\" in *'Carry out this plan'*) echo ran >> \(Shell.quote(path(mark))); \(carry);; *'=== Mind 1 ==='*) \(fuse);; *'Here is a draft and the changes'*) \(merge);; *'=== Draft ==='*) \(review);; *) \(propose ?? "printf 'a proposal\\n\(record(900_000))'");; esac" |
| 534 | } |
| 535 | let agree = "printf 'note hop record\\nfn deltas to ulong\\nret 0\\nend\\nfn agree to ulong\\nret 1\\nend\\nfn confidence to ulong\\nret 900000\\nend\\n'" |
| 536 | func trio(_ review: String, mark: String, act: Bool, fuse: String = "echo FUSED-TEXT", merge: String = "echo MERGED-TEXT", carry: String = "echo carried out") -> HopConfig { |
| 537 | var c = config() |
| 538 | let script = voice(review, mark: mark, fuse: fuse, merge: merge, carry: carry) |
| 539 | c.fusionSeats = [seat("One", script, tier: 4, family: "a", cost: 10, act: act), seat("Two", script, tier: 4, family: "b", cost: 20, act: act), |
| 540 | seat("Three", script, tier: 3, family: "c", cost: 30, act: act)] |
| 541 | return c |
| 542 | } |
| 543 | let object = "printf 'Step 2 is wrong.\\nnote hop record\\nfn deltas to ulong\\nret 1\\nend\\nfn agree to ulong\\nret 0\\nend\\nfn confidence to ulong\\nret 900000\\nend\\n'" |
| 544 | let open = Fusion.Triage(kind: 2, difficulty: 5, stakes: 2, confidence: 1_000_000, by: "the test") |
| 545 | let job = Fusion.Triage(kind: 3, difficulty: 5, stakes: 2, confidence: 1_000_000, by: "the test") |
| 546 | let fused = await go(Fusion.Ask(text: "design it", history: [ChatMessage(role: "user", text: "KEEP-IT-BLUE")], force: open), trio(agree, mark: "m16", act: false)) |
| 547 | let done16 = await go(Fusion.Ask(text: "build it", force: job), trio(agree, mark: "m16a", act: true)) |
| 548 | let unseen = await go(Fusion.Ask(text: "build it", force: job), trio("echo no record here", mark: "m16b", act: true)) |
| 549 | // The minds ask for a change. The tool that puts it in changes a file and fails: the run ends there. Put in, the merged text is the answer. |
| 550 | let torn = await go(Fusion.Ask(text: "build it", force: job), trio(object, mark: "m16c", act: true, merge: "echo changed >> \(Shell.quote(path("x16c"))); exit 1")) |
| 551 | // A tool that fails while it looks at the draft: the run ends there too. |
| 552 | let badLook = await go(Fusion.Ask(text: "build it", force: job), trio("echo changed >> \(Shell.quote(path("x16h"))); exit 1", mark: "m16h", act: true, merge: "echo merged >> \(Shell.quote(path("g16h"))); echo MERGED-TEXT")) |
| 553 | let mended = await go(Fusion.Ask(text: "design it", force: open), trio(object, mark: "m16d", act: false)) |
| 554 | // A fused text that is nothing but a record is no answer: the run fails, it does not end well with an empty reply. |
| 555 | let hollow = await go(Fusion.Ask(text: "design it", force: open), trio(agree, mark: "m16e", act: false, fuse: "printf '\(record(900_000))'")) |
| 556 | // The mind that carries out the plan says nothing but a record: that is not shown as work done. |
| 557 | let silentDoer = await go(Fusion.Ask(text: "build it", force: job), trio(agree, mark: "m16f", act: true, carry: "printf '\(record(900_000))'")) |
| 558 | // One of three tools fails on the request while two answer: nobody is started after it, not the one that fuses. |
| 559 | var c16g = trio(agree, mark: "m16g", act: true, fuse: "echo fused >> \(Shell.quote(path("f16g"))); echo FUSED-TEXT") |
| 560 | c16g.fusionSeats[2] = seat("Three", voice(agree, mark: "m16g", fuse: "echo fused >> \(Shell.quote(path("f16g"))); echo FUSED-TEXT", propose: "echo changed >> \(Shell.quote(path("x16g"))); exit 1"), |
| 561 | tier: 3, family: "c", cost: 30, act: true) |
| 562 | let oneFails = await go(Fusion.Ask(text: "build it", force: job), c16g) |
| 563 | // A command with no place for what it is asked does its one thing each time it is run. Hard work that would be |
| 564 | // fused among two tools is done by one of them instead, and that command runs once at most. |
| 565 | var c16i = config() |
| 566 | c16i.fusionSeats = [FusionSeat(name: "Fixed", command: ["/bin/sh", "-c", "echo changed >> \(Shell.quote(path("f16i"))); echo did my one thing"], tier: 4, family: "a", cost: 1, act: true), |
| 567 | seat("Other", "echo ran >> \(Shell.quote(path("o16i"))); echo did it", tier: 4, family: "b", cost: 2, act: true)] |
| 568 | let withFixed = await go(Fusion.Ask(text: "build it", force: job), c16i) |
| 569 | let fixedSeats = await Fusion.seats(c16i, installed: []) |
| 570 | let fixedPlan = Fusion.plan(job, fixedSeats, down: [], cfg: c16i) |
| 571 | var c16j = c16i |
| 572 | c16j.fusionSeats[0] = seat("Takes text", "echo ran >> \(Shell.quote(path("t16j"))); echo did it", tier: 4, family: "a", cost: 1, act: true) |
| 573 | let bothTakeText = Fusion.plan(job, await Fusion.seats(c16j, installed: []), down: [], cfg: c16j) |
| 574 | // Two model servers are to be fused and one of them is busy: the other's answer is one mind's answer. It is asked |
| 575 | // once, and the line under it is its own: where it ran and the model it named. |
| 576 | var oneVoice = false, oneNotes = "could not start a stub server" |
| 577 | if let silent = stub(chat: 503, reports: nil), let qp = await silent.start(), let speaks = stub(says: "the surviving answer", reports: "actual-model"), let sp = await speaks.start() { |
| 578 | var c = config() |
| 579 | c.models = [ModelEndpoint(name: "Silent label", baseURL: "http://127.0.0.1:\(qp)/v1", model: "configured-a"), |
| 580 | ModelEndpoint(name: "Friendly label", baseURL: "http://127.0.0.1:\(sp)/v1", model: "configured-b")] |
| 581 | c.fusionSeats = [FusionSeat(name: "Silent label", model: "Silent label", tier: 4, family: "a", cost: 1, act: false), |
| 582 | FusionSeat(name: "Friendly label", model: "Friendly label", tier: 4, family: "b", cost: 2, act: false)] |
| 583 | let r = await go(Fusion.Ask(text: "design it", above: Fusion.Standing(triage: open, tier: 4, by: "an earlier mind", fused: false, reply: "EARLIER")), c) |
| 584 | let posts = speaks.requests.filter { $0.hasPrefix("POST ") }.count |
| 585 | silent.stop(); speaks.stop() |
| 586 | oneVoice = r.end.outcome.ok && r.end.outcome.by == "Friendly label" && r.lines.reply == "the surviving answer" && posts == 1 |
| 587 | && r.end.outcome.meta.hasPrefix("๐ on this Mac") && r.end.outcome.meta.contains("answered by actual-model") && r.lines.notes.contains("one mind's answer, not a fusion") |
| 588 | oneNotes = "\(r.lines.notes) | under it: \(r.end.outcome.meta) | asked \(posts) time(s)" |
| 589 | } |
| 590 | // The own model goes first and is not sure; three servers online are fused; the one that is to fuse turns out |
| 591 | // busy. Another of the three fuses (not the own model, which is no stronger): the fused text is the answer. |
| 592 | // And when none of them can fuse, the own model's answer stands instead of no answer at all. |
| 593 | final class Turn: @unchecked Sendable { let l = NSLock(); var n = 0; func next() -> Int { l.lock(); defer { l.unlock() }; n += 1; return n } } |
| 594 | func afterUnsure(failFusing: Int, three: Bool = true, ownFirst: Bool = true) async -> (r: (end: Fusion.End, lines: Lines)?, ownAsked: Int) { |
| 595 | let fusing = Turn() |
| 596 | let agreeText = "note hop record\nfn deltas to ulong\nret 0\nend\nfn agree to ulong\nret 1\nend\nfn confidence to ulong\nret 900000\nend\n" |
| 597 | func mind(_ name: String) -> SelfTestServer? { |
| 598 | scripted { body in |
| 599 | // The fused text says how many of the proposals it was given: the one that fuses must get them all. |
| 600 | if body.contains("=== Mind 1 ===") { return fusing.next() <= failFusing ? nil : "FUSED-BY-\(name) from \(["A", "B", "C"].filter { body.contains("a proposal from \($0)") }.count)" } |
| 601 | if body.contains("=== Draft ===") { return agreeText } |
| 602 | return "a proposal from \(name)\n\nnote hop record\nfn confidence to ulong\nret 900000\nend\n" |
| 603 | } |
| 604 | } |
| 605 | guard let local = stub(says: "a guess of my own\n\nnote hop record\nfn confidence to ulong\nret 300000\nend\n", reports: nil), let lp = await local.start(), |
| 606 | let a = mind("A"), let ap = await a.start(), let b = mind("B"), let bp = await b.start(), let c3 = mind("C"), let cp = await c3.start() else { return (nil, 0) } |
| 607 | var c = config() |
| 608 | c.models = [ownModel(lp), online("A", ap), online("B", bp), online("C", cp)] |
| 609 | c.fusionSeats = (ownFirst ? [FusionSeat(name: own, model: own, tier: 3, family: "local", cost: 1, act: false)] : []) |
| 610 | + [FusionSeat(name: "A", model: "A", tier: 4, family: "a", cost: 2, act: false), FusionSeat(name: "B", model: "B", tier: 4, family: "b", cost: 3, act: false)] |
| 611 | + (three ? [FusionSeat(name: "C", model: "C", tier: 4, family: "c", cost: 4, act: false)] : []) |
| 612 | let r = await go(Fusion.Ask(text: "design it", force: open), c) |
| 613 | let asked = local.requests.filter { $0.hasPrefix("POST ") }.count |
| 614 | local.stop(); a.stop(); b.stop(); c3.stop() |
| 615 | return (r, asked) |
| 616 | } |
| 617 | let fuserBusy = await afterUnsure(failFusing: 1), allRefuse = await afterUnsure(failFusing: 99) |
| 618 | // Two servers, the fusing one busy: the other has both proposals in front of it and fuses them. No new fusion has to |
| 619 | // be formed for that. The same without an own model in front. |
| 620 | let twoLeft = await afterUnsure(failFusing: 1, three: false), twoAlone = await afterUnsure(failFusing: 1, three: false, ownFirst: false) |
| 621 | let oneFuses = [twoLeft, twoAlone].allSatisfy { x in |
| 622 | x.r.map { $0.end.outcome.ok && $0.lines.reply.hasPrefix("FUSED-BY-") && $0.lines.reply.hasSuffix(" from 2") && $0.lines.notes.contains("could not fuse the answers") && $0.lines.notes.contains("Fused by") } ?? false |
| 623 | } && twoLeft.ownAsked == 1 && twoAlone.ownAsked == 0 |
| 624 | let replaced = fuserBusy.r.map { r in |
| 625 | r.end.outcome.ok && r.lines.reply.hasPrefix("FUSED-BY-") && r.lines.reply.hasSuffix(" from 3") && r.lines.notes.contains("was not sure of its answer") && r.lines.notes.contains("could not fuse the answers") |
| 626 | && r.lines.notes.contains("Fused by") && fuserBusy.ownAsked == 1 |
| 627 | } ?? false |
| 628 | let standsAfter = allRefuse.r.map { r in |
| 629 | r.end.outcome.ok && r.end.outcome.by == own && r.lines.reply == "a guess of my own" && r.end.reply == "a guess of my own" && allRefuse.ownAsked == 1 && r.lines.notes.contains("answer stands") |
| 630 | } ?? false |
| 631 | report("Open-ended work is fused from several minds; an agreed plan is carried out once, one that was not agreed is not", |
| 632 | fused.end.outcome.ok && fused.lines.reply == "FUSED-TEXT" && fused.end.outcome.meta.contains("fused from One, Two, Three") |
| 633 | && fused.end.outcome.by == "3 minds" && !fused.end.outcome.strongerLeft && fused.lines.notes.contains("the minds agree") && fused.end.outcome.acted |
| 634 | && done16.end.outcome.ok && done16.lines.reply == "carried out" && read("m16a").split(separator: "\n").count == 1 |
| 635 | && done16.end.outcome.meta.contains("planned by One, Two, Three") && done16.end.outcome.meta.contains("carried out by One") |
| 636 | && unseen.end.outcome.ok && read("m16b").isEmpty && unseen.lines.reply == "FUSED-TEXT" && unseen.end.outcome.meta.hasSuffix("given to no tool to carry out") |
| 637 | && unseen.lines.problems.contains { $0.contains("gave it to no tool to carry out") } |
| 638 | // A tool that fails while it puts the changes in may have changed things: the run ends and says so, and does not say that nothing was done. |
| 639 | && !torn.end.outcome.ok && read("m16c").isEmpty && !read("x16c").isEmpty |
| 640 | && torn.lines.problems.contains { $0.contains("could not put the changes in") && $0.contains("It may have changed things") && $0.contains("no other tool was started") } |
| 641 | && !torn.lines.notes.contains("no tool to carry out") |
| 642 | && !badLook.end.outcome.ok && read("m16h").isEmpty && read("g16h").isEmpty && badLook.lines.problems.contains { $0.contains("did not finish looking at the draft") && $0.contains("no other tool was started") } |
| 643 | && mended.end.outcome.ok && mended.lines.reply == "MERGED-TEXT" |
| 644 | && !hollow.end.outcome.ok && hollow.end.reply.isEmpty && hollow.lines.reply.isEmpty && hollow.lines.problems.contains { $0.contains("could not fuse the answers") } |
| 645 | && !silentDoer.end.outcome.ok && silentDoer.end.reply.isEmpty && silentDoer.lines.reply.isEmpty && silentDoer.lines.problems.contains { $0.contains("did not finish: it gave no reply") } |
| 646 | && oneVoice && replaced && standsAfter && oneFuses |
| 647 | && withFixed.end.outcome.ok && read("f16i").split(separator: "\n").count + read("o16i").split(separator: "\n").count == 1 |
| 648 | && [4, 5].contains(fixedPlan.verdict) && bothTakeText.verdict == 6 && !withFixed.lines.notes.contains("fusing") |
| 649 | && !oneFails.end.outcome.ok && read("x16g").split(separator: "\n").count == 1 && read("f16g").isEmpty && read("m16g").isEmpty |
| 650 | && oneFails.lines.problems.contains { $0.contains("Three did not finish") && $0.contains("no other tool was started") }, |
| 651 | "\(fused.lines.notes) | \(fused.end.outcome.meta) || agreed: \(done16.end.outcome.meta) || not looked at again: \(unseen.lines.notes) || a tool that fails putting a change in: \(torn.lines.problems.last ?? "") || a tool that fails looking at the draft: \(badLook.lines.problems.last ?? "") || put in: \(mended.lines.reply) || a fused text that is only a record: \(hollow.lines.notes) || a plan carried out with only a record for an answer: \(silentDoer.lines.problems.last ?? "") || two model servers to be fused, one busy: \(oneNotes) || after an unsure own model, three servers online, the fusing one busy: \(fuserBusy.r?.lines.notes ?? "could not start the stub servers") || the same with nobody able to fuse: \(allRefuse.r?.lines.notes ?? "could not start the stub servers") || two servers, the fusing one busy: \(twoAlone.r?.lines.notes ?? "could not start the stub servers"); the answer: โ\(twoAlone.r?.lines.reply ?? "")โ || two tools, one with no place for the text: plan verdict \(fixedPlan.verdict) (two that take text: \(bothTakeText.verdict)), the fixed command ran \(read("f16i").split(separator: "\n").count) time(s), the other \(read("o16i").split(separator: "\n").count) || one of three tools fails on the request: \(oneFails.lines.problems.last ?? ""), the fusing mind ran: \(!read("f16g").isEmpty)") |
| 652 | |
| 653 | // 17. Sorting: a model server sorts the request, with the end of the conversation before it; a command from the |
| 654 | // settings never sorts; when nothing usable comes the words decide and say so; a follow-up to work that |
| 655 | // changed things, or a short go-ahead after any talk, is taken as such work, an ordinary question is not; an |
| 656 | // own model sorts whatever its tier; a busy sorter is asked once, not again for the answer. |
| 657 | func server(_ name: String, _ port: Int, tier: Int) -> [Fusion.Seat] { |
| 658 | [Fusion.Seat(id: 1, seat: FusionSeat(name: name, model: name, tier: tier, family: "local", cost: 1, act: false), |
| 659 | endpoint: ModelEndpoint(name: name, baseURL: "http://127.0.0.1:\(port)/v1", model: "configured-id"), ready: true)] |
| 660 | } |
| 661 | func lastPrompt(_ body: String) -> String { |
| 662 | let j = (try? JSONSerialization.jsonObject(with: Data(body.utf8))) as? [String: Any] |
| 663 | return ((j?["messages"] as? [[String: Any]])?.last?["content"] as? String) ?? "" |
| 664 | } |
| 665 | let sortText = "note hop record\nfn kind to ulong\nret 1\nend\nfn difficulty to ulong\nret 1\nend\nfn stakes to ulong\nret 1\nend\nfn confidence to ulong\nret 990000\nend\n" |
| 666 | var sorted17 = Fusion.Triage(), p17 = "", ownSorts = false |
| 667 | if let sorts = stub(says: sortText, reports: nil), let sp = await sorts.start() { |
| 668 | sorted17 = await Fusion.triage("what is the capital of France?", server("Sorter", sp, tier: 2), cwd: dir.path, |
| 669 | history: [ChatMessage(role: "user", text: "EARLIER-TURN"), ChatMessage(role: "assistant", text: String(repeating: "x", count: 700))]) |
| 670 | p17 = lastPrompt(sorts.bodies.last ?? "") |
| 671 | let top = await Fusion.triage("what is the capital of France?", server("Top", sp, tier: 4), cwd: dir.path) |
| 672 | sorts.stop() |
| 673 | ownSorts = top.by == "Top" && top.difficulty == 1 |
| 674 | } |
| 675 | let unsorted = await Fusion.triage("please delete the old branch", server("Sorter", wp, tier: 2), cwd: dir.path) // that server says "ready": no record |
| 676 | let byCommand = [Fusion.Seat(id: 1, seat: seat("Command", "echo ran > \(Shell.quote(path("m17"))); echo sorted", tier: 2, family: "a", cost: 1, act: false), endpoint: nil, ready: true)] |
| 677 | let notByCommand = await Fusion.triage("hello there friend", byCommand, cwd: dir.path) |
| 678 | let follow = await Fusion.triage("yes, do that", [], cwd: dir.path, history: [ChatMessage(role: "user", text: "rename a.txt"), ChatMessage(role: "assistant", text: "I would run mv.")], previousKind: 3) |
| 679 | let fresh = await Fusion.triage("yes, do that", [], cwd: dir.path, previousKind: 3) |
| 680 | // A go-ahead after a talk about how to do something (sorted as a question then) is work that changes things too. |
| 681 | let talked = [ChatMessage(role: "user", text: "how would I rename a.txt?"), ChatMessage(role: "assistant", text: "Use mv a.txt b.txt.")] |
| 682 | let goes = await Fusion.triage("Yes, do that.", [], cwd: dir.path, history: talked, previousKind: 1) |
| 683 | let wonders = await Fusion.triage("why is that the way?", [], cwd: dir.path, history: talked, previousKind: 1) |
| 684 | let asksOn = await Fusion.triage("Do you know French?", [], cwd: dir.path, history: talked, previousKind: 1) |
| 685 | let goAheads = ["ok", "yes please", "go ahead", "ok do it", "run it", "sure, do that now"].filter { !Fusion.goAhead($0) } |
| 686 | let notGoAheads = ["Do you know French?", "is that ok?", "go to the store for me", "okay but what about the tests", "do not do that", "yes, and also delete the old ones"].filter { Fusion.goAhead($0) } |
| 687 | var once = "could not start a stub server" |
| 688 | var askedOnce = false |
| 689 | if let busy = stub(chat: 503, reports: nil), let bp = await busy.start() { |
| 690 | var c = config(); c.models = [ownModel(bp)] |
| 691 | c.fusionSeats = [FusionSeat(name: own, model: own, tier: 3, family: "local", cost: 1, act: false), seat("Second", "echo from the second mind", tier: 3, family: "b", cost: 5, act: false)] |
| 692 | let r = await go(Fusion.Ask(text: "hello there"), c) |
| 693 | let posts = busy.requests.filter { $0.hasPrefix("POST ") }.count |
| 694 | busy.stop() |
| 695 | askedOnce = r.end.outcome.ok && r.end.outcome.by == "Second" && posts == 1 && r.end.failed[own] == Fusion.busyWhy |
| 696 | && r.lines.notes.contains("\(own) is busy with something else") && !r.lines.notes.contains("Hop chose \(own)") && r.lines.notes.contains("by the words alone") |
| 697 | once = "\(r.lines.notes) | the busy server was asked \(posts) time(s)" |
| 698 | } |
| 699 | report("A cheap mind sorts the request; without a usable sorting the words decide and say so; a busy sorter is not asked twice", |
| 700 | sorted17.by == "Sorter" && sorted17.difficulty == 1 && sorted17.kind == 1 && sorted17.tried.isEmpty |
| 701 | && p17.contains("EARLIER-TURN") && p17.contains("[cut]") && !p17.contains(String(repeating: "x", count: 601)) && p17.hasSuffix("what is the capital of France?") |
| 702 | && unsorted.by == "the words alone" && unsorted.kind == 3 && unsorted.difficulty >= 2 && unsorted.confidence < 700_000 && unsorted.tried == "Sorter: no usable record" |
| 703 | && notByCommand.by == "the words alone" && read("m17").isEmpty |
| 704 | && follow.kind == 3 && follow.by.contains("follow-up") && fresh.kind == 1 |
| 705 | && goes.kind == 3 && goes.by.contains("go-ahead") && wonders.kind == 1 && asksOn.kind == 1 && goAheads.isEmpty && notGoAheads.isEmpty |
| 706 | && ownSorts |
| 707 | && askedOnce, |
| 708 | "sorted by \(sorted17.by) as difficulty \(sorted17.difficulty), with the conversation in front; junk from the sorter: by \(unsorted.by), kind \(unsorted.kind), asked in vain: \(unsorted.tried); a command from the settings sorted: \(!read("m17").isEmpty); โyes, do thatโ after work that changed things: kind \(follow.kind), with nothing before it: kind \(fresh.kind); after a talk about how to: kind \(goes.kind), a question after the same talk: kind \(wonders.kind), โDo you know French?โ: kind \(asksOn.kind); go-aheads not taken as one: \(goAheads), questions taken as one: \(notGoAheads); an own model of tier 4 sorted: \(ownSorts); busy sorter: \(once)") |
| 709 | |
| 710 | // 18. What is shown of a reply while it arrives, however it is cut into pieces: it grows as the pieces come, |
| 711 | // never holds the record, and ends up as exactly what the record reader calls the reply. |
| 712 | let rec = "note hop record\nfn confidence to ulong\nret 910000\nend\n" |
| 713 | let cases: [(String, String, String)] = [ |
| 714 | ("plain", "Paris.\n", "Paris."), ("no newline at the end", "Paris.", "Paris."), |
| 715 | ("record after a blank line", "Paris.\n\n" + rec, "Paris."), ("record directly", "Paris.\n" + rec, "Paris."), |
| 716 | ("record in a fence", "Paris.\n\n```\n" + rec + "```\n", "Paris."), |
| 717 | ("code, then the record", "Use:\n```sh\nls -la\n```\n\n" + rec, "Use:\n```sh\nls -la\n```"), |
| 718 | ("code at the end", "Use:\n```\nls\n```", "Use:\n```\nls\n```"), |
| 719 | ("code, then a fenced record", "A\n```\nx\n```\n```\n" + rec + "```", "A\n```\nx\n```"), |
| 720 | ("blank lines inside and at the end", "One.\n\nTwo.\n\n\n", "One.\n\nTwo."), |
| 721 | ("blank lines in front", "\n\nParis.\n", "Paris."), |
| 722 | ("a line that only starts like the marker", "note hop records are fine\nok\n", "note hop records are fine\nok"), |
| 723 | ("half a marker at the end", "note hop", "note hop"), |
| 724 | ("an indented marker", "x\n note hop record\nfn a to ulong\nret 1\nend\n", "x"), |
| 725 | ("only a record", rec, ""), ("a line that starts with a backtick", "`ls` lists files\nyes\n", "`ls` lists files\nyes"), |
| 726 | ("the marker without a line end", "Yes.\nnote hop record", "Yes."), |
| 727 | ("two paragraphs and code inside", "A\n\n```\nx\n\ny\n```\n\nB\n", "A\n\n```\nx\n\ny\n```\n\nB"), |
| 728 | ("the marker quoted in the reply, then the real record", "It ends with:\nnote hop record\nfn x to ulong\nret 1\nend\nThat is all.\n\n" + rec, "It ends with:\nnote hop record\nfn x to ulong\nret 1\nend\nThat is all."), |
| 729 | ("the marker quoted in code, then the real record", "```\nnote hop record\n```\nSee above.\n" + rec, "```\nnote hop record\n```\nSee above."), |
| 730 | ] |
| 731 | final class Shown: @unchecked Sendable { let l = NSLock(); var s = "", n = 0; func add(_ x: String) { l.lock(); s += x; n += 1; l.unlock() } } |
| 732 | var wrong: [String] = [] |
| 733 | for (name, input, want) in cases { |
| 734 | for cut in [1, 2, 3, 5, 7, 1000] { |
| 735 | let box = Shown(), live = LiveText { box.add($0) } |
| 736 | var i = input.startIndex |
| 737 | while i < input.endIndex { let j = input.index(i, offsetBy: cut, limitedBy: input.endIndex) ?? input.endIndex; live.add(String(input[i..<j])); i = j } |
| 738 | live.finish() |
| 739 | if box.s != want { wrong.append("\(name), pieces of \(cut): โ\(box.s)โ") } |
| 740 | if box.s != FusionRecord.parse(input).body { wrong.append("\(name), pieces of \(cut): shown differs from what the record reader keeps") } |
| 741 | } |
| 742 | } |
| 743 | // Where the pieces shown and the reply kept could differ (spaces around the reply; the marker quoted, then the |
| 744 | // real record in a fence), the run puts the kept reply on screen: the two are the same to the letter. |
| 745 | var sameAsKept = false, keptNotes = "could not start a stub server" |
| 746 | let quoted = "It ends with:\nnote hop record\nfn x to ulong\nret 1\nend\nThat is all.\n```\n" + rec + "```\n" |
| 747 | if let a = stub(says: " Paris. \n", reports: nil), let ap = await a.start(), let b = stub(says: quoted, reports: nil), let bp = await b.start() { |
| 748 | var ca = config(); ca.models = [ownModel(ap)] |
| 749 | var cb = config(); cb.models = [ownModel(bp)] |
| 750 | let spaced = await go(Fusion.Ask(text: "hello", force: question), ca) |
| 751 | let fenced = await go(Fusion.Ask(text: "hello", force: question), cb) |
| 752 | a.stop(); b.stop() |
| 753 | sameAsKept = spaced.end.outcome.ok && spaced.lines.reply == "Paris." && spaced.end.reply == "Paris." |
| 754 | && fenced.end.outcome.ok && fenced.lines.reply == FusionRecord.parse(quoted).body && fenced.end.reply == fenced.lines.reply && !fenced.lines.reply.hasSuffix("```") |
| 755 | keptNotes = "โ Paris. โ is shown and kept as โ\(spaced.lines.reply)โ; a quoted marker before a fenced record: shown equals kept \(fenced.end.reply == fenced.lines.reply)" |
| 756 | } |
| 757 | let growing = Shown(), live = LiveText { growing.add($0) } |
| 758 | live.add("One.\nTw") |
| 759 | let early18 = growing.s |
| 760 | live.add("o.\n\nnote hop rec") |
| 761 | let middle = growing.s |
| 762 | live.finish() |
| 763 | report("A reply is shown as it arrives, without its record, however it is cut into pieces; what is on screen at the end is what is kept", |
| 764 | wrong.isEmpty && early18 == "One.\nTw" && middle == "One.\nTwo." && growing.s == "One.\nTwo.\n\nnote hop rec" && sameAsKept, |
| 765 | wrong.isEmpty ? "\(cases.count) replies, each cut six ways, each equal to what the record reader keeps; shown before the reply was over: โ\(early18.replacingOccurrences(of: "\n", with: " / "))โ; \(keptNotes)" : wrong.prefix(3).joined(separator: "; ")) |
| 766 | |
| 767 | // 19. Built-in agents new in this Hop are added to an older settings file once; one the person removed stays |
| 768 | // removed, also in a file from before Hop kept track; a list that is all the person's own is left alone. |
| 769 | func settings(_ name: String, _ json: String) -> HopConfig { let u = dir.appendingPathComponent(name); try? Data(json.utf8).write(to: u); return HopConfig.read(u).config } |
| 770 | let builtins = HopConfig().agentEngines.map(\.name) |
| 771 | let known = String(data: (try? JSONEncoder().encode(builtins)) ?? Data(), encoding: .utf8) ?? "[]" |
| 772 | let grown = settings("older.json", "{\"agentEngines\":[{\"name\":\"Claude Code\",\"command\":[\"claude\",\"-p\",\"{prompt}\"]},{\"name\":\"Mine\",\"command\":[\"mine\",\"{prompt}\"]}]}") |
| 773 | let same = settings("pruned.json", "{\"agentEngines\":[{\"name\":\"Claude Code\",\"command\":[\"claude\",\"-p\",\"{prompt}\"]}],\"knownBuiltins\":\(known)}") |
| 774 | let theirs = settings("theirs.json", "{\"agentEngines\":[{\"name\":\"Mine\",\"command\":[\"mine\",\"{prompt}\"]}]}") |
| 775 | let emptied = settings("emptied.json", "{\"agentEngines\":[],\"agentCommand\":[\"mine\",\"{prompt}\"]}") |
| 776 | let wild = settings("wild.json", "{\"fusionMaxSeats\":40,\"fusionEscalations\":-2}") |
| 777 | let wildNotes = HopConfig.read(dir.appendingPathComponent("wild.json")).notes |
| 778 | report("Agents new in this Hop are added to older settings once; removed ones stay removed", |
| 779 | builtins.contains("Muse") && builtins.contains("Antigravity") |
| 780 | && grown.agentEngines.map(\.name) == ["Claude Code", "Mine", "Antigravity", "Muse"] && grown.agentEngines.first?.command == ["claude", "-p", "{prompt}"] |
| 781 | && grown.builtinsChanged && Set(grown.knownBuiltins) == Set(builtins) |
| 782 | && same.agentEngines.map(\.name) == ["Claude Code"] && !same.builtinsChanged && same.addedEngines.isEmpty |
| 783 | && theirs.agentEngines.map(\.name) == ["Mine"] && emptied.agentEngines.isEmpty |
| 784 | && wild.fusionMaxSeats == 8 && wild.fusionEscalations == 0 && wildNotes.count == 2 && wildNotes.allSatisfy { $0.contains("must be between") }, |
| 785 | "a file from before with Claude Code and one of the person's own: \(grown.agentEngines.map(\.name).joined(separator: ", ")); one that already knew them: \(same.agentEngines.map(\.name).joined(separator: ", ")); only the person's own: \(theirs.agentEngines.map(\.name).joined(separator: ", ")); emptied: \(emptied.agentEngines.count); out-of-range settings: said in \(wildNotes.count) lines") |
| 786 | |
| 787 | // 20. More minds than the chooser plans: the ready ones are taken first, and the ones left out are named in |
| 788 | // the conversation, never dropped in silence. |
| 789 | var c20 = config() |
| 790 | c20.fusionSeats = (1...17).map { seat("Gone \($0)", "echo no", tier: 3, family: "f\($0 % 5)", cost: 5, act: false) } |
| 791 | for i in c20.fusionSeats.indices { c20.fusionSeats[i].command = ["/nonexistent/hop-no-such-tool-\(i)", "{prompt}"] } |
| 792 | c20.fusionSeats.append(seat("Last and working", "echo from the last one", tier: 3, family: "z", cost: 5, act: false)) |
| 793 | let crowd = await go(Fusion.Ask(text: "hello", force: question), c20) |
| 794 | let table20 = await Fusion.table(c20, installed: []) |
| 795 | report("More minds than the chooser plans: the ready ones first, the rest named", |
| 796 | crowd.end.outcome.ok && crowd.end.outcome.by == "Last and working" && table20.seats.count == Fusion.mostSeats && table20.leftOut.count == 2 |
| 797 | && table20.seats.map(\.id) == Array(1...Fusion.mostSeats) && crowd.lines.notes.contains("Not considered for this message: ") && table20.leftOut.allSatisfy { crowd.lines.notes.contains($0) }, |
| 798 | "18 set up, the one that works is last: answered by \(crowd.end.outcome.by); left out and said so: \(table20.leftOut.joined(separator: ", "))") |
| 799 | |
| 800 | // 25. A request is given to one tool. A tool that was given it and failed is never followed by a second tool, |
| 801 | // whatever it printed and whatever its error says: it may have changed a file. That holds for questions too. |
| 802 | // A tool that is signed out says so on the test question before, and has not seen the request. |
| 803 | let step = "printf '{\\\"type\\\":\\\"assistant\\\",\\\"message\\\":{\\\"content\\\":[{\\\"type\\\":\\\"tool_use\\\",\\\"name\\\":\\\"Bash\\\"}]}}\\n'; exit 1" |
| 804 | var c25 = config() |
| 805 | c25.fusionSeats = [seat("Half way", step, tier: 3, family: "a", cost: 1, act: true), seat("Other", "echo ran >> \(Shell.quote(path("m25"))); echo done", tier: 3, family: "b", cost: 5, act: true)] |
| 806 | let half = await go(Fusion.Ask(text: "rename it", force: change), c25) |
| 807 | var c25b = config() |
| 808 | c25b.fusionSeats = [seat("Never began", "echo saw >> \(Shell.quote(path("n25b"))); echo 'status: 401' >&2; exit 1", tier: 3, family: "a", cost: 1, act: true, signedIn: false, known: true), |
| 809 | seat("Other", "echo ran >> \(Shell.quote(path("m25b"))); echo done", tier: 3, family: "b", cost: 5, act: true, known: true)] |
| 810 | let notBegun = await go(Fusion.Ask(text: "rename it", force: change), c25b) |
| 811 | var c25c = config() |
| 812 | c25c.fusionSeats = [seat("Silent", "echo changed >> \(Shell.quote(path("s25"))); exit 1", tier: 3, family: "a", cost: 1, act: true), |
| 813 | seat("Other", "echo changed >> \(Shell.quote(path("s25"))); echo done", tier: 3, family: "b", cost: 5, act: true)] |
| 814 | let silent = await go(Fusion.Ask(text: "what is in it", force: question), c25c) |
| 815 | // It changes a file, then says at once that it is not signed in, has no credit, has no room: none of that is believed. |
| 816 | var claims: [String] = [] |
| 817 | for (n, words) in ["Unauthorized (401): not logged in", "status: 402 insufficient credits", "status: 429 quota exceeded", "insufficient disk space"].enumerated() { |
| 818 | var c = config() |
| 819 | c.fusionSeats = [seat("Claims", "echo changed >> \(Shell.quote(path("l25-\(n)"))); echo '\(words)' >&2; exit 1", tier: 3, family: "a", cost: 1, act: true, known: true), |
| 820 | seat("Other", "echo changed >> \(Shell.quote(path("l25-\(n)"))); echo done", tier: 3, family: "b", cost: 5, act: true, known: true)] |
| 821 | let r = await go(Fusion.Ask(text: "rename it", force: change), c) |
| 822 | if r.end.outcome.ok || read("l25-\(n)").split(separator: "\n").count != 1 || !(r.lines.problems.first ?? "").contains("no other tool was started") { claims.append(words) } |
| 823 | } |
| 824 | // It says "Starting", then reports an error of its own, and ends as if all were well: that is a failure, with its reason. |
| 825 | let errEvents = "printf '{\\\"type\\\":\\\"assistant\\\",\\\"message\\\":{\\\"content\\\":[{\\\"type\\\":\\\"text\\\",\\\"text\\\":\\\"Starting\\\"}]}}\\n{\\\"type\\\":\\\"result\\\",\\\"is_error\\\":true,\\\"result\\\":\\\"permission denied\\\"}\\n'; exit 0" |
| 826 | var c25e = config() |
| 827 | c25e.fusionSeats = [seat("Reports", errEvents, tier: 3, family: "a", cost: 1, act: true), seat("Other", "echo ran >> \(Shell.quote(path("m25e"))); echo done", tier: 3, family: "b", cost: 5, act: true)] |
| 828 | let reports = await go(Fusion.Ask(text: "rename it", force: change), c25e) |
| 829 | // An answer that merely starts like an error is an answer: in a message of the tool's, and as a plain line. |
| 830 | let bang = "printf '{\\\"type\\\":\\\"assistant\\\",\\\"message\\\":{\\\"content\\\":[{\\\"type\\\":\\\"text\\\",\\\"text\\\":\\\"! This is literal answer text.\\\"}]}}\\n{\\\"type\\\":\\\"result\\\",\\\"is_error\\\":false,\\\"result\\\":\\\"ok\\\"}\\n'" |
| 831 | var c25f = config(); c25f.fusionSeats = [seat("Bang", bang, tier: 3, family: "a", cost: 1, act: true)] |
| 832 | var c25g = config(); c25g.fusionSeats = [seat("Plain bang", "echo '! a plain line'; echo 'to the error stream' >&2", tier: 3, family: "a", cost: 1, act: true)] |
| 833 | let bangAnswer = await go(Fusion.Ask(text: "rename it", force: change), c25f), plainBang = await go(Fusion.Ask(text: "rename it", force: change), c25g) |
| 834 | report("Work a tool has begun is not handed to a second tool; a tool that failed before it began is passed over", |
| 835 | !half.end.outcome.ok && read("m25").isEmpty && half.lines.problems.count == 1 && half.lines.problems[0].contains("Half way stopped part way") |
| 836 | && notBegun.end.outcome.ok && notBegun.end.outcome.by == "Other" && read("m25b").split(separator: "\n").count == 1 |
| 837 | && read("n25b").split(separator: "\n").count == 1 && notBegun.lines.notes.contains("Never began is not ready: it is not signed in") |
| 838 | && !silent.end.outcome.ok && read("s25").split(separator: "\n").count == 1 && silent.lines.problems.count == 1 && silent.lines.problems[0].contains("no other tool was started") |
| 839 | && claims.isEmpty |
| 840 | && !reports.end.outcome.ok && reports.end.failed["Reports"] == "permission denied" && read("m25e").isEmpty && reports.lines.problems.contains { $0.contains("permission denied") } |
| 841 | && bangAnswer.end.outcome.ok && bangAnswer.lines.reply == "! This is literal answer text." && plainBang.end.outcome.ok && plainBang.lines.reply == "! a plain line", |
| 842 | "\(half.lines.notes) || \(notBegun.lines.notes) || changed a file, printed nothing, failed: \(silent.lines.notes); the file was changed \(read("s25").split(separator: "\n").count) time || changed a file and then claimed a refusal, followed by a second tool all the same: \(claims.isEmpty ? "never" : claims.joined(separator: ", ")) || a tool that reports an error of its own and ends well: \(reports.lines.problems.last ?? "taken as an answer") || answers that only start like an error: โ\(bangAnswer.lines.reply)โ, โ\(plainBang.lines.reply)โ") |
| 843 | |
| 844 | // The rows below go through `Pick`, as the Agent screen does: what lasts from one message to the next. |
| 845 | var pc = config(); pc.models = [ownModel(wp)]; pc.agentConfirmed = true; pc.agentConsentVersion = HopConfig.currentAgentConsentVersion |
| 846 | pc.agentEngines = [tool("Waits", "echo $$ > \(Shell.quote(path("p21"))); sleep 30", tier: 4, family: "a", cost: 1), |
| 847 | tool("Teller", "echo \"$2 $3\" >> \(Shell.quote(path("a21"))); printf \"\(stream)\"", tier: 4, family: "b", cost: 2)] |
| 848 | let host = Host(pc), kept = Kept() |
| 849 | let pick = Pick(host: host, memory: kept.memory) |
| 850 | var clock = Date() |
| 851 | pick.now = { clock } |
| 852 | |
| 853 | // 21. Stop, then send at once: the new message is answered; a second message while one is being worked on is |
| 854 | // told so, never dropped in silence; nothing arrives after the outcome. |
| 855 | let lines21 = Lines() |
| 856 | var firstOutcome: PickOutcome?, lateLines = 0 |
| 857 | pick.start("rename the file", history: [], stronger: false, say: { lines21.add($0); if firstOutcome != nil { lateLines += 1 } }, done: { firstOutcome = $0 }) |
| 858 | var w21 = 0 |
| 859 | while read("p21").isEmpty, w21 < 100 { try? await Task.sleep(nanoseconds: 100_000_000); w21 += 1 } |
| 860 | let second = await send(pick, "another one") // while the first is at work |
| 861 | pick.stop() |
| 862 | let next = await send(pick, "hello after stop") // at once, before the stopped run has wound down |
| 863 | var w21b = 0 |
| 864 | while firstOutcome == nil, w21b < 100 { try? await Task.sleep(nanoseconds: 100_000_000); w21b += 1 } |
| 865 | try? await Task.sleep(nanoseconds: 300_000_000) |
| 866 | report("Stop and send at once: the new message is answered; a message sent while one is at work is told so", |
| 867 | !second.outcome.ok && second.lines.problems.count == 1 && second.lines.problems[0].contains("still working") |
| 868 | && next.outcome.ok && next.outcome.by == own && next.lines.reply == "ready" |
| 869 | && firstOutcome?.ok == false && lines21.problems == ["Stopped."] && lateLines == 0 && !pick.running && !alive(pid("p21")), |
| 870 | "while at work: โ\(second.lines.problems.first ?? "")โ; after stop: answered by \(next.outcome.by); the stopped run ended with \(lines21.problems); lines after its outcome: \(lateLines)") |
| 871 | |
| 872 | // 22. The same message again is answered from memory (nobody asked, no tokens), Stronger still works on it, |
| 873 | // tokens of real answers are counted where they went, and what a tool answered is never kept. |
| 874 | let n22 = well.requests.filter { $0.hasPrefix("POST ") }.count |
| 875 | let repeated = await send(pick, "hello after stop") |
| 876 | let posts22 = well.requests.filter { $0.hasPrefix("POST ") }.count - n22 |
| 877 | host.config.agentEngines = [tool("Teller", "echo \"$2 $3\" >> \(Shell.quote(path("a21"))); echo x >> \(Shell.quote(path("m22"))); printf \"\(stream)\"", tier: 4, family: "b", cost: 2)] |
| 878 | host.config.agentConfirmed = false; host.asked = []; host.saved = 0 // from here on the yes is not given yet |
| 879 | host.yes = false |
| 880 | let refused = await send(pick, "hello after stop", stronger: true) |
| 881 | let stillNo = !host.config.agentConfirmed && host.saved == 0 |
| 882 | host.yes = true |
| 883 | let stronger22 = await send(pick, "hello after stop", stronger: true) |
| 884 | let askedYes = host.asked.count |
| 885 | let work1 = await send(pick, "rename the file to b") |
| 886 | let work2 = await send(pick, "rename the file to b") |
| 887 | report("A repeated message is answered from memory; Stronger works on it; a tool's answer is never kept; the yes is asked once", |
| 888 | repeated.outcome.ok && repeated.outcome.by == "memory" && repeated.lines.reply == "ready" && posts22 == 0 && kept.hits == 1 && repeated.outcome.strongerLeft |
| 889 | && (kept.spent[.thisMac] ?? 0) > 0 |
| 890 | && !refused.outcome.ok && refused.outcome.declined && stillNo |
| 891 | && stronger22.outcome.ok && stronger22.outcome.by == "Teller" && stronger22.outcome.acted && host.config.agentConfirmed && host.saved == 1 |
| 892 | && work1.outcome.ok && work2.outcome.ok && work2.outcome.by == "Teller" && read("m22").split(separator: "\n").count == 3 && host.asked.count == askedYes && askedYes == 2 |
| 893 | && host.learned.count == 3 && (kept.spent[.online] ?? 0) == 36, |
| 894 | "again: \(repeated.outcome.meta), server asked \(posts22) times; Stronger on it: \(stronger22.outcome.by); the tool ran \(read("m22").split(separator: "\n").count) times for three tool answers; the yes was asked \(host.asked.count) times (one no, one yes) and saved \(host.saved) time; tokens counted: \(kept.spent[.thisMac] ?? 0) on this Mac, \(kept.spent[.online] ?? 0) online; from memory \(kept.hits) time(s), Stronger offered on it: \(repeated.outcome.strongerLeft); the no: ok \(refused.outcome.ok) declined \(refused.outcome.declined); tool results kept for Cortex: \(host.learned.count); the two tool requests: \(work1.outcome.by), \(work2.outcome.by)") |
| 895 | |
| 896 | // 23. A tool's own session is carried on by the next message to the same tool, not after 15 minutes, and not |
| 897 | // after a new conversation. |
| 898 | func lastArgs() -> String { read("a21").split(separator: "\n").last.map { $0.trimmingCharacters(in: .whitespaces) } ?? "" } |
| 899 | let carried = lastArgs() // work2 followed work1 at the same tool |
| 900 | clock = clock.addingTimeInterval(Pick.sessionFor + 1) |
| 901 | _ = await send(pick, "rename the file to c") |
| 902 | let expired = lastArgs() |
| 903 | _ = await send(pick, "rename the file to d") |
| 904 | let carriedAgain = lastArgs() |
| 905 | pick.forget() |
| 906 | _ = await send(pick, "rename the file to e") |
| 907 | let forgotten = lastArgs() |
| 908 | report("A tool's session is carried on by the next message, not after 15 minutes and not into a new conversation", |
| 909 | carried == "--resume sess-1" && expired.isEmpty && carriedAgain == "--resume sess-1" && forgotten.isEmpty, |
| 910 | "next message: โ\(carried)โ; after \(Int(Pick.sessionFor / 60)) minutes: โ\(expired)โ; then again: โ\(carriedAgain)โ; after a new conversation: โ\(forgotten)โ") |
| 911 | |
| 912 | // 24. A mind that failed rests for ten minutes and is asked again after that. |
| 913 | host.config.agentEngines = [tool("Flaky", "echo x >> \(Shell.quote(path("m24"))); echo 'status: 402 payment required' >&2; exit 1", tier: 3, family: "c", cost: 1, signedIn: false, known: true), |
| 914 | tool("Steady", "echo done by steady", tier: 4, family: "d", cost: 50, known: true)] |
| 915 | let f1 = await send(pick, "rename the file to f") |
| 916 | let restingAfter = pick.restingNow, provenAfter = pick.provenNow |
| 917 | let f2 = await send(pick, "rename the file to g") |
| 918 | let askedWhileResting = read("m24").split(separator: "\n").count |
| 919 | clock = clock.addingTimeInterval(Pick.restFor + 1) |
| 920 | let f3 = await send(pick, "rename the file to h") |
| 921 | report("A mind that failed rests for ten minutes, then is asked again; one that showed it is ready is not asked the test question for as long", |
| 922 | f1.outcome.ok && f1.outcome.by == "Steady" && restingAfter == ["Flaky": "its account has no credit left"] && provenAfter.contains("Steady") && !provenAfter.contains("Flaky") |
| 923 | && f1.lines.notes.contains("checking that Steady is ready") |
| 924 | && f2.outcome.ok && askedWhileResting == 1 && !f2.lines.notes.contains("Flaky is not") && !f2.lines.notes.contains("checking") // Steady is known to be ready: not asked the test question again |
| 925 | && f3.outcome.ok && read("m24").split(separator: "\n").count == 2 && f3.lines.notes.contains("Flaky is not ready: its account has no credit left") |
| 926 | && f3.lines.notes.contains("checking that Steady is ready"), |
| 927 | "first: \(f1.lines.notes); asked \(askedWhileResting) time while resting; after \(Int(Pick.restFor / 60)) minutes asked again: \(read("m24").split(separator: "\n").count) times in all") |
| 928 | |
| 929 | // 26. A tool that sends its reply in small pieces (Claude Code's partial messages, as Hop's own chat-only Claude |
| 930 | // seat asks for them): the pieces are shown as they come, the whole message after them is not shown a second |
| 931 | // time, and the tokens and the model it reports are under the answer. |
| 932 | func event(_ json: String) -> String { json.replacingOccurrences(of: "\"", with: "\\\"") + "\\n" } |
| 933 | func delta(_ t: String) -> String { event("{\"type\":\"stream_event\",\"event\":{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"\(t)\"}}}") } |
| 934 | let opening = event("{\"type\":\"system\",\"subtype\":\"init\",\"model\":\"claude-test-model-2\",\"session_id\":\"sess-2\"}") |
| 935 | + event("{\"type\":\"stream_event\",\"event\":{\"type\":\"message_start\",\"message\":{\"role\":\"assistant\"}}}") |
| 936 | let closing = event("{\"type\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"Paris, on the Seine.\"}]}}") |
| 937 | + event("{\"type\":\"result\",\"is_error\":false,\"result\":\"Paris, on the Seine.\",\"session_id\":\"sess-2\",\"usage\":{\"input_tokens\":11,\"output_tokens\":4}}") |
| 938 | var c26 = config() |
| 939 | c26.fusionSeats = [seat("Pieces", "printf \"\(opening)\(delta("Paris,"))\"; sleep 2; printf \"\(delta(" on the "))\(delta("Seine."))\(closing)\"", tier: 3, family: "a", cost: 1, act: false)] |
| 940 | final class Seen: @unchecked Sendable { |
| 941 | let l = NSLock(); var first: Date?, firstText = "" |
| 942 | func note(_ line: PickLine) { l.lock(); if first == nil, case .answer(let p) = line { first = Date(); firstText = p }; l.unlock() } |
| 943 | } |
| 944 | let seen = Seen(), lines26 = Lines() |
| 945 | let end26 = await Fusion.run(Fusion.Ask(text: "hello", force: question), cfg: c26, installed: [], mayAct: { _ in true }) { seen.note($0); lines26.add($0) } |
| 946 | let early26 = seen.first.map { Date().timeIntervalSince($0) } ?? 0 |
| 947 | report("A reply that comes in small pieces from a tool is shown as it comes, once, with the tokens and the model it reports", |
| 948 | end26.outcome.ok && lines26.reply == "Paris, on the Seine." && end26.reply == "Paris, on the Seine." && seen.firstText == "Paris," && early26 > 1 |
| 949 | && lines26.list.filter { $0 == .restart }.isEmpty && end26.outcome.meta.contains("15 tokens") && end26.outcome.meta.contains("claude-test-model-2"), |
| 950 | "first piece โ\(seen.firstText)โ on screen \(String(format: "%.1f", early26)) s before the tool ended; shown: โ\(lines26.reply)โ; under it: \(end26.outcome.meta)") |
| 951 | |
| 952 | // 27. After a Stop that ended a working tool, the next message starts no command while that tool or anything it |
| 953 | // started is still running: a child that ignores the request to end is not at work beside the next tool. |
| 954 | // It is waited for, not timed: after a tool that ends when asked, the next one starts at once. |
| 955 | var qc = config(); qc.agentConfirmed = true; qc.agentConsentVersion = HopConfig.currentAgentConsentVersion |
| 956 | qc.agentEngines = [tool("Hangs", "(trap '' TERM; sleep 60) & echo $! > \(Shell.quote(path("c27"))); echo $$ > \(Shell.quote(path("p27"))); wait", tier: 4, family: "a", cost: 1)] |
| 957 | let host27 = Host(qc), kept27 = Kept(), pick27 = Pick(host: host27, memory: kept27.memory) |
| 958 | func stopWhenStarted(_ mark: String) async { |
| 959 | pick27.start("rename the file", history: [], stronger: false, say: { _ in }, done: { _ in }) |
| 960 | var w = 0 |
| 961 | while read(mark).isEmpty, w < 150 { try? await Task.sleep(nanoseconds: 100_000_000); w += 1 } |
| 962 | pick27.stop() |
| 963 | } |
| 964 | // The next tool looks for the stopped tool's child the moment it is started, on the test question too. |
| 965 | func follower(_ name: String, child: String, beside: String) -> AgentEngine { |
| 966 | tool(name, "if kill -0 $(cat \(Shell.quote(path(child)))) 2>/dev/null; then echo beside >> \(Shell.quote(path(beside))); fi; case \"$1\" in *'exactly one word: ready'*) echo ready;; *) echo done by \(name);; esac", |
| 967 | tier: 4, family: "b", cost: 1, signedIn: false, known: true) |
| 968 | } |
| 969 | await stopWhenStarted("p27") |
| 970 | let stoppedAt = Date() |
| 971 | host27.config.agentEngines = [follower("Next", child: "c27", beside: "o27")] |
| 972 | let after27 = await send(pick27, "rename the file to z") |
| 973 | let waited27 = Date().timeIntervalSince(stoppedAt) |
| 974 | host27.config.agentEngines = [tool("Ends", "sleep 60 & echo $! > \(Shell.quote(path("c27b"))); echo $$ > \(Shell.quote(path("p27b"))); wait", tier: 4, family: "c", cost: 1)] |
| 975 | pick27.forget() |
| 976 | await stopWhenStarted("p27b") |
| 977 | let stoppedAgain = Date() |
| 978 | host27.config.agentEngines = [follower("Soon", child: "c27b", beside: "o27b")] |
| 979 | let soon27 = await send(pick27, "rename the file to y") |
| 980 | let waitedAgain = Date().timeIntervalSince(stoppedAgain) |
| 981 | report("After a Stop that ended a working tool, no command starts until the stopped tool and its children are gone", |
| 982 | after27.outcome.ok && after27.outcome.by == "Next" && read("o27").isEmpty && !alive(pid("c27")) |
| 983 | && waited27 >= CommandRun.graceToEnd - 0.5 && after27.lines.notes.contains("Waiting for the tool that was stopped") && after27.lines.notes.contains("checking that Next is ready") |
| 984 | && soon27.outcome.ok && soon27.outcome.by == "Soon" && read("o27b").isEmpty && !alive(pid("c27b")) && waitedAgain < CommandRun.graceToEnd - 1, |
| 985 | "a stopped tool whose child ignores the request to end: the next tool started \(String(format: "%.1f", waited27)) s after the stop, the child still at work beside it: \(!read("o27").isEmpty); said: \(after27.lines.notes) || a stopped tool that ends when asked: the next tool answered \(String(format: "%.1f", waitedAgain)) s after the stop") |
| 986 | |
| 987 | // 28. A stronger try that gives no answer: the earlier answer comes back right after the request and the half |
| 988 | // answer the try left behind is dropped, so the next mind is told the earlier answer alone. A try that |
| 989 | // answers keeps its own answer. |
| 990 | let asked28 = ChatMessage(role: "user", text: "what is it?"), good = ChatMessage(role: "assistant", text: "GOOD-ANSWER") |
| 991 | let half28 = ChatMessage(role: "assistant", text: "half of a stron"), stopNote = ChatMessage(role: "note", text: "Stopped.") |
| 992 | var log28 = [asked28, half28, stopNote] |
| 993 | let back28 = AppModel.restore(&log28, aside: [good], halfReply: half28.id, ok: false) |
| 994 | var kept28 = [asked28, ChatMessage(role: "assistant", text: "STRONGER-ANSWER")] |
| 995 | let notBack = AppModel.restore(&kept28, aside: [good], halfReply: kept28[1].id, ok: true) |
| 996 | report("A stronger try that gives no answer leaves the earlier answer, and no half answer, for the next mind", |
| 997 | back28 && AppModel.history(log28).map(\.text) == ["what is it?", "GOOD-ANSWER"] && log28.map(\.role) == ["user", "assistant", "note"] |
| 998 | && !notBack && AppModel.history(kept28).map(\.text) == ["what is it?", "STRONGER-ANSWER"], |
| 999 | "after a failed try the next mind is told: \(AppModel.history(log28).map(\.text).joined(separator: " / ")); after one that answered: \(AppModel.history(kept28).map(\.text).joined(separator: " / "))") |
| 1000 | |
| 1001 | // 29. Two requests at once to a model server that refuses the usage option: each is sent again without it, and |
| 1002 | // both are answered. What one request found out does not stop the other from trying again. |
| 1003 | var bothAnswered = false, posts29 = 0 |
| 1004 | let gate = Gate() |
| 1005 | if let picky = stub(says: "fine", reports: nil, gate: gate), let pp = await picky.start() { |
| 1006 | let ep = ownModel(pp), msg = [ChatMessage(role: "user", text: "hello")] |
| 1007 | async let one = try? ModelClient.streamReply(ep, history: msg) { _ in } |
| 1008 | async let two = try? ModelClient.streamReply(ep, history: msg) { _ in } |
| 1009 | let (r1, r2) = await (one, two) |
| 1010 | posts29 = picky.requests.filter { $0.hasPrefix("POST ") }.count |
| 1011 | picky.stop() |
| 1012 | let asked = picky.bodies.filter { $0.contains("\"messages\"") } |
| 1013 | bothAnswered = r1 != nil && r2 != nil && asked.count == 4 && asked.prefix(2).allSatisfy { $0.contains("stream_options") } && asked.suffix(2).allSatisfy { !$0.contains("stream_options") } |
| 1014 | } |
| 1015 | report("Two requests at once to a server that refuses the usage option are both sent again without it and answered", |
| 1016 | bothAnswered && posts29 == 4, "both answered, the first two requests with the option and the next two without: \(bothAnswered); requests the server got: \(posts29)") |
| 1017 | |
| 1018 | // 30. A tool that does not answer the test question in time is ended with everything it started, and the next |
| 1019 | // tool is asked only when that is gone; and a tool that said the word but had to be ended is not ready. |
| 1020 | func asksFor(_ child: String, beside: String, _ reply: String) -> String { |
| 1021 | "if kill -0 $(cat \(Shell.quote(path(child))) 2>/dev/null) 2>/dev/null; then echo beside >> \(Shell.quote(path(beside))); fi; case \"$1\" in *'exactly one word: ready'*) echo ready;; *) echo \(reply);; esac" |
| 1022 | } |
| 1023 | var c30 = config() |
| 1024 | c30.fusionSeats = [seat("Hangs", "(trap '' TERM; sleep 60) & echo $! > \(Shell.quote(path("c30"))); sleep 60", tier: 3, family: "a", cost: 1, act: false, signedIn: false, known: true), |
| 1025 | seat("After", asksFor("c30", beside: "o30", "from the one after"), tier: 3, family: "b", cost: 5, act: false, signedIn: false, known: true)] |
| 1026 | var ask30 = Fusion.Ask(text: "hello", force: question) |
| 1027 | ask30.probeTime = 2 |
| 1028 | let t30 = Date() |
| 1029 | let slow = await go(ask30, c30) |
| 1030 | let took30 = Date().timeIntervalSince(t30) |
| 1031 | var c30b = config() |
| 1032 | c30b.fusionSeats = [seat("Too late", "case \"$1\" in *'exactly one word: ready'*) trap 'exit 0' TERM; echo ready; sleep 60 & wait;; *) echo ran >> \(Shell.quote(path("m30b"))); echo from too late;; esac", tier: 3, family: "a", cost: 1, act: false, signedIn: false, known: true), |
| 1033 | seat("After", "echo from the one after", tier: 3, family: "b", cost: 5, act: false, known: true)] |
| 1034 | let late = await go(ask30, c30b) |
| 1035 | report("A tool that does not answer the test question in time is ended with what it started before the next is asked, and is not taken as ready", |
| 1036 | slow.end.outcome.ok && slow.end.outcome.by == "After" && slow.end.failed["Hangs"] == "it ran out of time" && read("o30").isEmpty && !alive(pid("c30")) && took30 >= CommandRun.graceToEnd |
| 1037 | && late.end.outcome.ok && late.end.outcome.by == "After" && late.end.failed["Too late"] == "it ran out of time" && read("m30b").isEmpty, |
| 1038 | "a tool that hangs on the test question, with a child that ignores the request to end: \(slow.lines.notes); the next tool found that child still at work: \(!read("o30").isEmpty); all of it took \(String(format: "%.1f", took30)) s || a tool that says the word, hangs and ends well when stopped: \(late.lines.notes)") |
| 1039 | report("Legacy per-tool consent is re-asked before automatic routing and current consent survives restart", |
| 1040 | await consentUpgradeCheck(), "decline starts no command; a fresh yes is saved once; missing/future consent versions are refused") |
| 1041 | } |
| 1042 | |
| 1043 | /// The old per-engine yes is not permission for the new automatic tool chooser. |
| 1044 | static func consentUpgradeCheck() async -> Bool { |
| 1045 | let directory = FileManager.default.temporaryDirectory.appendingPathComponent("hop-consent-\(UUID().uuidString)") |
| 1046 | do { try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) } |
| 1047 | catch { return false } |
| 1048 | defer { try? FileManager.default.removeItem(at: directory) } |
| 1049 | do { |
| 1050 | var legacy = try JSONDecoder().decode(HopConfig.self, from: Data("{\"agentConfirmed\":true}".utf8)) |
| 1051 | let future = try JSONDecoder().decode(HopConfig.self, from: Data("{\"agentConfirmed\":true,\"agentConsentVersion\":999}".utf8)) |
| 1052 | guard !legacy.agentToolsAllowed, !legacy.agentConfirmed, !future.agentToolsAllowed else { return false } |
| 1053 | legacy.models = []; legacy.fusionSeats = []; legacy.agentCommand = [] |
| 1054 | legacy.cortex.enabled = false; legacy.agentWorkingDirectory = directory.path |
| 1055 | let marker = directory.appendingPathComponent("ran") |
| 1056 | legacy.agentEngines = [tool("Upgrade test tool", "echo ran >> \(Shell.quote(marker.path)); echo completed", tier: 4, family: "test", cost: 1)] |
| 1057 | let host = Host(legacy), memory = Kept(), pick = Pick(host: host, memory: memory.memory) |
| 1058 | host.yes = false |
| 1059 | let denied = await send(pick, "rename the file") |
| 1060 | guard denied.outcome.declined, host.asked.count == 1, host.saved == 0, |
| 1061 | !FileManager.default.fileExists(atPath: marker.path), !host.config.agentToolsAllowed else { return false } |
| 1062 | host.yes = true |
| 1063 | let accepted = await send(pick, "rename the file") |
| 1064 | let restored = try JSONDecoder().decode(HopConfig.self, from: JSONEncoder().encode(host.config)) |
| 1065 | let again = await send(pick, "rename the other file") |
| 1066 | return accepted.outcome.ok && again.outcome.ok && host.asked.count == 2 && host.saved == 1 |
| 1067 | && host.config.agentToolsAllowed && restored.agentToolsAllowed |
| 1068 | && host.config.agentConsentVersion == HopConfig.currentAgentConsentVersion |
| 1069 | && FileManager.default.fileExists(atPath: marker.path) |
| 1070 | } catch { return false } |
| 1071 | } |
| 1072 | |
| 1073 | /// `Hop --selftest-pick`: these rows alone (used by tools/check-pick.sh for the changed copies). |
| 1074 | static func runAlone() async -> Int32 { |
| 1075 | var failures = 0, passes = 0 |
| 1076 | await run { name, ok, detail in |
| 1077 | print("\(ok ? "PASS" : "FAIL") \(name): \(detail)") |
| 1078 | if ok { passes += 1 } else { failures += 1 } |
| 1079 | } |
| 1080 | print(failures == 0 ? "PICK PASS \(passes)" : "PICK FAIL \(failures) of \(passes + failures)") |
| 1081 | return failures == 0 ? 0 : 1 |
| 1082 | } |
| 1083 | } |