@hivey/cli 0.9.73 → 0.9.75

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.
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hivey/cli",
3
- "version": "0.9.73",
3
+ "version": "0.9.75",
4
4
  "description": "All your AI swarms, one terminal: a workspace and lead agent for teams of Claude Code and Codex agents",
5
5
  "keywords": [
6
6
  "hivey",
@@ -17,7 +17,10 @@ Desktop pets that act out what hivey's agents do. Choose one (or none) with `hiv
17
17
  - `pet.py`: `hivey pet` (build, install to `~/Applications`, switch, off, show). The
18
18
  choice is in `~/.hivey/pet.json`; `hivey update` runs `hivey pet refresh` to rebuild it when
19
19
  its source changed.
20
- - Chat: clicking a pet opens `HiveyChat` (a box above it); Enter sends the text to the hivey
20
+ - Click: right-click → On click ▸ picks what a click does (`PetClick`, shared): open the agent fleet
21
+ (default; `hivey agent-map fleet` refreshes and fronts the fleet tab already open in Chrome, or opens
22
+ it in a new Chrome window) or the chat box. The menu's "Open agent fleet" and "Chat with hivey" items do either anytime.
23
+ - Chat: "Chat with hivey" (or a click, when picked) opens `HiveyChat` (a box above it); Enter sends the text to the hivey
21
24
  agent (`hivey msg send hivey/master`), whose reply to `human` the pet shows and says
22
25
  (`replyLine`). Other agents' replies are announced as "<agent> replied.".
23
26
  - Lifecycle: every hivey window writes `~/.hivey/windows/<pid>` while open and runs
@@ -34,7 +34,8 @@ Professional "harness" look: a dark graphite satin sphere (key light upper-left,
34
34
  - `build.sh` — builds universal (arm64 + x86_64, macOS 12+) ad-hoc-signed `Hivey System.app` and `dist/HiveySystem.zip` for sharing. Run after every change.
35
35
 
36
36
  ## Behavior
37
- - Click = chat box above the pet (`HiveyChat`): Enter sends to the hivey agent (`hivey msg send hivey/master`), Esc / clicking away closes; the agent's reply to `human` is shown in the bubble and said aloud. Drag still moves the pet.
37
+ - Click = the action picked in right-click → On click ▸ (`PetClick`, shared): **Open agent fleet** (default; `hivey agent-map fleet` reloads and fronts the fleet tab already open in Chrome, or opens it in a new Chrome window) or **Open chat box**. The menu also has "Open agent fleet" and "Chat with hivey" items, whatever the click does.
38
+ - Chat box above the pet (`HiveyChat`): Enter sends to the hivey agent (`hivey msg send hivey/master`), Esc / clicking away closes; the agent's reply to `human` is shown in the bubble and said aloud. Drag still moves the pet.
38
39
  - Lives in the hivey repo (`pets/hivey-dot/`). Built and installed by `hivey pet use hivey-dot` (into `~/Applications`; the other pets are quit); `./build.sh` compiles `main.swift` with the shared `../shared/HiveyWatch.swift`.
39
40
  - Right-click: hivey status line ("hivey: N agents, M working"), Watch hivey, Speak aloud, Effects (preview only) ▸ (plays the pet's moves; nothing happens in hivey), Switch pet ▸ (Hivey / Hivey Prompt / Hivey, via `hivey pet use`), Turn off pet (`hivey pet off`), Quit.
40
41
  - Watches hivey through the shared `HiveyWatcher` (every 2s: `hivey swarm list --json` + `hivey msg log --json`, default session, never starts a server, nothing replayed on first look). Spoken aloud: "<slug> is starting.", "<agent> needs you.", "<agent> replied."; "<agent> finished." is bubble-only; one line per look, most urgent first.
@@ -43,7 +44,7 @@ Professional "harness" look: a dark graphite satin sphere (key light upper-left,
43
44
  - Event CLI: `Hivey.app/Contents/MacOS/hivey agent|leave|swarm|pulse|done ["text"]` (DistributedNotification `com.hivey.pet.event`).
44
45
  - On launch: fades in, small restrained lift + mint glow, says "Welcome! I'm Hivey." (bubble + voice). Always visible, floats above windows, on all Spaces.
45
46
  - Idle: agents travel the signal wave (`signalPoint`, depth-sorted behind/in front of Hivey), breathing, blinking, eyes follow the cursor, occasional message pulse between agents.
46
- - Click = small lift + glow, and the chat box opens (see above).
47
+ - Click = small lift + glow, then the click action (see above).
47
48
  - Effects (preview only) ▸: New agent (dot flies out, max 9), Swarm formation (dots arc above Hivey, frequent pulses, 5s), Task finished (lift + glow), Quit.
48
49
  - A crew-motion variant (no orbit; idle groups, errands, listen/swarm/tidy formations) was tried on 2026-10-02 and rejected — user prefers the orbit.
49
50
  - Drag = move (position autosaved as `HiveyPet`).
@@ -508,6 +508,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
508
508
  private let hiveyItem = NSMenuItem(title: "hivey: looking…", action: nil, keyEquivalent: "")
509
509
  private let watcher = HiveyWatcher()
510
510
  private let chat = HiveyChat()
511
+ private lazy var clicks = PetClickMenu(
512
+ chat: { [weak self] in guard let self else { return }; chat.toggle(above: window) },
513
+ say: { [weak self] in self?.say($0, aloud: false) })
511
514
  private lazy var switcher = PetSwitcher(current: "hivey-dot", say: { [weak self] in self?.say($0, aloud: false) },
512
515
  turnOffHere: { [weak self] in self?.turnOff() })
513
516
  private var watching: Bool {
@@ -561,14 +564,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
561
564
  effectsItem.submenu = effects
562
565
  menu.addItem(effectsItem)
563
566
  menu.addItem(.separator())
567
+ clicks.addItems(to: menu)
568
+ menu.addItem(.separator())
564
569
  switcher.addItems(to: menu)
565
570
  menu.addItem(withTitle: "Quit Hivey", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "")
566
571
  pet.menu = menu
567
- // Click: talk to the hivey agent (a chat box above the pet); drag still moves it
572
+ // Click: the agent fleet page or the chat box (On click ▸); drag still moves it
568
573
  pet.onPoke = { [weak self] in
569
574
  guard let self else { return }
570
575
  pet.celebrate()
571
- chat.toggle(above: window)
576
+ clicks.click() // right-click → On click ▸: agent fleet (default) or chat box
572
577
  }
573
578
  chat.say = { [weak self] text, aloud in self?.say(text, aloud: aloud) }
574
579
  chat.onSent = { [weak self] in self?.pet.pulse() }
@@ -39,7 +39,8 @@ A living, three-dimensional "H": the software conductor whose body shows how it
39
39
  - `build.sh` — builds universal (arm64 + x86_64, macOS 12+) ad-hoc-signed `Hivey.app` and `dist/Hivey.zip`. Run after every change.
40
40
 
41
41
  ## Behavior
42
- - Click = chat box above the pet (`HiveyChat`): Enter sends to the hivey agent (`hivey msg send hivey/master`), Esc / clicking away closes; the agent's reply to `human` is shown in the bubble and said aloud. Drag still moves the pet.
42
+ - Click = the action picked in right-click → On click ▸ (`PetClick`, shared): **Open agent fleet** (default; `hivey agent-map fleet` reloads and fronts the fleet tab already open in Chrome, or opens it in a new Chrome window) or **Open chat box**. The menu also has "Open agent fleet" and "Chat with hivey" items, whatever the click does.
43
+ - Chat box above the pet (`HiveyChat`): Enter sends to the hivey agent (`hivey msg send hivey/master`), Esc / clicking away closes; the agent's reply to `human` is shown in the bubble and said aloud. Drag still moves the pet.
43
44
  - Lives in the hivey repo (`pets/hivey-h/`). Built and installed by `hivey pet use hivey-h` (into `~/Applications`; the other pets are quit); `./build.sh` compiles `main.swift` with the shared `../shared/HiveyWatch.swift`.
44
45
  - Right-click: hivey status line ("hivey: N agents, M working"), Watch hivey, Speak aloud, Effects (preview only) ▸ (plays the pet's moves; nothing happens in hivey), Switch pet ▸ (Hivey / Hivey Prompt / Hivey, via `hivey pet use`), Turn off pet (`hivey pet off`), Quit.
45
46
  - Watches hivey through the shared `HiveyWatcher` (every 2s: `hivey swarm list --json` + `hivey msg log --json`, default session, never starts a server, nothing replayed on first look). Spoken aloud: "<slug> is starting.", "<agent> needs you.", "<agent> replied."; "<agent> finished." is bubble-only; one line per look, most urgent first.
@@ -492,6 +492,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
492
492
  private let hiveyItem = NSMenuItem(title: "hivey: looking…", action: nil, keyEquivalent: "")
493
493
  private let watcher = HiveyWatcher()
494
494
  private let chat = HiveyChat()
495
+ private lazy var clicks = PetClickMenu(
496
+ chat: { [weak self] in guard let self else { return }; chat.toggle(above: window) },
497
+ say: { [weak self] in self?.say($0, aloud: false) })
495
498
  private lazy var switcher = PetSwitcher(current: "hivey-h", say: { [weak self] in self?.say($0, aloud: false) },
496
499
  turnOffHere: { [weak self] in self?.turnOff() })
497
500
  private var watching: Bool {
@@ -543,14 +546,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
543
546
  effectsItem.submenu = effects
544
547
  menu.addItem(effectsItem)
545
548
  menu.addItem(.separator())
549
+ clicks.addItems(to: menu)
550
+ menu.addItem(.separator())
546
551
  switcher.addItems(to: menu)
547
552
  menu.addItem(withTitle: "Quit Hivey", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "")
548
553
  pet.menu = menu
549
- // Click: talk to the hivey agent (a chat box above the pet); drag still moves it
554
+ // Click: the agent fleet page or the chat box (On click ▸); drag still moves it
550
555
  pet.onPoke = { [weak self] in
551
556
  guard let self else { return }
552
557
  pet.listen()
553
- chat.toggle(above: window)
558
+ clicks.click() // right-click → On click ▸: agent fleet (default) or chat box
554
559
  }
555
560
  chat.say = { [weak self] text, aloud in self?.say(text, aloud: aloud) }
556
561
  chat.onSent = { [weak self] in self?.pet.listen(for: 3) }
@@ -35,7 +35,8 @@ A three-dimensional satin sphere: deep charcoal-teal body, crisp mint `>_` face,
35
35
  - `build.sh` — builds universal (arm64 + x86_64, macOS 12+) ad-hoc-signed `Hivey Prompt.app` and `dist/HiveyPrompt.zip`. Run after every change.
36
36
 
37
37
  ## Behavior
38
- - Click = chat box above the pet (`HiveyChat`): Enter sends to the hivey agent (`hivey msg send hivey/master`), Esc / clicking away closes; the agent's reply to `human` is shown in the bubble and said aloud. Drag still moves the pet.
38
+ - Click = the action picked in right-click → On click ▸ (`PetClick`, shared): **Open agent fleet** (default; `hivey agent-map fleet` reloads and fronts the fleet tab already open in Chrome, or opens it in a new Chrome window) or **Open chat box**. The menu also has "Open agent fleet" and "Chat with hivey" items, whatever the click does.
39
+ - Chat box above the pet (`HiveyChat`): Enter sends to the hivey agent (`hivey msg send hivey/master`), Esc / clicking away closes; the agent's reply to `human` is shown in the bubble and said aloud. Drag still moves the pet.
39
40
  - Lives in the hivey repo (`pets/hivey-prompt/`). Built and installed by `hivey pet use hivey-prompt` (into `~/Applications`; the other pets are quit); `./build.sh` compiles `main.swift` with the shared `../shared/HiveyWatch.swift`.
40
41
  - Right-click: hivey status line ("hivey: N agents, M working"), Watch hivey, Speak aloud, Effects (preview only) ▸ (plays the pet's moves; nothing happens in hivey), Switch pet ▸ (Hivey / Hivey Prompt / Hivey, via `hivey pet use`), Turn off pet (`hivey pet off`), Quit.
41
42
  - Watches hivey through the shared `HiveyWatcher` (every 2s: `hivey swarm list --json` + `hivey msg log --json`, default session, never starts a server, nothing replayed on first look). Spoken aloud: "<slug> is starting.", "<agent> needs you.", "<agent> replied."; "<agent> finished." is bubble-only; one line per look, most urgent first.
@@ -445,6 +445,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
445
445
  private let hiveyItem = NSMenuItem(title: "hivey: looking…", action: nil, keyEquivalent: "")
446
446
  private let watcher = HiveyWatcher()
447
447
  private let chat = HiveyChat()
448
+ private lazy var clicks = PetClickMenu(
449
+ chat: { [weak self] in guard let self else { return }; chat.toggle(above: window) },
450
+ say: { [weak self] in self?.say($0, aloud: false) })
448
451
  private lazy var switcher = PetSwitcher(current: "hivey-prompt", say: { [weak self] in self?.say($0, aloud: false) },
449
452
  turnOffHere: { [weak self] in self?.turnOff() })
450
453
  private var watching: Bool {
@@ -499,14 +502,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
499
502
  effectsItem.submenu = effects
500
503
  menu.addItem(effectsItem)
501
504
  menu.addItem(.separator())
505
+ clicks.addItems(to: menu)
506
+ menu.addItem(.separator())
502
507
  switcher.addItems(to: menu)
503
508
  menu.addItem(withTitle: "Quit Hivey Prompt", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "")
504
509
  pet.menu = menu
505
- // Click: talk to the hivey agent (a chat box above the pet); drag still moves it
510
+ // Click: the agent fleet page or the chat box (On click ▸); drag still moves it
506
511
  pet.onPoke = { [weak self] in
507
512
  guard let self else { return }
508
513
  pet.attend()
509
- chat.toggle(above: window)
514
+ clicks.click() // right-click → On click ▸: agent fleet (default) or chat box
510
515
  }
511
516
  chat.say = { [weak self] text, aloud in self?.say(text, aloud: aloud) }
512
517
  chat.onSent = { [weak self] in self?.pet.attend() }
@@ -242,28 +242,102 @@ final class PetSwitcher: NSObject {
242
242
  @objc private func turnOff() {
243
243
  if !runHivey(["pet", "off"]) { turnOffHere() }
244
244
  }
245
+ }
245
246
 
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
247
+ /// Runs `hivey <args>` detached (it may outlive this pet); false when hivey isn't installed.
248
+ func runHivey(_ args: [String]) -> Bool {
249
+ guard let hivey = HiveyWatcher().findHivey() else { return false }
250
+ let p = Process()
251
+ p.executableURL = URL(fileURLWithPath: hivey)
252
+ p.arguments = args
253
+ p.currentDirectoryURL = URL(fileURLWithPath: NSHomeDirectory())
254
+ // What happened lands in ~/.hivey/pet.log (a switch builds for a minute; errors matter)
255
+ let log = URL(fileURLWithPath: NSHomeDirectory() + "/.hivey/pet.log")
256
+ try? FileManager.default.createDirectory(at: log.deletingLastPathComponent(), withIntermediateDirectories: true)
257
+ if !FileManager.default.fileExists(atPath: log.path) { FileManager.default.createFile(atPath: log.path, contents: nil) }
258
+ if let handle = try? FileHandle(forWritingTo: log) {
259
+ handle.seekToEndOfFile()
260
+ handle.write(Data("\n\(Date()) hivey \(args.joined(separator: " "))\n".utf8))
261
+ p.standardOutput = handle
262
+ p.standardError = handle
263
+ } else {
264
+ p.standardOutput = FileHandle.nullDevice
265
+ p.standardError = FileHandle.nullDevice
266
+ }
267
+ return (try? p.run()) != nil
268
+ }
269
+
270
+ // MARK: - What a click on the pet does
271
+
272
+ /// The pet's click action, picked in its right-click menu (On click ▸) and kept per pet.
273
+ enum PetClick: String, CaseIterable {
274
+ /// Bring up the agent fleet page: the Chrome tab already showing it, refreshed, or a new one
275
+ case fleet
276
+ /// The chat box above the pet (`HiveyChat`)
277
+ case chat
278
+
279
+ var title: String {
280
+ switch self {
281
+ case .fleet: return "Open agent fleet"
282
+ case .chat: return "Open chat box"
265
283
  }
266
- return (try? p.run()) != nil
284
+ }
285
+
286
+ static var current: PetClick {
287
+ get { UserDefaults.standard.string(forKey: "clickAction").flatMap(PetClick.init) ?? .fleet }
288
+ set { UserDefaults.standard.set(newValue.rawValue, forKey: "clickAction") }
289
+ }
290
+ }
291
+
292
+ /// "Open agent fleet", "Chat with hivey" and "On click ▸" for a pet's right-click menu, and the
293
+ /// click itself. The fleet runs `hivey agent-map fleet`, which reloads and fronts an open fleet
294
+ /// tab in Chrome or opens one.
295
+ final class PetClickMenu: NSObject {
296
+ private let chat: () -> Void
297
+ private let say: (String) -> Void
298
+ private var choiceItems: [NSMenuItem] = []
299
+
300
+ /// `chat`: open/close the chat box; `say`: a bubble line from the pet
301
+ init(chat: @escaping () -> Void, say: @escaping (String) -> Void) {
302
+ self.chat = chat
303
+ self.say = say
304
+ }
305
+
306
+ func click() {
307
+ switch PetClick.current {
308
+ case .fleet: openFleet()
309
+ case .chat: chat()
310
+ }
311
+ }
312
+
313
+ func addItems(to menu: NSMenu) {
314
+ menu.addItem(withTitle: "Open agent fleet", action: #selector(fleetItem), keyEquivalent: "").target = self
315
+ menu.addItem(withTitle: "Chat with hivey", action: #selector(chatItem), keyEquivalent: "").target = self
316
+ let onClick = NSMenuItem(title: "On click", action: nil, keyEquivalent: "")
317
+ let submenu = NSMenu()
318
+ for action in PetClick.allCases {
319
+ let item = submenu.addItem(withTitle: action.title, action: #selector(choose(_:)), keyEquivalent: "")
320
+ item.target = self
321
+ item.representedObject = action.rawValue
322
+ item.state = action == PetClick.current ? .on : .off
323
+ choiceItems.append(item)
324
+ }
325
+ onClick.submenu = submenu
326
+ menu.addItem(onClick)
327
+ }
328
+
329
+ func openFleet() {
330
+ guard runHivey(["agent-map", "fleet"]) else { say("I need hivey to open the fleet."); return }
331
+ say("Opening the agent fleet…")
332
+ }
333
+
334
+ @objc private func fleetItem() { openFleet() }
335
+ @objc private func chatItem() { chat() }
336
+
337
+ @objc private func choose(_ item: NSMenuItem) {
338
+ guard let raw = item.representedObject as? String, let action = PetClick(rawValue: raw) else { return }
339
+ PetClick.current = action
340
+ for choice in choiceItems { choice.state = choice.representedObject as? String == raw ? .on : .off }
267
341
  }
268
342
  }
269
343
 
@@ -111,6 +111,7 @@ hivey agent-map nightly [--model sonnet] # a full report now (also: --no-llm,
111
111
  hivey agent-map schedule install [--at 06:30] [--model sonnet] # | remove | status
112
112
  ```
113
113
 
114
+ - **Failing jobs, live:** the fleet page asks `/hv-job-health` on load, every 5 minutes and when the Jobs tab opens (a jobs-only scan, ~0.1 s, no model). Jobs whose last run exited non-zero get a red count on the 📊 Jobs tab, a "N scheduled jobs failing" chip in the top strip and a banner over the jobs pages (click a job: its error lines, log path and log tail); jobs not loaded, missed or with errors in an ok run are listed folded under "more to check". A run that exited non-zero keeps its error lines even when it ends with "All done!", and the one-line error is the line naming a cause (an HTTP status, `fatal:`, an exception).
114
115
  - **hivey menu → agent fleet → 📊 Jobs tab** (key 4, or `/fleet/?view=jobs`) shows these pages inside the fleet page: the frame loads `/hv-jobs`, which the server redirects to the latest map (else stats, logs, sessions); with no report yet it starts the first build (`agent_map.py open --no-open`) and shows a page that reloads until it is ready. Every jobs page's navbar starts with 🚀 Fleet (hidden inside the frame). `hivey agent-map open` still opens `agent-stats.html`,
115
116
  `agent-map.html` and `agent-logs.html` from `~/.hivey/agent-map/reports/latest`.
116
117
  - **hivey's layer on the archify pages** (`enhance.py`, after finalize; `agent_map.py enhance [folder]`
@@ -184,7 +185,7 @@ hivey agent-map schedule install [--at 06:30] [--model sonnet] # | remove | st
184
185
 
185
186
  ## Agent fleet (what every agent does now)
186
187
 
187
- `hivey agent-map fleet` (or `fleet`; hivey menu → agent fleet) opens http://127.0.0.1:42817/fleet/ (old /fleet/ links redirect there; files in `reports/fleet/`): every live
188
+ `hivey agent-map fleet` (or `fleet`; hivey menu → agent fleet) opens http://127.0.0.1:42817/fleet/ (old /fleet/ links redirect there; files in `reports/fleet/`; a fleet tab already open in Chrome is reloaded and brought to the front, otherwise it opens in a new Chrome window, not a tab in yours; the desktop pet's click does the same by default): every live
188
189
  agent in hivey at a desk in a 3D fleet, one room per space, and one spaceship per hivey session (`hivey session list`: the default session flies the classic frigate, the others a carrier, an explorer or a recoloured frigate, their name painted on the hull; a stopped session's ship has cold engines and its agents asleep at their desks, read from its saved `session.json`; a running one's engines burn). Click an agent to open its session in a terminal: the one already showing it, or a new Terminal/iTerm window running `hivey session attach <name>`, which also starts a stopped session. Click the name painted on a ship's hull for its menu (hover shows its agent count): open/start the session, or stop it (a second click confirms; `hivey session stop` ends all its agents and closes its terminal; never the default session). The space outside is one of six scenes (violet, emerald, crimson, deep blue, golden twin suns, a singularity with its lensed accretion disk), chosen with the page's 🌌 setting: a new one on every load, or always the one you pick (saved with the ⏱ setting; `?space=1..6` in the address overrides it). Drag the hull name to move the ship; positions are kept in `~/.hivey/agent-map/fleet-settings.json` with the ⏱ setting. Open, compact and clear reach the agent through its own session's socket. The details panel (right-click an agent, or ⓘ) has a 📚 Wiki section: the agent's own `<name>-wiki/` (in its folder, or the folder named after its space under `~/agents` or `~/swarms`), its 8 newest pages and reports and its latest `log.md` entries; click one to open it in Obsidian (`obsidian://open`; a wiki that is not an Obsidian vault yet opens in the default Markdown app). After a /compact the context shown is the compacted size until the agent's next reply. Solo agents, extra sessions in a space and
189
190
  each swarm's coordinator get a desk; a swarm's workers and critics stand beside their coordinator's desk.
190
191
 
@@ -107,12 +107,18 @@ def log_path(command: str) -> str | None:
107
107
 
108
108
  def _is_err(line: str) -> bool:
109
109
  # "N Failed downloads:" is yfinance warning about delisted tickers, not a failed run
110
- return bool(re.search(r"error|traceback|exception|failed|fatal", line, re.I)
110
+ return bool(re.search(r"error|traceback|exception|failed|fatal|✗", line, re.I)
111
111
  and not re.search(r"\b0 failed|failed:? 0\b|0 errors?\b|errors?:? 0\b|rerun picks|failed downloads?:",
112
112
  line, re.I))
113
113
 
114
114
 
115
+ # an error line that names a cause (an HTTP status, a fatal git error, a Python exception...), preferred
116
+ # over headings like "Failed updates:" as the one-line reason a job failed
117
+ CAUSE_RE = re.compile(r"\b[45]\d\d\b|fatal|\w(Error|Exception)\b|denied|forbid|timed? ?out|not found|no such|"
118
+ r"unauthori[sz]ed|refused|could not|cannot|can't", re.I)
119
+
115
120
  # the first and last line of an uncaught Python traceback; an uncaught one always exits non-zero
121
+ TRACE_BODY_RE = re.compile(r'^\s*(raise\b|File "|~*\^)') # a traceback's source and caret lines
116
122
  CRASH_RE = re.compile(r"^\s*(Traceback \(most recent call last\)|[\w.]+(Error|Exception|Interrupt|Exit)\b)")
117
123
 
118
124
 
@@ -142,11 +148,14 @@ def log_info(path: str | None, exit_code: int | None = None) -> dict:
142
148
  # follows is history, not a current problem (a Baserow timeout stayed flagged after good runs)
143
149
  ok = re.compile(r"\b(success(ful(ly)?)?|succeeded|finished|completed?|done|wrote|all ok)\b", re.I)
144
150
  last_ok = max((i for i, l in enumerate(tail) if ok.search(l) and not _is_err(l)), default=-1)
145
- errs = [l.strip() for l in tail[last_ok + 1:] if _is_err(l)]
151
+ # a run that exited non-zero failed even if it printed "All done!" at the end (the nightly
152
+ # upgrade does): its error lines count wherever they are in the tail
153
+ errs = [l.strip() for l in tail[(0 if exit_code else last_ok + 1):] if _is_err(l)]
146
154
  if exit_code == 0: # the latest run exited 0, so any traceback still in the tail is from an earlier run
147
- errs = [l for l in errs if not CRASH_RE.match(l)]
155
+ errs = [l for l in errs if not CRASH_RE.match(l) and not TRACE_BODY_RE.match(l)]
148
156
  if errs:
149
- info["last_error"] = errs[-1][:200]
157
+ causes = [e for e in errs if CAUSE_RE.search(e) and not e.rstrip().endswith(":")]
158
+ info["last_error"] = (causes or errs)[-1][:200]
150
159
  info["errors"] = list(dict.fromkeys(e[:200] for e in errs))[-5:]
151
160
  info["tail"] = tail
152
161
  except OSError:
@@ -269,7 +278,8 @@ def launchd_jobs() -> list[dict]:
269
278
  jobs.append({
270
279
  "id": f"launchd:{label}", "name": re.sub(r"^com\.(jcsancho|hivey)\.", "", label), "kind": "launchd",
271
280
  "schedule": sched, "command": cmd, "agent": job_agent(cmd, d.get("WorkingDirectory")),
272
- "status": state, **log_info(d.get("StandardOutPath") or d.get("StandardErrorPath")),
281
+ "status": state, **log_info(d.get("StandardOutPath") or d.get("StandardErrorPath"),
282
+ int(code) if re.fullmatch(r"-?\d+", code) else None),
273
283
  })
274
284
  mod = jobs[-1].get("log_modified")
275
285
  if period_h and mod and dt.datetime.now() - dt.datetime.fromisoformat(mod) > dt.timedelta(hours=period_h):
@@ -155,6 +155,27 @@ main{position:relative}
155
155
  #jobs{display:none;background:#fff}
156
156
  #jobs iframe{display:block;width:100%;height:calc(100vh - 70px);border:0}
157
157
  body.v-jobs .search{visibility:hidden}
158
+ /* failing scheduled jobs, live from /hv-job-health: a banner over the jobs pages and a count on the tab */
159
+ #jobhealth{background:var(--bg);color:var(--text);padding:10px 18px;border-bottom:1px solid var(--line);max-height:46vh;overflow:auto}
160
+ #jobhealth:empty{display:none}
161
+ #jobhealth.ok{padding:6px 18px;color:var(--muted);font-size:12.5px}
162
+ #jobhealth h4{margin:0 0 6px;font-size:14px;color:var(--block)}
163
+ #jobhealth h4.soft{color:var(--honey);margin-top:10px}
164
+ #jobhealth details{border:1px solid rgba(251,113,133,.35);background:rgba(251,113,133,.07);border-radius:10px;margin:5px 0;font-size:12.5px}
165
+ #jobhealth details.soft{border-color:rgba(245,184,61,.3);background:rgba(245,184,61,.05)}
166
+ #jobhealth summary{cursor:pointer;padding:6px 10px;list-style:none;display:flex;gap:8px;align-items:baseline;flex-wrap:wrap}
167
+ #jobhealth summary::-webkit-details-marker{display:none}
168
+ #jobhealth summary b{white-space:nowrap}
169
+ #jobhealth summary .m{color:var(--muted);white-space:nowrap}
170
+ #jobhealth summary .e{color:#fecdd3;word-break:break-word}
171
+ #jobhealth details.soft summary .e{color:#fde68a}
172
+ #jobhealth .body{padding:0 10px 9px}
173
+ #jobhealth ul{margin:4px 0;padding-left:18px;color:#fecdd3}
174
+ #jobhealth pre{background:#0a0e15;border:1px solid var(--line);border-radius:8px;padding:8px;font:11px/1.35 ui-monospace,Menlo,monospace;
175
+ white-space:pre-wrap;max-height:220px;overflow:auto;color:#c9d4e3;margin:6px 0 0}
176
+ #views .jbad{margin-left:5px;padding:0 6px;border-radius:999px;background:var(--block);color:#1b0b10;font-size:11px;font-weight:700}
177
+ #views .jbad.soft{background:var(--honey)}
178
+ .ask.job{border-color:rgba(251,113,133,.5);cursor:pointer}
158
179
  #list{display:none;padding:12px 18px 40px}
159
180
  table{width:100%;border-collapse:collapse;font-size:12.5px}
160
181
  th{text-align:left;color:var(--muted);font-weight:600;padding:7px 8px;border-bottom:1px solid var(--line);cursor:pointer;white-space:nowrap;position:sticky;top:57px;background:var(--bg)}
@@ -247,7 +268,7 @@ td.j{max-width:420px}
247
268
  </section>
248
269
  <section id="board"></section>
249
270
  <section id="list"></section>
250
- <section id="jobs"><iframe id="jobsframe" title="Agent jobs"></iframe></section>
271
+ <section id="jobs"><div id="jobhealth"></div><iframe id="jobsframe" title="Agent jobs"></iframe></section>
251
272
  </main>
252
273
  <aside id="drawer"></aside>
253
274
  <div id="tip"></div>
@@ -26,6 +26,7 @@ let data = null, agents = [], selected = null;
26
26
  const ui = JSON.parse(localStorage.getItem('hv-fleet-ship') || localStorage.getItem('hv-' + 'off' + 'ice-ship') || '{}');
27
27
  ui.view ||= 'fleet';
28
28
  const VIEWS = ['fleet', 'board', 'list', 'jobs'];
29
+ let health = null, healthAt = 0; // failing scheduled jobs (pollHealth)
29
30
  { const v = new URLSearchParams(location.search).get('view'); if (VIEWS.includes(v)) ui.view = v; if (v) history.replaceState(null, '', location.pathname); } // ?view=jobs from the menu or a jobs page
30
31
  ui.filter ||= null;
31
32
  if (ui.toon === undefined) ui.toon = false;
@@ -219,10 +220,15 @@ function renderInbox() {
219
220
  const asked = agents.filter(a => !a.asleep && a.status !== 'blocked' && a.status !== 'working' && a.summary?.needs_you);
220
221
  const need = [...blocked, ...asked];
221
222
  const lead = [blocked.length ? `✋ ${blocked.length} blocked` : '', asked.length ? `<span style="color:var(--honey)">💬 ${asked.length} asked you</span>` : ''].filter(Boolean).join('<br>');
222
- $('#inbox').innerHTML = need.length ? `<span class="lead">${lead}</span>` + need.map(a =>
223
+ const failed = health?.failed || [];
224
+ const jobs = failed.length ? `<div class="ask job" id="jobchip" title="Open the Jobs tab: what failed and its log"><span class="em">❌</span>
225
+ <div class="t"><b>${failed.length} scheduled job${failed.length === 1 ? '' : 's'} failing</b>${esc(failed.slice(0, 3).map(j => j.name).join(', ') + (failed.length > 3 ? '…' : ''))}</div><span class="go">jobs ↗</span></div>` : '';
226
+ $('#inbox').innerHTML = (need.length ? `<span class="lead">${lead}</span>` + need.map(a =>
223
227
  `<div class="ask ${a.status === 'blocked' ? '' : 'soft'}" data-id="${esc(a.id)}" title="Click: open in hivey · right-click: details"><span class="em">${esc(a.emoji)}</span>
224
- <div class="t"><b>${esc(a.name)}</b>${esc(a.summary?.needs_you || a.summary?.bubble || 'waiting in its terminal')}</div><span class="go">open ↗</span></div>`).join('') : '';
228
+ <div class="t"><b>${esc(a.name)}</b>${esc(a.summary?.needs_you || a.summary?.bubble || 'waiting in its terminal')}</div><span class="go">open ↗</span></div>`).join('') : '') + jobs;
225
229
  wireActions($('#inbox'));
230
+ const chip = $('#jobchip');
231
+ if (chip) chip.onclick = () => { ui.view = 'jobs'; save(); renderAll(); };
226
232
  }
227
233
 
228
234
  // ---------------------------------------------------------------- board & list
@@ -948,6 +954,7 @@ function showJobs() {
948
954
  document.body.classList.toggle('v-jobs', on);
949
955
  $('#jobs').style.display = on ? 'block' : 'none';
950
956
  if (!on) return;
957
+ if (Date.now() - healthAt > 60000) pollHealth();
951
958
  if (!frame.dataset.loaded) { // an older page server has no /hv-jobs: the latest map straight away
952
959
  frame.dataset.loaded = '1';
953
960
  fetch('/hv-jobs', { cache: 'no-store' }).then(r => { frame.src = r.ok ? r.url : '/latest/agent-map.html'; })
@@ -955,6 +962,45 @@ function showJobs() {
955
962
  }
956
963
  fitJobs();
957
964
  }
965
+ // scheduled jobs that failed (non-zero exit) or need a check, live from the page server: a count on the
966
+ // Jobs tab, a chip in the top strip and a banner over the jobs pages (the nightly report is a day old)
967
+ async function pollHealth() {
968
+ healthAt = Date.now();
969
+ try {
970
+ const r = await fetch('/hv-job-health', { cache: 'no-store' });
971
+ if (!r.ok) return; // an older page server has no /hv-job-health
972
+ health = await r.json();
973
+ } catch { return; }
974
+ renderHealth();
975
+ renderInbox();
976
+ }
977
+ function healthRow(j, soft) {
978
+ const err = j.error || j.words || j.status;
979
+ const errs = (j.errors || []).filter(e => e !== j.error);
980
+ return `<details class="${soft ? 'soft' : ''}"><summary><b>${soft ? '⚠️' : '❌'} ${esc(j.name)}</b>
981
+ <span class="m">${esc(j.status)} · ${esc(j.kind.split(' ')[0])} ${esc(j.schedule)}${j.when ? ' · ' + esc(String(j.when).replace('T', ' ')) : ''}</span>
982
+ <span class="e">${esc(err)}</span></summary><div class="body">
983
+ ${errs.length ? `<ul>${errs.map(e => `<li>${esc(e)}</li>`).join('')}</ul>` : ''}
984
+ ${j.log ? `<div class="m">log: <code>${esc(j.log)}</code></div>` : '<div class="m">no log file</div>'}
985
+ ${j.tail?.length ? `<pre>${esc(j.tail.join('\n'))}</pre>` : ''}</div></details>`;
986
+ }
987
+ function renderHealth() {
988
+ const btn = document.querySelector('#views button[data-v="jobs"]'), box = $('#jobhealth');
989
+ if (!btn || !box || !health) return;
990
+ const failed = health.failed || [], check = health.check || [];
991
+ btn.innerHTML = '📊 Jobs' + (failed.length ? `<span class="jbad" title="${failed.length} scheduled job(s) failed on their last run">${failed.length}</span>`
992
+ : check.length ? `<span class="jbad soft" title="${check.length} scheduled job(s) need a check">${check.length}</span>` : '');
993
+ const at = health.checked ? new Date(health.checked).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '';
994
+ box.classList.toggle('ok', health.ok && !failed.length && !check.length);
995
+ if (!health.ok) box.innerHTML = `<span class="err">Could not check the scheduled jobs: ${esc(health.error || '?')}</span>`;
996
+ else if (!failed.length && !check.length) box.innerHTML = `✅ All ${health.total} scheduled jobs ran cleanly · checked ${at}`;
997
+ else box.innerHTML =
998
+ (failed.length ? `<h4>❌ ${failed.length} scheduled job${failed.length === 1 ? '' : 's'} failed on the last run <span class="m" style="font-weight:400;color:var(--muted)">· checked ${at} · click one for its errors and log</span></h4>` + failed.map(j => healthRow(j, false)).join('') : '') +
999
+ (check.length ? `<details style="border:0;background:none"><summary><h4 class="soft" style="margin:6px 0 0">⚠️ ${check.length} more to check (not loaded, missed a run, or errors in the log but exited ok)</h4></summary>` + check.map(j => healthRow(j, true)).join('') + '</details>' : '');
1000
+ fitJobs();
1001
+ }
1002
+ pollHealth();
1003
+ setInterval(pollHealth, 5 * 60 * 1000);
958
1004
  function fitJobs() {
959
1005
  const frame = $('#jobsframe');
960
1006
  if (ui.view === 'jobs') frame.style.height = Math.max(420, innerHeight - frame.getBoundingClientRect().top) + 'px';
@@ -674,6 +674,61 @@ def write(data: dict) -> None:
674
674
  os.replace(tmp, OUT / "fleet.json")
675
675
 
676
676
 
677
+ # A fleet tab already open in Chrome is reloaded and brought to the front; otherwise Chrome
678
+ # opens it in a new window of its own (not a tab in one of the user's windows). Without Chrome (or without permission to script it) the default browser opens it.
679
+ CHROME_FOCUS_SCRIPT = """
680
+ on run argv
681
+ set theURL to item 1 of argv
682
+ tell application "Google Chrome"
683
+ repeat with w in windows
684
+ set i to 0
685
+ repeat with t in tabs of w
686
+ set i to i + 1
687
+ set u to URL of t
688
+ if (u starts with "http://127.0.0.1:" or u starts with "http://localhost:") and (u contains "/fleet" or u contains "/office") then
689
+ try
690
+ set minimized of w to false
691
+ end try
692
+ set active tab index of w to i
693
+ set index of w to 1
694
+ tell t to reload
695
+ activate
696
+ return "refreshed the open tab"
697
+ end if
698
+ end repeat
699
+ end repeat
700
+ set w to make new window
701
+ set URL of active tab of w to theURL
702
+ activate
703
+ return "opened a new Chrome window"
704
+ end tell
705
+ end run
706
+ """
707
+
708
+
709
+ def chrome_running() -> bool:
710
+ p = subprocess.run(["pgrep", "-x", "Google Chrome"], capture_output=True)
711
+ return p.returncode == 0
712
+
713
+
714
+ def show_in_browser(url: str) -> str:
715
+ """Puts the fleet page in front of the user: the open Chrome tab refreshed, or a new window."""
716
+ if sys.platform == "darwin":
717
+ if chrome_running():
718
+ try:
719
+ p = subprocess.run(["osascript", "-e", CHROME_FOCUS_SCRIPT, url],
720
+ capture_output=True, text=True, timeout=20)
721
+ if p.returncode == 0:
722
+ return p.stdout.strip() or "opened in Chrome"
723
+ except subprocess.TimeoutExpired:
724
+ pass
725
+ elif subprocess.run(["open", "-na", "Google Chrome", "--args", "--new-window", url],
726
+ capture_output=True).returncode == 0:
727
+ return "opened a new Chrome window"
728
+ subprocess.run(["open", url], capture_output=True)
729
+ return "opened in the default browser"
730
+
731
+
677
732
  def open_page(model: str) -> int:
678
733
  import serve
679
734
  data = OUT / "fleet.json"
@@ -687,8 +742,8 @@ def open_page(model: str) -> int:
687
742
  if not fresh:
688
743
  serve.request_fleet_refresh(port)
689
744
  url = f"http://127.0.0.1:{port}/fleet/"
690
- subprocess.run(["open", url], capture_output=True)
691
- print(f"agent fleet: {url}")
745
+ how = show_in_browser(url)
746
+ print(f"agent fleet: {url} ({how})")
692
747
  return 0
693
748
 
694
749
 
@@ -8,6 +8,9 @@ trigger them:
8
8
  GET /hv-jobs the agent jobs pages for the fleet page's Jobs tab: a redirect to the latest
9
9
  map (else stats, logs, sessions); with no report yet it starts the first build
10
10
  (`agent_map.py open --no-open`) and answers a page that reloads until it is ready
11
+ GET /hv-job-health scheduled jobs whose latest run failed (non-zero exit) or needs a check (not
12
+ loaded, missed its run, errors in its log), from a jobs-only scan (~0.1 s, no
13
+ model), with each one's error lines and log tail: the Jobs tab's warnings
11
14
  POST /hv-refresh `agent_map.py refresh` (free: no model)
12
15
  GET /fleet/ the agent fleet page (files in reports/fleet/; old /fleet/ links redirect here)
13
16
  POST /hv-fleet-refresh `fleet.py run` in the background (the agent fleet, /fleet/)
@@ -56,7 +59,7 @@ IDLE_SECONDS = 2 * 3600
56
59
  PING = "/hv-ping"
57
60
  LEGACY_PAGE = "/office" # the fleet page's address before it was renamed; redirected to /fleet/
58
61
  MARK = b"hivey-agent-map"
59
- VERSION = b"fleet-16" # bump when the server gains actions, so `ensure` replaces an older one
62
+ VERSION = b"fleet-17" # bump when the server gains actions, so `ensure` replaces an older one
60
63
  FLEET_EVERY = 300 # seconds between full fleet refreshes (every terminal re-summarized) while its page is open
61
64
  FLEET_LIVE = 60 # seconds between live passes (status, context, screen; only changed statuses summarized)
62
65
  FLEET_WATCHED = 600 # the page counts as open for this long after its last poll
@@ -508,8 +511,34 @@ class Handler(http.server.SimpleHTTPRequestHandler):
508
511
  Handler.fleet_polled = time.time()
509
512
  if self.path.split("?")[0] == "/hv-jobs":
510
513
  return self.jobs()
514
+ if path == "/hv-job-health":
515
+ return self.job_health()
511
516
  return super().do_GET()
512
517
 
518
+ def job_health(self) -> None:
519
+ """Failing scheduled jobs, live (the nightly report is up to a day old)."""
520
+ port = self.server.server_address[1]
521
+ if self.headers.get("Host") not in (f"127.0.0.1:{port}", f"localhost:{port}"): # log tails stay local
522
+ return self.answer(403, b'{"ok":false,"error":"local pages only"}')
523
+ try:
524
+ import agent_map
525
+ import report
526
+ jobs = agent_map.cron_jobs() + agent_map.launchd_jobs()
527
+ except Exception as e: # a broken scan must not take the fleet page down
528
+ return self.answer(200, json.dumps({"ok": False, "error": str(e)[:300]}).encode())
529
+ out = {"ok": True, "checked": time.strftime("%Y-%m-%dT%H:%M"), "total": len(jobs), "failed": [], "check": []}
530
+ for j in jobs:
531
+ emo, words = report.job_state(j)
532
+ if emo not in ("❌", "⚠️"):
533
+ continue
534
+ failed = j.get("status", "").startswith("exit")
535
+ out["failed" if failed else "check"].append({
536
+ "name": j["name"], "kind": j["kind"], "schedule": j.get("schedule", ""), "status": j.get("status"),
537
+ "words": words, "error": j.get("last_error", ""), "errors": j.get("errors", []),
538
+ "log": j.get("log", ""), "when": j.get("last_run") or j.get("log_modified") or "",
539
+ "tail": (j.get("tail") or [])[-15:]})
540
+ return self.answer(200, json.dumps(out).encode())
541
+
513
542
  def jobs(self) -> None:
514
543
  """The fleet page's Jobs tab: the latest agent jobs page, or the first report being built."""
515
544
  import report