@hivey/cli 0.9.53 → 0.9.57

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.53",
3
+ "version": "0.9.57",
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",
@@ -130,7 +130,11 @@ hivey agent-map schedule install [--at 06:30] [--model haiku] # | remove | sta
130
130
  People chatting with agents (Claude Code, Codex, Grok in a terminal; snapshot `interactive`, with one
131
131
  entry per session) go to **`agent-sessions.html`**: cost by agent and by day, the costliest sessions with
132
132
  their peak context (⚠️ over 300k tokens), length and first message, and tips to spend less.
133
- - **Refresh:** `hivey agent-map open` serves the pages from 127.0.0.1 (`serve.py`, port 8754 or any
133
+ - **Open:** `hivey agent-map open` (hivey menu → agent map) opens `http://127.0.0.1:42817/latest/agent-map.html`
134
+ (the map first; the stats page when there is no map yet). With no report yet it builds the pages without
135
+ a model in seconds, opens them, then draws the map in the background (`first-run.json` stops a second
136
+ click from starting another build). If a stats page fails, the logs and sessions pages still publish.
137
+ - **Refresh:** `hivey agent-map open` serves the pages from 127.0.0.1 (`serve.py`, port 42817 (unregistered, below macOS's temporary ports) or any
134
138
  free one, in `~/.hivey/agent-map/server.json`; stops after 2 h unused) so the navbar's ↻ Refresh
135
139
  button works: it runs `agent_map.py refresh` (new scan into the latest report's pages, no model, a few
136
140
  seconds; the map keeps the night's boxes) and reloads. Only the served pages can trigger it (Origin
@@ -563,6 +563,9 @@ def describe_markdown(path: Path) -> str:
563
563
  return ""
564
564
  fm = re.match(r"---\n(.*?)\n---", text, re.S)
565
565
  if fm:
566
+ m = re.search(r"^description:[ \t]*[>|]-?[ \t]*\n((?:[ \t]+.*\n?)+)", fm.group(1) + "\n", re.M)
567
+ if m: # folded or literal block: the indented lines
568
+ return first_sentence(" ".join(l.strip() for l in m.group(1).splitlines()))
566
569
  m = re.search(r"^description:\s*\"?(.+?)\"?\s*$", fm.group(1), re.M)
567
570
  if m:
568
571
  return first_sentence(m.group(1))
@@ -28,6 +28,11 @@ STAGE_HELP = {
28
28
  "outputs": "What leaves the system: posts, messages, published files.",
29
29
  }
30
30
 
31
+ # The tab icon: hivey's logo (assets/logo.svg), embedded so the pages need no other file.
32
+ FAVICON = ('<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,'
33
+ "%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' rx='9' "
34
+ "fill='%239befc8'/%3E%3Cpath d='M10 9h7v9h6V9h7v23h-7V22h-6v10h-7z' fill='%23122319'/%3E%3C/svg%3E\">")
35
+
31
36
  NAV_CSS = """
32
37
  .hv-nav{position:relative;z-index:50;display:flex;flex-wrap:wrap;gap:4px;align-items:center;justify-content:flex-start;
33
38
  padding:6px 16px;font:600 13px/1.2 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;
@@ -85,7 +90,8 @@ catch(e){clearInterval(tick);b.disabled=false;b.textContent='refresh failed: ser
85
90
  def inject(page: str, css: str, top: str, script: str = "") -> str:
86
91
  """Adds hivey's pieces, each wrapped in <!--hv--> markers so a rerun replaces them."""
87
92
  page = re.sub(r"<!--hv-->.*?<!--/hv-->", "", page, flags=re.S)
88
- page = page.replace("</head>", f"<!--hv--><style>{css}</style><!--/hv--></head>", 1)
93
+ page = re.sub(r"<link\b[^>]*\brel=[\"']?(?:shortcut )?icon\b[^>]*>", "", page, flags=re.I) # hivey's icon only
94
+ page = page.replace("</head>", f"<!--hv-->{FAVICON}<style>{css}</style><!--/hv--></head>", 1)
89
95
  m = re.search(r"<body[^>]*>", page)
90
96
  if m:
91
97
  page = page[: m.end()] + f"<!--hv-->{top}<!--/hv-->" + page[m.end():]
@@ -19,6 +19,7 @@ import re
19
19
  import shutil
20
20
  import subprocess
21
21
  import sys
22
+ import time
22
23
  from pathlib import Path
23
24
 
24
25
  HOME = Path.home()
@@ -336,6 +337,7 @@ def write_logs_page(snap: dict, folder: Path) -> None:
336
337
  NAV, NAV_CSS = enhance.nav("agent-logs.html", snap['generated']), enhance.NAV_CSS
337
338
  page = f"""<!doctype html><html lang=en><meta charset=utf-8>
338
339
  <meta name=viewport content="width=device-width,initial-scale=1">
340
+ {enhance.FAVICON}
339
341
  <title>Agent logs · {e(snap['generated'][:16])}</title>
340
342
  <style>
341
343
  :root{{--bg:#fff;--fg:#1d2330;--mute:#667085;--line:#e4e7ec;--card:#f8f9fb;--accent:#2f6fec;--pre:#f2f4f7}}
@@ -546,7 +548,7 @@ def nightly(scan, days: int, model: str, use_llm: bool) -> int:
546
548
  enhance.enhance_folder(folder, json.loads((folder / "snapshot.json").read_text()), job_state)
547
549
  except Exception as e: # the pages still work without hivey's layer
548
550
  log(folder, f"enhance failed: {e}")
549
- if ok:
551
+ if ok or (folder / "agent-logs.html").is_file(): # a failed stats page still publishes logs and sessions
550
552
  tmp = REPORTS / ".latest-new"
551
553
  if tmp.is_symlink() or tmp.exists():
552
554
  tmp.unlink()
@@ -586,9 +588,11 @@ def refresh(scan, days: int, model: str) -> int:
586
588
  # ---------------------------------------------------------------- open
587
589
 
588
590
  def latest_report() -> Path | None:
589
- if LATEST.exists() and (LATEST / "agent-stats.html").is_file():
591
+ def has_pages(p: Path) -> bool:
592
+ return (p / "agent-stats.html").is_file() or (p / "agent-logs.html").is_file()
593
+ if LATEST.exists() and has_pages(LATEST):
590
594
  return LATEST.resolve()
591
- folders = sorted(p for p in REPORTS.glob("*-*-*-*") if (p / "agent-stats.html").is_file()) if REPORTS.is_dir() else []
595
+ folders = sorted(p for p in REPORTS.glob("*-*-*-*") if has_pages(p)) if REPORTS.is_dir() else []
592
596
  return folders[-1] if folders else None
593
597
 
594
598
 
@@ -598,25 +602,61 @@ def notify(text: str) -> None:
598
602
  capture_output=True)
599
603
 
600
604
 
605
+ PAGES = ("agent-map.html", "agent-stats.html", "agent-logs.html", "agent-sessions.html") # the first one found opens
606
+ FIRST_RUN = STATE / "first-run.json"
607
+
608
+
609
+ def open_page(folder: Path) -> bool:
610
+ """Open the map (else the first page there is) from the local server, so Refresh works; the
611
+ navbar reaches the other pages. Without the server, the file itself."""
612
+ page = next((p for p in PAGES if (folder / p).is_file()), None)
613
+ if not page:
614
+ return False
615
+ import serve
616
+ port = serve.ensure()
617
+ rel = "latest" if LATEST.exists() and LATEST.resolve() == folder.resolve() else folder.name
618
+ target = f"http://127.0.0.1:{port}/{rel}/{page}" if port else str(folder / page)
619
+ p = subprocess.run(["open", target], capture_output=True, text=True)
620
+ if p.returncode:
621
+ notify(f"Could not open the agent map: {(p.stderr or '').strip()[:120]}")
622
+ return False
623
+ print(f"opened {target}")
624
+ return True
625
+
626
+
627
+ def first_run_busy() -> bool:
628
+ try:
629
+ info = json.loads(FIRST_RUN.read_text())
630
+ os.kill(int(info["pid"]), 0)
631
+ return time.time() - info.get("started", 0) < 1800
632
+ except (OSError, ValueError, KeyError, TypeError):
633
+ return False
634
+
635
+
601
636
  def open_latest(model: str) -> int:
602
637
  folder = latest_report()
603
638
  if folder:
604
- import serve # served from 127.0.0.1 so the pages' Refresh button works; else the files
605
- port = serve.ensure()
606
- base = f"http://127.0.0.1:{port}/{os.path.relpath(LATEST if LATEST.exists() else folder, REPORTS)}/" \
607
- if port else None
608
- for page in ("agent-stats.html", "agent-map.html", "agent-logs.html", "agent-sessions.html"):
609
- if (folder / page).is_file():
610
- subprocess.run(["open", base + page if base else str(folder / page)], capture_output=True)
611
- print(f"opened {base or folder}")
639
+ return 0 if open_page(folder) else 1
640
+ # No report yet: the pages without a model first (seconds), open them, then the map in the background.
641
+ if first_run_busy(): # a second click while the first report is being built
642
+ notify("Your first agent map is still being built; it opens when ready.")
612
643
  return 0
613
- # No report yet: build the first one in the background and open it when it is ready.
614
644
  REPORTS.mkdir(parents=True, exist_ok=True)
645
+ FIRST_RUN.write_text(json.dumps({"pid": os.getpid(), "started": time.time()}))
646
+ notify("Building your first agent map (a few seconds)…")
615
647
  with open(STATE / "first-run.log", "a") as fh:
616
- subprocess.Popen([sys.executable, "-I", str(SCRIPTS / "agent_map.py"), "nightly", "--model", model, "--open"],
617
- stdout=fh, stderr=fh, stdin=subprocess.DEVNULL, start_new_session=True)
618
- notify("Building your first agent map (a few minutes); it opens when ready.")
619
- print("no report yet: building the first one in the background (log: ~/.hivey/agent-map/first-run.log)")
648
+ subprocess.run([sys.executable, "-I", str(SCRIPTS / "agent_map.py"), "refresh"], stdout=fh, stderr=fh,
649
+ stdin=subprocess.DEVNULL, timeout=600)
650
+ folder = latest_report()
651
+ if folder:
652
+ open_page(folder)
653
+ # the map needs the model: drawn in the background; the page's Refresh (or reopening) shows it
654
+ bg = subprocess.Popen([sys.executable, "-I", str(SCRIPTS / "agent_map.py"), "nightly", "--model", model],
655
+ stdout=fh, stderr=fh, stdin=subprocess.DEVNULL, start_new_session=True)
656
+ FIRST_RUN.write_text(json.dumps({"pid": bg.pid, "started": time.time()}))
657
+ if folder:
658
+ notify("Stats, logs and sessions are open; the map is being drawn (a few minutes).")
659
+ print("first report: pages built; the map is being drawn in the background (log: ~/.hivey/agent-map/first-run.log)")
620
660
  return 0
621
661
 
622
662
 
@@ -22,7 +22,7 @@ STATE = Path.home() / ".hivey" / "agent-map"
22
22
  REPORTS = STATE / "reports"
23
23
  INFO = STATE / "server.json"
24
24
  SCRIPTS = Path(__file__).resolve().parent
25
- PREFERRED_PORT = 8754
25
+ PREFERRED_PORT = 42817 # unregistered and below macOS's temporary-port range, so no other app picks it
26
26
  IDLE_SECONDS = 2 * 3600
27
27
  PING = "/hv-ping"
28
28
  MARK = b"hivey-agent-map"
@@ -40,11 +40,27 @@ def running() -> int | None:
40
40
  return None
41
41
 
42
42
 
43
+ def port_free(port: int) -> bool:
44
+ import socket
45
+ with socket.socket() as sock:
46
+ try:
47
+ sock.bind(("127.0.0.1", port))
48
+ return True
49
+ except OSError:
50
+ return False
51
+
52
+
43
53
  def ensure() -> int | None:
44
54
  """The running server's port, starting one in the background when there is none."""
45
55
  port = running()
46
- if port:
56
+ if port and (port == PREFERRED_PORT or not port_free(PREFERRED_PORT)):
47
57
  return port
58
+ if port: # an older server on another port while ours is free: replace it
59
+ try:
60
+ os.kill(int(json.loads(INFO.read_text())["pid"]), 15)
61
+ time.sleep(0.3)
62
+ except (OSError, ValueError, KeyError, TypeError):
63
+ pass
48
64
  STATE.mkdir(parents=True, exist_ok=True)
49
65
  with open(STATE / "server.log", "a") as fh:
50
66
  subprocess.Popen([sys.executable, "-I", str(SCRIPTS / "agent_map.py"), "serve"], stdin=subprocess.DEVNULL,
@@ -116,6 +116,7 @@ def write_sessions_page(snap: dict, folder: Path) -> None:
116
116
  NAV, NAV_CSS = enhance.nav("agent-sessions.html", snap.get('generated', '')), enhance.NAV_CSS
117
117
  page = f"""<!doctype html><html lang=en><meta charset=utf-8>
118
118
  <meta name=viewport content="width=device-width,initial-scale=1">
119
+ {enhance.FAVICON}
119
120
  <title>Interactive sessions · {e(snap.get('generated', '')[:16])}</title>
120
121
  <style>
121
122
  :root{{--bg:#fff;--fg:#1d2330;--mute:#667085;--line:#e4e7ec;--card:#f8f9fb;--accent:#2f6fec}}
@@ -1,6 +1,14 @@
1
1
  ---
2
2
  name: hivey-grok
3
- description: Run tasks with xAI's Grok Build CLI (`grok`, installed at ~/.grok/bin/grok) headless through a bundled uv Python runner — research questions (web search, "what's X/Twitter saying about…", trend scans with source links), quick answers, structured JSON extraction, or coding work in a folder — then check the result and report cost. Also manages grok itself: models, sessions, resuming, login, usage limits, updates, config and docs. Use whenever the user says "grok", "ask Grok", "with Grok", "grok -p", wants a Grok/xAI second opinion, or wants a Grok-powered scan of X/Twitter discussion, even if they don't say "CLI". Not for the grok.com web app in Chrome (use grok-research / deep-research-duo) and not for calling the xAI API from code.
3
+ description: >-
4
+ Run tasks with xAI's Grok Build CLI (`grok`, installed at ~/.grok/bin/grok) headless through a
5
+ bundled uv Python runner — research questions (web search, "what's X/Twitter saying about…", trend
6
+ scans with source links), quick answers, structured JSON extraction, or coding work in a folder —
7
+ then check the result and report cost. Also manages grok itself: models, sessions, resuming, login,
8
+ usage limits, updates, config and docs. Use whenever the user says "grok", "ask Grok", "with Grok",
9
+ "grok -p", wants a Grok/xAI second opinion, or wants a Grok-powered scan of X/Twitter discussion,
10
+ even if they don't say "CLI". Not for the grok.com web app in Chrome (use grok-research /
11
+ deep-research-duo) and not for calling the xAI API from code.
4
12
  ---
5
13
 
6
14
  > Local additions: if `EXTRA_SKILL.md` exists in this skill's folder, read it too and follow it.