@hivey/cli 0.0.0-stage → 0.9.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +235 -2
  2. package/bin/hivey.js +98 -0
  3. package/native/darwin-arm64/hivey +0 -0
  4. package/package.json +36 -4
  5. package/platforms.json +3 -0
  6. package/repo/LICENSE +201 -0
  7. package/repo/NOTICE +18 -0
  8. package/repo/README.md +148 -0
  9. package/repo/install.sh +365 -0
  10. package/repo/pets/README.md +25 -0
  11. package/repo/pets/hivey-dot/CLAUDE.md +55 -0
  12. package/repo/pets/hivey-dot/build.sh +34 -0
  13. package/repo/pets/hivey-dot/main.swift +750 -0
  14. package/repo/pets/hivey-h/CLAUDE.md +75 -0
  15. package/repo/pets/hivey-h/build.sh +34 -0
  16. package/repo/pets/hivey-h/main.swift +739 -0
  17. package/repo/pets/hivey-prompt/CLAUDE.md +59 -0
  18. package/repo/pets/hivey-prompt/build.sh +34 -0
  19. package/repo/pets/hivey-prompt/main.swift +691 -0
  20. package/repo/pets/pet.py +288 -0
  21. package/repo/pets/shared/HiveyWatch.swift +437 -0
  22. package/repo/pets/test_pet.py +122 -0
  23. package/repo/plugins/README.md +108 -0
  24. package/repo/plugins/agent-creator/herdr-plugin.toml +17 -0
  25. package/repo/plugins/dashboard/dashboard.py +507 -0
  26. package/repo/plugins/dashboard/herdr-plugin.toml +14 -0
  27. package/repo/plugins/dashboard/test_dashboard.py +134 -0
  28. package/repo/plugins/github/github.py +261 -0
  29. package/repo/plugins/github/herdr-plugin.toml +14 -0
  30. package/repo/plugins/github/test_github.py +49 -0
  31. package/repo/plugins/skills/herdr-plugin.toml +11 -0
  32. package/repo/plugins/skills/skills.md +41 -0
  33. package/repo/plugins/slack-relay/connect.py +198 -0
  34. package/repo/plugins/slack-relay/create_channel.py +134 -0
  35. package/repo/plugins/slack-relay/herdr-plugin.toml +15 -0
  36. package/repo/plugins/slack-relay/relay.py +401 -0
  37. package/repo/plugins/slack-relay/slack-app-manifest.json +30 -0
  38. package/repo/plugins/slack-relay/test_connect.py +66 -0
  39. package/repo/plugins/slack-relay/test_create_channel.py +61 -0
  40. package/repo/plugins/slack-relay/test_relay.py +254 -0
  41. package/repo/plugins/swarm-creator/herdr-plugin.toml +17 -0
  42. package/repo/plugins/swarm-watcher/dashboard.py +333 -0
  43. package/repo/plugins/swarm-watcher/herdr-plugin.toml +16 -0
  44. package/repo/plugins/swarm-watcher/usage.py +129 -0
  45. package/repo/plugins/swarm-watcher/watcher.py +191 -0
  46. package/repo/plugins/team-template/herdr-plugin.toml +15 -0
  47. package/repo/plugins/team-template/setup.py +211 -0
  48. package/repo/plugins/team-template/test_setup.py +73 -0
  49. package/repo/plugins/tts/herdr-plugin.toml +15 -0
  50. package/repo/skills/herdr/SKILL.md +214 -0
  51. package/repo/skills/hivey/SKILL.md +322 -0
  52. package/repo/skills/hivey/scripts/handoff.py +27 -0
  53. package/repo/skills/hivey/scripts/new_wiki.py +143 -0
  54. package/repo/skills/hivey-agent-creator/SKILL.md +303 -0
  55. package/repo/skills/hivey-agent-creator/references/agent-claude-md.md +256 -0
  56. package/repo/skills/hivey-agent-creator/references/global-guidelines.md +67 -0
  57. package/repo/skills/hivey-agent-creator/references/reviewer-agent.md +35 -0
  58. package/repo/skills/hivey-agent-creator/scripts/agent_context.py +76 -0
  59. package/repo/skills/hivey-agent-creator/scripts/agent_gate.py +78 -0
  60. package/repo/skills/hivey-agent-creator/scripts/setup_agent.py +288 -0
  61. package/repo/skills/hivey-agy/SKILL.md +123 -0
  62. package/repo/skills/hivey-agy/references/gemini-prompting.md +134 -0
  63. package/repo/skills/hivey-agy/scripts/agy_run.py +146 -0
  64. package/repo/skills/hivey-codex/SKILL.md +66 -0
  65. package/repo/skills/hivey-context7/SKILL.md +56 -0
  66. package/repo/skills/hivey-create-wiki/SKILL.md +329 -0
  67. package/repo/skills/hivey-grok/SKILL.md +101 -0
  68. package/repo/skills/hivey-grok/scripts/grok_run.py +139 -0
  69. package/repo/skills/hivey-swarm-creator/SKILL.md +384 -0
  70. package/repo/skills/hivey-swarm-creator/references/agent-claude-md.md +313 -0
  71. package/repo/skills/hivey-swarm-creator/references/archify-report.md +24 -0
  72. package/repo/skills/hivey-swarm-creator/references/dashboard.md +46 -0
  73. package/repo/skills/hivey-swarm-creator/references/retrospective.md +23 -0
  74. package/repo/skills/hivey-swarm-creator/references/shared-rules.md +39 -0
  75. package/repo/skills/hivey-swarm-creator/references/wiki-memory.md +30 -0
  76. package/repo/skills/hivey-swarm-creator/scripts/setup_agent.py +76 -0
  77. package/repo/skills/hivey-swarm-creator/scripts/shared_rules.py +50 -0
  78. package/repo/skills/hivey-swarm-creator/scripts/swarm_tasks.py +171 -0
  79. package/repo/skills/hivey-wiki-ingest/SKILL.md +45 -0
  80. package/repo/skills/hivey-wiki-lint/SKILL.md +38 -0
  81. package/repo/skills/hivey-wiki-list/SKILL.md +46 -0
  82. package/repo/skills/hivey-wiki-log/SKILL.md +45 -0
  83. package/repo/skills/hivey-wiki-query/SKILL.md +44 -0
@@ -0,0 +1,437 @@
1
+ // Shared by every hivey pet (compiled next to its main.swift by build.sh): the hivey watcher,
2
+ // which turns one look at hivey into events each pet acts out with its own moves, and the
3
+ // pet switcher behind the "Switch pet" menu.
4
+
5
+ import AppKit
6
+
7
+
8
+ /// What the pet should act out after one look at hivey
9
+ enum HiveyEvent: Equatable {
10
+ case launched(String) // a new swarm or agent → assign
11
+ case needsYou([String]) // agents waiting for the user → listen + say
12
+ case finished(String) // an agent went from working to idle/done → complete
13
+ case message(fromHuman: Bool, replyFrom: String?, text: String) // replyFrom: an agent writing to the user
14
+ }
15
+
16
+ /// One look at hivey: every agent's status ("slug/key" → status) and every swarm
17
+ struct HiveySnapshot {
18
+ var swarms: Set<String> = []
19
+ var status: [String: String] = [:]
20
+ var names: [String: String] = [:] // "slug/key" → how the pet calls it
21
+
22
+ init(swarmList: [String: Any]) {
23
+ for swarm in swarmList["swarms"] as? [[String: Any]] ?? [] {
24
+ guard let slug = swarm["slug"] as? String else { continue }
25
+ swarms.insert(slug)
26
+ let solo = swarm["solo"] as? Bool ?? false
27
+ for agent in swarm["agents"] as? [[String: Any]] ?? [] {
28
+ guard let key = agent["key"] as? String, agent["role"] as? String != "script" else { continue }
29
+ let id = "\(slug)/\(key)"
30
+ status[id] = agent["status"] as? String ?? "gone"
31
+ names[id] = solo ? slug : "\(slug) \(key)"
32
+ }
33
+ }
34
+ }
35
+
36
+ var working: Int { status.values.filter { $0 == "working" }.count }
37
+ var idle: Int { status.values.filter { ["idle", "done", "blocked"].contains($0) }.count }
38
+
39
+ /// Changes since `old` worth a reaction; nothing on the first look
40
+ func events(since old: HiveySnapshot?) -> [HiveyEvent] {
41
+ guard let old else { return [] }
42
+ var events: [HiveyEvent] = swarms.subtracting(old.swarms).sorted().map { .launched($0) }
43
+ var waiting: [String] = []
44
+ for (id, now) in status.sorted(by: { $0.key < $1.key }) {
45
+ let before = old.status[id]
46
+ if now == "blocked" && before != "blocked" { waiting.append(names[id] ?? id) }
47
+ if before == "working" && (now == "idle" || now == "done") { events.append(.finished(names[id] ?? id)) }
48
+ }
49
+ if !waiting.isEmpty { events.append(.needsYou(waiting)) }
50
+ return events
51
+ }
52
+ }
53
+
54
+ /// Watches the default hivey session by polling its CLI every 2s (off the main thread).
55
+ /// No hivey, or no hivey server running: it waits quietly and never starts one.
56
+ final class HiveyWatcher {
57
+ var onUpdate: ((HiveySnapshot, [HiveyEvent]) -> Void)?
58
+ /// The last hivey window on this computer closed (after one had been open): the pet goes
59
+ /// too, and comes back when a window opens (`hivey pet show`).
60
+ var onLastWindowClosed: (() -> Void)?
61
+ private var sawWindow = false
62
+ private var emptyLooks = 0
63
+ private(set) var hiveyPath: String?
64
+ private var last: HiveySnapshot?
65
+ private var lastMessageTs: Double?
66
+ private let queue = DispatchQueue(label: "com.hivey.h.watch")
67
+ private var timer: DispatchSourceTimer?
68
+ private let vars = ProcessInfo.processInfo.environment
69
+ private var debug: Bool { vars["HIVEY_H_DEBUG"] != nil }
70
+
71
+ func findHivey() -> String? {
72
+ var candidates = [vars["HIVEY_BIN"], NSHomeDirectory() + "/.local/bin/hivey",
73
+ "/opt/homebrew/bin/hivey", "/usr/local/bin/hivey"].compactMap { $0 }
74
+ candidates += (vars["PATH"] ?? "").split(separator: ":").map { "\($0)/hivey" }
75
+ return candidates.first { FileManager.default.isExecutableFile(atPath: $0) }
76
+ }
77
+
78
+ func start() {
79
+ stop()
80
+ let t = DispatchSource.makeTimerSource(queue: queue)
81
+ t.schedule(deadline: .now() + 1, repeating: 2)
82
+ t.setEventHandler { [weak self] in self?.poll() }
83
+ t.resume()
84
+ timer = t
85
+ }
86
+
87
+ func stop() {
88
+ timer?.cancel()
89
+ timer = nil
90
+ queue.async { [weak self] in
91
+ self?.last = nil
92
+ self?.lastMessageTs = nil
93
+ }
94
+ }
95
+
96
+ private func run(_ args: [String]) -> [String: Any]? {
97
+ guard let hiveyPath else { return nil }
98
+ let p = Process()
99
+ p.executableURL = URL(fileURLWithPath: hiveyPath)
100
+ p.arguments = args
101
+ p.currentDirectoryURL = URL(fileURLWithPath: "/")
102
+ // Not a pane of any swarm: hivey answers for all swarms of the default session
103
+ p.environment = vars.filter { !$0.key.hasPrefix("HERDR_") && !$0.key.hasPrefix("HIVEY_") }
104
+ let out = Pipe()
105
+ p.standardOutput = out
106
+ p.standardError = FileHandle.nullDevice
107
+ do { try p.run() } catch { return nil }
108
+ let data = out.fileHandleForReading.readDataToEndOfFile()
109
+ p.waitUntilExit()
110
+ guard p.terminationStatus == 0 else { return nil }
111
+ return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
112
+ }
113
+
114
+ /// hivey windows open on this computer: `~/.hivey/windows/<pid>` of a live process (a
115
+ /// window that crashed leaves its file behind; it's removed here)
116
+ static func openWindows() -> Int {
117
+ let dir = NSHomeDirectory() + "/.hivey/windows"
118
+ guard let names = try? FileManager.default.contentsOfDirectory(atPath: dir) else { return 0 }
119
+ var open = 0
120
+ for name in names {
121
+ guard let pid = Int32(name) else { continue }
122
+ if kill(pid, 0) == 0 || errno == EPERM {
123
+ open += 1
124
+ } else {
125
+ try? FileManager.default.removeItem(atPath: dir + "/" + name)
126
+ }
127
+ }
128
+ return open
129
+ }
130
+
131
+ /// Three empty looks in a row (~6s) count as closed: a reattach or `hivey update` reopens
132
+ /// windows within that time.
133
+ private func checkWindows() {
134
+ if Self.openWindows() > 0 {
135
+ sawWindow = true
136
+ emptyLooks = 0
137
+ return
138
+ }
139
+ guard sawWindow else { return }
140
+ emptyLooks += 1
141
+ if emptyLooks >= 3 {
142
+ sawWindow = false
143
+ emptyLooks = 0
144
+ if debug { FileHandle.standardError.write(Data("hivey pet: last hivey window closed\n".utf8)) }
145
+ DispatchQueue.main.async { [weak self] in self?.onLastWindowClosed?() }
146
+ }
147
+ }
148
+
149
+ private func poll() {
150
+ checkWindows()
151
+ if hiveyPath == nil { hiveyPath = findHivey() }
152
+ guard let list = run(["swarm", "list", "--json"]) else {
153
+ // hivey gone or its server stopped: start fresh when it's back (no replay of old events)
154
+ if last != nil { report(HiveySnapshot(swarmList: [:]), []) }
155
+ last = nil
156
+ lastMessageTs = nil
157
+ return
158
+ }
159
+ let snapshot = HiveySnapshot(swarmList: list)
160
+ var events = snapshot.events(since: last)
161
+ let firstLook = last == nil
162
+ last = snapshot
163
+
164
+ let records = run(["msg", "log", "--limit", "40", "--json"])?["records"] as? [[String: Any]] ?? []
165
+ let messages = records.filter { $0["ev"] as? String == "msg" }
166
+ let newest = messages.compactMap { $0["ts"] as? Double }.max() ?? 0
167
+ if !firstLook, let since = lastMessageTs {
168
+ for message in messages where (message["ts"] as? Double ?? 0) > since {
169
+ let from = message["from"] as? String ?? ""
170
+ let toHuman = message["to"] as? String == "human"
171
+ events.append(.message(fromHuman: from == "human",
172
+ replyFrom: toHuman && from != "human" ? speaker(from, swarm: message["log"] as? String) : nil,
173
+ text: message["text"] as? String ?? ""))
174
+ }
175
+ }
176
+ lastMessageTs = max(newest, lastMessageTs ?? 0)
177
+ report(snapshot, events)
178
+ }
179
+
180
+ /// How the pet names a message's sender: "swarm/agent" → "agent" in its swarm, solo → its slug
181
+ private func speaker(_ from: String, swarm: String?) -> String {
182
+ let parts = from.split(separator: "/").map(String.init)
183
+ let slug = parts.count == 2 ? parts[0] : (swarm ?? "")
184
+ let key = parts.last ?? from
185
+ if key == slug || slug.isEmpty { return key }
186
+ return last?.names["\(slug)/\(key)"] ?? "\(slug) \(key)"
187
+ }
188
+
189
+ private func report(_ snapshot: HiveySnapshot, _ events: [HiveyEvent]) {
190
+ if debug && !events.isEmpty {
191
+ FileHandle.standardError.write(Data("hivey pet: \(snapshot.working) working, \(snapshot.idle) idle: \(events)\n".utf8))
192
+ }
193
+ DispatchQueue.main.async { [weak self] in self?.onUpdate?(snapshot, events) }
194
+ }
195
+ }
196
+
197
+
198
+ // MARK: - Switching pets
199
+
200
+ /// The hivey pets (folders under pets/ in the hivey repo); `hivey pet use <id>` swaps them.
201
+ let hiveyPets: [(id: String, name: String)] = [
202
+ ("hivey-dot", "Hivey System"),
203
+ ("hivey-prompt", "Hivey Prompt"),
204
+ ("hivey-h", "Hivey"),
205
+ ]
206
+
207
+ /// "Switch pet ▸" and "Turn off pet" for a pet's right-click menu. Both run the hivey CLI
208
+ /// (`hivey pet use <id>` / `hivey pet off`), which builds, swaps and remembers the choice.
209
+ final class PetSwitcher: NSObject {
210
+ private let current: String
211
+ private let say: (String) -> Void
212
+ private let turnOffHere: () -> Void
213
+
214
+ /// `say`: the pet announces the switch; `turnOffHere`: what "Turn off" does without hivey
215
+ init(current: String, say: @escaping (String) -> Void, turnOffHere: @escaping () -> Void) {
216
+ self.current = current
217
+ self.say = say
218
+ self.turnOffHere = turnOffHere
219
+ }
220
+
221
+ func addItems(to menu: NSMenu) {
222
+ let switchItem = NSMenuItem(title: "Switch pet", action: nil, keyEquivalent: "")
223
+ let submenu = NSMenu()
224
+ for pet in hiveyPets {
225
+ let item = submenu.addItem(withTitle: pet.name, action: #selector(choose(_:)), keyEquivalent: "")
226
+ item.target = self
227
+ item.representedObject = pet.id
228
+ item.state = pet.id == current ? .on : .off
229
+ }
230
+ switchItem.submenu = submenu
231
+ menu.addItem(switchItem)
232
+ menu.addItem(withTitle: "Turn off pet", action: #selector(turnOff), keyEquivalent: "").target = self
233
+ }
234
+
235
+ @objc private func choose(_ item: NSMenuItem) {
236
+ guard let id = item.representedObject as? String, id != current else { return }
237
+ let name = hiveyPets.first { $0.id == id }?.name ?? id
238
+ guard runHivey(["pet", "use", id]) else { say("I need hivey to switch pets."); return }
239
+ say("Switching to \(name)…") // hivey quits this pet once the new one is ready
240
+ }
241
+
242
+ @objc private func turnOff() {
243
+ if !runHivey(["pet", "off"]) { turnOffHere() }
244
+ }
245
+
246
+ /// Runs `hivey <args>` detached (it may outlive this pet); false when hivey isn't installed.
247
+ private func runHivey(_ args: [String]) -> Bool {
248
+ guard let hivey = HiveyWatcher().findHivey() else { return false }
249
+ let p = Process()
250
+ p.executableURL = URL(fileURLWithPath: hivey)
251
+ p.arguments = args
252
+ p.currentDirectoryURL = URL(fileURLWithPath: NSHomeDirectory())
253
+ // What happened lands in ~/.hivey/pet.log (a switch builds for a minute; errors matter)
254
+ let log = URL(fileURLWithPath: NSHomeDirectory() + "/.hivey/pet.log")
255
+ try? FileManager.default.createDirectory(at: log.deletingLastPathComponent(), withIntermediateDirectories: true)
256
+ if !FileManager.default.fileExists(atPath: log.path) { FileManager.default.createFile(atPath: log.path, contents: nil) }
257
+ if let handle = try? FileHandle(forWritingTo: log) {
258
+ handle.seekToEndOfFile()
259
+ handle.write(Data("\n\(Date()) hivey \(args.joined(separator: " "))\n".utf8))
260
+ p.standardOutput = handle
261
+ p.standardError = handle
262
+ } else {
263
+ p.standardOutput = FileHandle.nullDevice
264
+ p.standardError = FileHandle.nullDevice
265
+ }
266
+ return (try? p.run()) != nil
267
+ }
268
+ }
269
+
270
+ /// What the pet says when an agent writes to the user: the hivey agent's own words (it's the
271
+ /// chat partner of the pet's chat box), "<agent> replied." for everyone else
272
+ func replyLine(from agent: String, text: String) -> String {
273
+ guard agent == "hivey" else { return "\(agent) replied." }
274
+ let flat = text.split(whereSeparator: \.isNewline).joined(separator: " ")
275
+ return flat.count > 180 ? String(flat.prefix(177)) + "…" : flat
276
+ }
277
+
278
+ // MARK: - Chat with the hivey agent
279
+
280
+ /// Click the pet: a small chat box above it. Enter sends the text to the hivey agent
281
+ /// (`hivey msg send hivey/master`, from `human`); its answer comes back as a hivey message to
282
+ /// `human`, which the pet shows in its bubble and says aloud. Esc, Enter, clicking the pet again
283
+ /// or clicking in another app closes it.
284
+ final class HiveyChat: NSObject, NSTextFieldDelegate {
285
+ /// Feedback through the pet's bubble: (text, aloud)
286
+ var say: ((String, Bool) -> Void)?
287
+ /// The message went out: the pet leans in to listen
288
+ var onSent: (() -> Void)?
289
+ private var panel: ChatPanel?
290
+ private let field = NSTextField()
291
+ /// Clicks in other apps close the box (clicks on the pet toggle it themselves)
292
+ private var outsideClicks: Any?
293
+ private static let mint = NSColor(srgbRed: 0.56, green: 0.94, blue: 0.8, alpha: 1)
294
+
295
+ func toggle(above pet: NSWindow) {
296
+ if let panel, panel.isVisible { close(); return }
297
+ open(above: pet)
298
+ }
299
+
300
+ private func open(above pet: NSWindow) {
301
+ let size = NSSize(width: 320, height: 40)
302
+ let p = panel ?? makePanel(size: size)
303
+ panel = p
304
+ // Above the pet, kept on its screen
305
+ var origin = NSPoint(x: pet.frame.midX - size.width / 2, y: pet.frame.maxY + 4)
306
+ if let screen = pet.screen?.visibleFrame {
307
+ origin.x = min(max(origin.x, screen.minX + 4), screen.maxX - size.width - 4)
308
+ if origin.y + size.height > screen.maxY { origin.y = pet.frame.minY - size.height - 4 }
309
+ }
310
+ p.setFrameOrigin(origin)
311
+ field.stringValue = ""
312
+ NSApp.activate(ignoringOtherApps: true)
313
+ p.makeKeyAndOrderFront(nil)
314
+ p.makeFirstResponder(field)
315
+ if outsideClicks == nil {
316
+ outsideClicks = NSEvent.addGlobalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown]) { [weak self] _ in
317
+ self?.close()
318
+ }
319
+ }
320
+ }
321
+
322
+ func close() {
323
+ panel?.orderOut(nil)
324
+ if let monitor = outsideClicks {
325
+ NSEvent.removeMonitor(monitor)
326
+ outsideClicks = nil
327
+ }
328
+ }
329
+
330
+ private func makePanel(size: NSSize) -> ChatPanel {
331
+ let p = ChatPanel(contentRect: NSRect(origin: .zero, size: size),
332
+ styleMask: [.borderless], backing: .buffered, defer: false)
333
+ p.isOpaque = false
334
+ p.backgroundColor = .clear
335
+ p.level = .floating
336
+ p.hasShadow = true
337
+ p.collectionBehavior = [.canJoinAllSpaces, .ignoresCycle]
338
+
339
+ // Terminal-style box: dark ink, mint edge (like the speech bubble)
340
+ let box = NSView(frame: NSRect(origin: .zero, size: size))
341
+ box.wantsLayer = true
342
+ box.layer?.backgroundColor = NSColor(srgbRed: 0.067, green: 0.082, blue: 0.094, alpha: 1).cgColor
343
+ box.layer?.cornerRadius = 8
344
+ box.layer?.borderWidth = 1.2
345
+ box.layer?.borderColor = Self.mint.cgColor
346
+
347
+ let prompt = NSTextField(labelWithString: ">")
348
+ prompt.font = .monospacedSystemFont(ofSize: 13, weight: .bold)
349
+ prompt.textColor = Self.mint
350
+ prompt.frame = NSRect(x: 12, y: 11, width: 14, height: 18)
351
+ box.addSubview(prompt)
352
+
353
+ field.frame = NSRect(x: 28, y: 10, width: size.width - 40, height: 20)
354
+ field.font = .monospacedSystemFont(ofSize: 12, weight: .medium)
355
+ field.textColor = NSColor(srgbRed: 0.9, green: 0.96, blue: 0.93, alpha: 1)
356
+ field.isBordered = false
357
+ field.drawsBackground = false
358
+ field.focusRingType = .none
359
+ field.placeholderAttributedString = NSAttributedString(
360
+ string: "message hivey… ↵ send · esc close",
361
+ attributes: [.foregroundColor: NSColor(white: 1, alpha: 0.35),
362
+ .font: NSFont.monospacedSystemFont(ofSize: 12, weight: .regular)])
363
+ field.delegate = self
364
+ box.addSubview(field)
365
+ p.contentView = box
366
+ return p
367
+ }
368
+
369
+ // Enter sends, Esc closes
370
+ func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool {
371
+ if selector == #selector(NSResponder.insertNewline(_:)) {
372
+ let text = field.stringValue.trimmingCharacters(in: .whitespacesAndNewlines)
373
+ close()
374
+ if !text.isEmpty { send(text) }
375
+ return true
376
+ }
377
+ if selector == #selector(NSResponder.cancelOperation(_:)) {
378
+ close()
379
+ return true
380
+ }
381
+ return false
382
+ }
383
+
384
+ private func send(_ text: String) {
385
+ guard let hivey = HiveyWatcher().findHivey() else {
386
+ say?("I need hivey to talk to the hivey agent.", false)
387
+ return
388
+ }
389
+ onSent?()
390
+ say?("Sent to hivey.", false)
391
+ // From the user, not from whichever pane started this pet
392
+ let vars = ProcessInfo.processInfo.environment.filter { !$0.key.hasPrefix("HERDR_") && !$0.key.hasPrefix("HIVEY_") }
393
+ DispatchQueue.global().async { [weak self] in
394
+ let p = Process()
395
+ p.executableURL = URL(fileURLWithPath: hivey)
396
+ p.arguments = ["msg", "send", "hivey/master", text]
397
+ p.currentDirectoryURL = URL(fileURLWithPath: NSHomeDirectory())
398
+ p.environment = vars
399
+ let err = Pipe()
400
+ p.standardOutput = FileHandle.nullDevice
401
+ p.standardError = err
402
+ var ok = false
403
+ if (try? p.run()) != nil {
404
+ p.waitUntilExit()
405
+ ok = p.terminationStatus == 0
406
+ }
407
+ let detail = String(data: err.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
408
+ DispatchQueue.main.async {
409
+ guard !ok else { return }
410
+ let reason = detail.contains("server_not_running") || detail.contains("no herdr server")
411
+ ? "hivey isn't running." : "the hivey agent isn't set up (hivey home setup)."
412
+ self?.say?("Couldn't send: \(reason)", false)
413
+ }
414
+ }
415
+ }
416
+ }
417
+
418
+ /// A borderless panel that can take the keyboard
419
+ final class ChatPanel: NSPanel {
420
+ override var canBecomeKey: Bool { true }
421
+ }
422
+
423
+ /// The process that speaks a pet's line (the text goes to its stdin): `hivey voice say`, so the
424
+ /// pet uses the provider, voice and quiet hours from hivey settings → voice and waits its turn
425
+ /// behind the Claude Code hook; plain `say` when hivey isn't installed. `interruptible`: whether
426
+ /// terminating it stops the speech (hivey's speaker is its child, so it is not).
427
+ func speechProcess() -> (process: Process, interruptible: Bool) {
428
+ let p = Process()
429
+ if let hivey = HiveyWatcher().findHivey() {
430
+ p.executableURL = URL(fileURLWithPath: hivey)
431
+ p.arguments = ["voice", "say"]
432
+ return (p, false)
433
+ }
434
+ p.executableURL = URL(fileURLWithPath: "/usr/bin/say")
435
+ if let voice = UserDefaults.standard.string(forKey: "voice") { p.arguments = ["-v", voice] }
436
+ return (p, true)
437
+ }
@@ -0,0 +1,122 @@
1
+ """Tests for pet.py (no building, launching or quitting: those calls are stubbed)."""
2
+ import io
3
+ import os
4
+ import plistlib
5
+ import tempfile
6
+ import time
7
+ import unittest
8
+ from contextlib import redirect_stdout
9
+ from pathlib import Path
10
+ from unittest import mock
11
+
12
+ import pet
13
+
14
+
15
+ class PetTest(unittest.TestCase):
16
+ def setUp(self):
17
+ self.home = tempfile.TemporaryDirectory()
18
+ self.env = mock.patch.dict(os.environ, {"HOME": self.home.name})
19
+ self.env.start()
20
+
21
+ def tearDown(self):
22
+ self.env.stop()
23
+ self.home.cleanup()
24
+
25
+ def test_choice_is_remembered(self):
26
+ self.assertIsNone(pet.chosen())
27
+ pet.save_choice("hivey-dot")
28
+ self.assertEqual(pet.chosen(), "hivey-dot")
29
+ pet.save_choice(None)
30
+ self.assertIsNone(pet.chosen())
31
+
32
+ def test_login_item_opens_the_installed_app(self):
33
+ pet.set_login("hivey-h", True)
34
+ plist = plistlib.loads(pet.launch_agent("hivey-h").read_bytes())
35
+ self.assertEqual(plist["Label"], "com.hivey.h")
36
+ self.assertEqual(plist["ProgramArguments"][-1], str(pet.installed_app("hivey-h")))
37
+ self.assertTrue(plist["RunAtLoad"])
38
+ pet.set_login("hivey-h", False)
39
+ self.assertFalse(pet.launch_agent("hivey-h").exists())
40
+
41
+ def test_outdated_until_built_after_the_source(self):
42
+ self.assertTrue(pet.outdated("hivey-h")) # not installed
43
+ exe = pet.installed_app("hivey-h") / "Contents" / "MacOS" / "hivey-h"
44
+ exe.parent.mkdir(parents=True)
45
+ exe.write_text("")
46
+ newest = max(src.stat().st_mtime for src in pet.sources("hivey-h"))
47
+ os.utime(exe, (newest + 10, newest + 10))
48
+ self.assertFalse(pet.outdated("hivey-h"))
49
+ os.utime(exe, (newest - 10, newest - 10))
50
+ self.assertTrue(pet.outdated("hivey-h"))
51
+
52
+ def test_use_switches_and_retires_the_others(self):
53
+ calls = []
54
+ with mock.patch.object(pet, "check_mac"), \
55
+ mock.patch.object(pet, "outdated", return_value=False), \
56
+ mock.patch.object(pet, "quit_pet", side_effect=lambda p: calls.append(("quit", p))), \
57
+ mock.patch.object(pet.subprocess, "run") as run, \
58
+ redirect_stdout(io.StringIO()):
59
+ pet.set_login("hivey-dot", True)
60
+ pet.use("hivey-prompt")
61
+ self.assertEqual(pet.chosen(), "hivey-prompt")
62
+ # pets show while hivey is open: old login items are removed, none are added
63
+ self.assertFalse(any(pet.launch_agent(p).exists() for p in pet.ORDER))
64
+ self.assertEqual({p for _, p in calls}, set(pet.ORDER))
65
+ self.assertEqual(run.call_args.args[0][:2], ["open", "-a"])
66
+
67
+ def test_show_starts_only_a_chosen_stopped_pet(self):
68
+ with mock.patch.object(pet.platform, "system", return_value="Darwin"), \
69
+ mock.patch.object(pet, "outdated", return_value=False), \
70
+ mock.patch.object(pet.subprocess, "run") as run:
71
+ pet.show() # nothing chosen
72
+ pet.save_choice("hivey-h")
73
+ with mock.patch.object(pet, "running", return_value=True):
74
+ pet.show() # already there
75
+ run.assert_not_called()
76
+ with mock.patch.object(pet, "running", return_value=False):
77
+ pet.show()
78
+ self.assertEqual(run.call_args.args[0][:3], ["open", "-g", "-a"])
79
+
80
+ def test_unknown_pet_is_refused(self):
81
+ with self.assertRaises(SystemExit) as stop:
82
+ pet.use("cat")
83
+ self.assertIn("hivey-h", str(stop.exception))
84
+
85
+ def test_off_forgets_the_pet(self):
86
+ pet.save_choice("hivey-h")
87
+ pet.set_login("hivey-h", True)
88
+ with mock.patch.object(pet, "quit_pet"), redirect_stdout(io.StringIO()):
89
+ pet.off()
90
+ self.assertIsNone(pet.chosen())
91
+ self.assertFalse(pet.launch_agent("hivey-h").exists())
92
+
93
+ def test_choose(self):
94
+ cases = [("2", ("use", "hivey-dot")), ("0", ("off",)), ("", None), ("9", None)]
95
+ for answer, expected in cases:
96
+ with mock.patch("builtins.input", return_value=answer), \
97
+ mock.patch.object(pet, "use") as use, mock.patch.object(pet, "off") as off, \
98
+ redirect_stdout(io.StringIO()):
99
+ pet.choose()
100
+ if expected is None:
101
+ use.assert_not_called()
102
+ off.assert_not_called()
103
+ elif expected[0] == "use":
104
+ use.assert_called_once_with(expected[1])
105
+ else:
106
+ off.assert_called_once()
107
+
108
+ def test_refresh_only_rebuilds_a_chosen_outdated_pet(self):
109
+ with mock.patch.object(pet, "use") as use, mock.patch.object(pet.platform, "system", return_value="Darwin"), \
110
+ mock.patch.object(pet.shutil, "which", return_value="/usr/bin/swiftc"):
111
+ pet.refresh() # no pet chosen
112
+ pet.save_choice("hivey-h")
113
+ with mock.patch.object(pet, "outdated", return_value=False):
114
+ pet.refresh()
115
+ use.assert_not_called()
116
+ with mock.patch.object(pet, "outdated", return_value=True):
117
+ pet.refresh()
118
+ use.assert_called_once_with("hivey-h")
119
+
120
+
121
+ if __name__ == "__main__":
122
+ unittest.main()
@@ -0,0 +1,108 @@
1
+ # hivey swarm addons
2
+
3
+ An **addon** is an ordinary hivey (herdr) plugin that `hivey swarm launch` opens in a swarm's
4
+ own space before the agents start. Relays are the main use: bridging the swarm's message bus
5
+ to Slack, Discord, Telegram, email, or anything else. Anyone can write one.
6
+
7
+ ```bash
8
+ hivey plugin link ./plugins/slack-relay # or: hivey plugin install owner/repo/path
9
+ hivey swarm launch <root> --slug app --channel C0123 scout critic \
10
+ --addon hivey.slack-relay # alias: --relay; repeatable
11
+ hivey swarm launch … --addon me.discord:bridge # a pane entrypoint other than "relay"
12
+ ```
13
+
14
+ ## Contract
15
+
16
+ 1. **Manifest.** A `herdr-plugin.toml` with a `[[panes]]` entrypoint, `relay` by default:
17
+ ```toml
18
+ id = "me.discord-relay"
19
+ name = "Discord relay"
20
+ version = "0.1.0"
21
+ min_herdr_version = "0.9.0"
22
+ platforms = ["linux", "macos"]
23
+
24
+ [[panes]]
25
+ id = "relay"
26
+ title = "discord relay"
27
+ placement = "split"
28
+ command = ["sh", "-c", "exec python3 \"$HERDR_PLUGIN_ROOT/relay.py\""]
29
+ ```
30
+ The pane runs with the **swarm root as its working directory**, so reach your own files
31
+ through `$HERDR_PLUGIN_ROOT`.
32
+ 2. **Environment.** hivey sets:
33
+ | Variable | Value |
34
+ |---|---|
35
+ | `HIVEY_SWARM_ROOT` | the swarm folder (`<root>/.swarm/agents.json` is the roster) |
36
+ | `HIVEY_SWARM_SLUG` | the swarm's slug |
37
+ | `HIVEY_SWARM_CHANNEL` | `--channel` (or the manifest's `channel_id`), may be empty |
38
+ | `HERDR_BIN_PATH` | the hivey binary to call |
39
+ | `HERDR_PLUGIN_CONFIG_DIR` / `HERDR_PLUGIN_STATE_DIR` | your config (tokens, options) / state |
40
+ 3. **Inbound (outside → agents).** Send through the bus, so delivery timing, queueing, digests
41
+ and the log all apply:
42
+ ```bash
43
+ "$HERDR_BIN_PATH" msg send <agent|@all|master> "text" --swarm "$HIVEY_SWARM_SLUG" --from human --json
44
+ ```
45
+ Use `--from <slug>/<agent>` when the outside message was written on an agent's behalf.
46
+ 4. **Outbound (agents → outside).** Tail `<root>/.swarm/bus.jsonl`. Every line is JSON; messages
47
+ have `"ev": "msg"` with `id`, `ts` (ms), `from` (`<slug>/<agent>`, `human`, `hivey`), `swarm`,
48
+ `to`, `kind` (`normal`/`fyi`/`urgent`), `text`, and `copy: true` on a sender-side copy of a
49
+ cross-swarm message (skip those). Receipts (`delivered`, `read`, `held`) can be ignored.
50
+ Remember the ids you injected, so you don't echo them back.
51
+ 5. **Robustness.** Keep your own state (e.g. under `<root>/.swarm/`) so a restart resumes where
52
+ it stopped, and never exit on a network error.
53
+
54
+ hivey records opened addons in the manifest (`"addons"`) and shows them as `▷` script panes;
55
+ they never receive messages themselves.
56
+
57
+ ## Setup providers
58
+
59
+ A **setup provider** designs a swarm (team, roles, briefs, memory, channels) and hands it to
60
+ hivey. hivey doesn't hardcode one: any plugin with a pane entrypoint `setup` is a provider.
61
+
62
+ ```bash
63
+ hivey swarm providers # installed providers (* = default)
64
+ hivey swarm new "<task>" # the default (or only) provider
65
+ hivey swarm new --provider my.crew --default "<task>"
66
+ ```
67
+
68
+ `hivey swarm new` opens the provider's `setup` pane as a new tab in the current folder (creating
69
+ a space for it if none is open), with `HIVEY_SETUP_TASK` and `HIVEY_SETUP_CWD` set. The provider
70
+ then:
71
+
72
+ 1. writes each agent's brief into `<root>/<agent>/CLAUDE.md` (Codex agents read `AGENTS.md`;
73
+ hivey links it to `CLAUDE.md` when only that exists), and
74
+ 2. runs `hivey swarm launch <root> --slug … <agents…>` with whatever it chose: `--models`,
75
+ `--kinds a=codex`, `--channel`, `--addon …`, `--heartbeat 15m --heartbeat-task "…"`,
76
+ `--kickoff "…"`. Launch moves the provider's pane into the swarm's space as the master.
77
+
78
+ The swarm manifest `<root>/.swarm/agents.json` is hivey's; a provider may add:
79
+
80
+ | Field | Shown / used by hivey |
81
+ |---|---|
82
+ | `info` | `{"Slack": "#swarm-x (C0…)", "vault": "…"}` or `[[label, value], …]`: shown in the hover card and `hivey swarm info` |
83
+ | `product_dir` | the product folder `hivey.github` publishes (default `app`) |
84
+ | `state` | `"paused"` holds all deliveries (what `hivey swarm pause` sets) |
85
+ | `.swarm/tasks.json` | `{"tasks": [{"status": "open\|in-progress\|review\|approved\|blocked"}]}`: task counts in info and the dashboard |
86
+
87
+ Step-by-step guide and an example to copy: [`../docs/hivey-providers.md`](../docs/hivey-providers.md)
88
+ (`hivey.team-template`, a fixed builder + critic team).
89
+
90
+ Included: **`hivey.swarm-creator`** and **`hivey.agent-creator`** open a Claude coordinator (or
91
+ designer) running the `hivey-swarm-creator` / `hivey-agent-creator` skill, which ship with hivey.
92
+ **`hivey.swarm-watcher`** (an addon) tells a swarm's master when a worker is blocked, stopped,
93
+ stalled or gone and when the time budget runs out, and keeps a Gantt dashboard page.
94
+
95
+ ## Included
96
+
97
+ - [`slack-relay`](slack-relay/) (`hivey.slack-relay`): Slack ↔ bus. Configure the token in
98
+ `$(hivey plugin config-dir hivey.slack-relay)/config.json`:
99
+ `{"token_command": "envsave get <id>", "mirror": "masters"}` (or set `SLACK_TOKEN`).
100
+ `mirror` is `masters` (default), `all`, or `off`. Tests: `python3 -m unittest plugins/slack-relay/test_relay.py`.
101
+ - [`dashboard`](dashboard/) (`hivey.dashboard`): live pane with agent states, token bars and a
102
+ token-rate sparkline, budget, task counts and recent messages. Tests:
103
+ `python3 -m unittest plugins/dashboard/test_dashboard.py`.
104
+ - [`github`](github/) (`hivey.github`): publishes the product (e.g. `app/`) and the swarm
105
+ workspace as two repos, `<slug>` and `<slug>-swarm`. It shows the plan and creates nothing
106
+ until you confirm; gitleaks scans what is committed before each first push. Then "push both"
107
+ on demand. Try it safely with `HIVEY_GITHUB_DRY_RUN=1`. Tests:
108
+ `python3 -m unittest plugins/github/test_github.py`.