@hivey/cli 0.9.63 → 0.9.65

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.
@@ -10,7 +10,7 @@ For each desk it reads two things:
10
10
  context size (input + cache tokens of the last reply), model, your last prompt, the
11
11
  session's recap (away_summary) and its last replies
12
12
 
13
- Sonnet (`claude -p --model sonnet`, no tools, no session saved) turns them into a short summary per
13
+ Haiku (`claude -p --model haiku`, no tools, no session saved) turns them into a short summary per
14
14
  desk: the current job, a speech-bubble line, what it achieved, what it waits for and whether to keep,
15
15
  /compact or /clear the conversation. Only desks whose terminal or log changed since the last run are
16
16
  sent again, in batches, so 100 agents cost a few calls per refresh. Without a model (--no-llm, or the
@@ -19,7 +19,7 @@ call fails) the summary comes from the recap and the last prompt.
19
19
  Output: ~/.hivey/agent-map/reports/office/office.json, read by office.html (Three.js, vendored), served
20
20
  by serve.py, which reruns this every 5 minutes while the page is open. Python standard library only.
21
21
 
22
- office.py run [--no-llm] [--model sonnet] one refresh
22
+ office.py run [--no-llm] [--quick] [--model haiku] one refresh (--quick: the 1-minute live pass)
23
23
  office.py open start the server, refresh if stale, open the page
24
24
  """
25
25
  from __future__ import annotations
@@ -48,7 +48,7 @@ STATE = HOME / ".hivey" / "agent-map"
48
48
  OUT = STATE / "reports" / "office"
49
49
  CACHE = STATE / "office-cache.json"
50
50
  LOCK = STATE / "office.lock"
51
- RUN_DIR = STATE / "office-run" # neutral cwd for the sonnet calls (no CLAUDE.md, no project)
51
+ RUN_DIR = STATE / "office-run" # neutral cwd for the model calls (no CLAUDE.md, no project)
52
52
 
53
53
  STANDARD_WINDOW = 200_000
54
54
  LARGE_WINDOW = 1_000_000
@@ -66,9 +66,22 @@ def hivey_bin() -> str | None:
66
66
  return exe if exe and os.path.isfile(exe) else shutil.which("hivey")
67
67
 
68
68
 
69
- def sh(cmd: list[str], timeout: int = 15) -> str:
69
+ INHERITED = ("HERDR_SOCKET_PATH", "HERDR_CLIENT_SOCKET_PATH", "HERDR_SESSION", "HERDR_PANE_ID", "HERDR_TAB_ID",
70
+ "HERDR_WORKSPACE_ID", "HERDR_PANE_RUNTIME_ID")
71
+
72
+
73
+ def hv_env(sock: str | None) -> dict | None:
74
+ """The environment that points a hivey command at one session's server (None: inherit ours)."""
75
+ if not sock:
76
+ return None
77
+ env = {k: v for k, v in os.environ.items() if k not in INHERITED}
78
+ env["HERDR_SOCKET_PATH"] = sock
79
+ return env
80
+
81
+
82
+ def sh(cmd: list[str], timeout: int = 15, sock: str | None = None) -> str:
70
83
  try:
71
- return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout
84
+ return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, env=hv_env(sock)).stdout
72
85
  except (OSError, subprocess.SubprocessError):
73
86
  return ""
74
87
 
@@ -83,11 +96,25 @@ def now_iso() -> str:
83
96
 
84
97
  # ---------------------------------------------------------------- who is in the office
85
98
 
86
- def spaces(hv: str) -> dict:
99
+ def hv_sessions(hv: str) -> list[dict]:
100
+ """Every named hivey session: [{name, running, default, socket}] (the default one first)."""
101
+ try:
102
+ got = json.loads(sh([hv, "session", "list", "--json"]) or "{}").get("sessions") or []
103
+ except (ValueError, AttributeError):
104
+ got = []
105
+ out = [{"name": s.get("name") or "default", "running": bool(s.get("running")), "default": bool(s.get("default")),
106
+ "socket": s.get("socket_path"), "dir": s.get("session_dir")} for s in got if isinstance(s, dict)]
107
+ if not out: # an older hivey without sessions: the server we are attached to
108
+ out = [{"name": "default", "running": True, "default": True, "socket": None}]
109
+ out.sort(key=lambda s: (not s["default"], not s["running"], s["name"]))
110
+ return out
111
+
112
+
113
+ def spaces(hv: str, sock: str | None = None) -> dict:
87
114
  """workspace id → {label, emoji, name, about}."""
88
115
  out = {}
89
116
  try:
90
- data = json.loads(sh([hv, "workspace", "list"]) or "{}")
117
+ data = json.loads(sh([hv, "workspace", "list"], sock=sock) or "{}")
91
118
  except ValueError:
92
119
  return out
93
120
  for w in data.get("result", {}).get("workspaces", []):
@@ -102,14 +129,17 @@ def spaces(hv: str) -> dict:
102
129
  return out
103
130
 
104
131
 
105
- def desks(hv: str) -> list[dict]:
106
- """One entry per agent you talk to; swarm workers/critics/scripts fold into their coordinator."""
132
+ def desks(hv: str, hs: dict | None = None) -> list[dict]:
133
+ """One entry per agent you talk to; swarm workers/critics/scripts fold into their coordinator.
134
+ hs: the hivey session to read (default: the one we are attached to)."""
135
+ hs = hs or {"name": "default", "default": True, "socket": None}
136
+ sock = hs.get("socket")
107
137
  try:
108
- data = json.loads(sh([hv, "agent", "list"]) or "{}")
138
+ data = json.loads(sh([hv, "agent", "list"], sock=sock) or "{}")
109
139
  except ValueError:
110
140
  return []
111
141
  agents = data.get("result", {}).get("agents", [])
112
- rooms = spaces(hv)
142
+ rooms = spaces(hv, sock)
113
143
  team: dict[str, list] = {}
114
144
  for a in agents:
115
145
  tok = a.get("tokens") or {}
@@ -132,7 +162,8 @@ def desks(hv: str) -> list[dict]:
132
162
  sess = a.get("agent_session") or {}
133
163
  title = re.sub(r"^\W+\s*", "", a.get("title") or "")
134
164
  out.append({
135
- "id": a.get("pane_id"), "pane": a.get("pane_id"), "workspace": ws, "space": room["name"],
165
+ "id": a.get("pane_id") if hs.get("default") else f"{hs['name']}/{a.get('pane_id')}",
166
+ "pane": a.get("pane_id"), "hv_session": hs["name"], "sock": sock, "workspace": ws, "space": room["name"],
136
167
  "space_label": room["label"], "emoji": room["emoji"], "about": room["about"] if master else "",
137
168
  "name": name, "role": "coordinator" if members else ("agent" if master else "session"),
138
169
  "cli": CLIS.get(a.get("agent"), a.get("agent") or "?"), "cli_id": a.get("agent"),
@@ -148,11 +179,48 @@ def desks(hv: str) -> list[dict]:
148
179
  return out
149
180
 
150
181
 
182
+ def asleep_desks(hs: dict) -> list[dict]:
183
+ """The agents of a stopped hivey session, from the layout it saved (session.json): they sit powered down
184
+ at their desks; their context and last work still come from their session logs."""
185
+ try:
186
+ path = Path(hs.get("dir") or "") / "session.json"
187
+ saved = json.loads(path.read_text())
188
+ stopped_at = dt.datetime.fromtimestamp(path.stat().st_mtime, dt.timezone.utc).isoformat(timespec="seconds")
189
+ except (OSError, ValueError, TypeError):
190
+ return []
191
+ out = []
192
+ for w in saved.get("workspaces") or []:
193
+ if not isinstance(w, dict):
194
+ continue
195
+ ws, label = w.get("id", ""), w.get("custom_name") or w.get("id", "")
196
+ m = re.match(r"^(\W+?)\s+(.+)$", label)
197
+ emoji, space = (m.group(1).strip(), m.group(2)) if m else ("🐝", label)
198
+ panes = [(pid, p) for t in w.get("tabs") or [] for pid, p in (t.get("panes") or {}).items()
199
+ if isinstance(p, dict) and (p.get("agent_session") or {}).get("value")]
200
+ leads = [x for x in panes if not x[1].get("managed_agent_kind")] or panes[:1]
201
+ crew = [x for x in panes if x not in leads]
202
+ for n, (pid, p) in enumerate(leads, 1):
203
+ sess = p["agent_session"]
204
+ members = [{"name": c.get("agent_name") or f"pane {cid}", "role": (c.get("agent_name") or "").rsplit("-", 1)[-1] or "worker",
205
+ "status": "idle"} for cid, c in crew] if n == 1 else []
206
+ name = p.get("agent_name") or (space if len(leads) == 1 else f"{space} · session {n}")
207
+ pane = f"{ws}:p{pid}"
208
+ out.append({
209
+ "id": f"{hs['name']}/{pane}", "pane": pane, "hv_session": hs["name"], "sock": None, "asleep": True,
210
+ "stopped_at": stopped_at, "workspace": f"{hs['name']}/{ws}", "space": space, "space_label": label, "emoji": emoji, "about": "",
211
+ "name": name, "role": "coordinator" if members else "agent",
212
+ "cli": CLIS.get(sess.get("agent"), sess.get("agent") or "?"), "cli_id": sess.get("agent"),
213
+ "status": "idle", "cwd": short(p.get("cwd")), "folder": p.get("cwd"), "session": sess.get("value"),
214
+ "model_hint": "", "team": members, "team_working": 0, "focused": False, "queued": False,
215
+ })
216
+ return out
217
+
218
+
151
219
  # ---------------------------------------------------------------- what each one shows
152
220
 
153
- def screen(hv: str, pane: str) -> str:
221
+ def screen(hv: str, pane: str, sock: str | None = None) -> str:
154
222
  """The bottom of the pane's terminal, cleaned for reading (no colors, no box lines, no blank runs)."""
155
- raw = sh([hv, "pane", "read", pane, "--source", "recent", "--lines", str(SCREEN_LINES)], timeout=10)
223
+ raw = sh([hv, "pane", "read", pane, "--source", "recent", "--lines", str(SCREEN_LINES)], timeout=10, sock=sock)
156
224
  lines = []
157
225
  for line in ANSI.sub("", raw).splitlines():
158
226
  line = BOX.sub(" ", line).rstrip()
@@ -208,6 +276,13 @@ def session_log(path: Path | None) -> dict:
208
276
  if kind == "last-prompt":
209
277
  info["last_prompt"] = (d.get("lastPrompt") or "")[:400]
210
278
  continue
279
+ if kind == "system" and d.get("subtype") == "compact_boundary":
280
+ # /compact (or auto-compact) shrank the context; until the next reply this is its size
281
+ meta = d.get("compactMetadata") if isinstance(d.get("compactMetadata"), dict) else {}
282
+ if meta.get("postTokens"):
283
+ info["context"] = int(meta["postTokens"])
284
+ info["compacted_at"] = d.get("timestamp")
285
+ continue
211
286
  if kind == "system" and d.get("subtype") == "away_summary":
212
287
  info["recap"] = re.sub(r"\n+DONE:.*$", "", d.get("content") or "", flags=re.S).strip()[:600]
213
288
  continue
@@ -305,7 +380,7 @@ def claude_token() -> str | None:
305
380
  return None
306
381
 
307
382
 
308
- def ask_sonnet(batch: list[dict], model: str, token: str | None) -> list[dict]:
383
+ def ask_model(batch: list[dict], model: str, token: str | None) -> list[dict]:
309
384
  claude = shutil.which("claude") or str(HOME / ".local/bin/claude")
310
385
  prompt = PROMPT + "\n\n".join(brief(d) for d in batch)
311
386
  env = dict(os.environ)
@@ -361,10 +436,12 @@ def clean_summary(s: dict) -> dict:
361
436
 
362
437
  # ---------------------------------------------------------------- one refresh
363
438
 
364
- def collect(hv: str) -> list[dict]:
365
- people = desks(hv)
439
+ def collect(hv: str, sessions: list[dict] | None = None) -> list[dict]:
440
+ """Every agent of every running hivey session (one spaceship per session on the page)."""
441
+ people = [d for hs in (sessions or hv_sessions(hv))
442
+ for d in (desks(hv, hs) if hs["running"] else asleep_desks(hs))]
366
443
  with cf.ThreadPoolExecutor(max_workers=8) as pool:
367
- screens = list(pool.map(lambda d: screen(hv, d["pane"]), people))
444
+ screens = list(pool.map(lambda d: "" if d.get("asleep") else screen(hv, d["pane"], d.get("sock")), people))
368
445
  for d, scr in zip(people, screens):
369
446
  d["screen"] = scr
370
447
  log = session_log(transcript_of(d["session"], d["cli_id"]))
@@ -379,10 +456,11 @@ def collect(hv: str) -> list[dict]:
379
456
  d["log"] = log.get("log", "")
380
457
  d["last_prompt"] = log.get("last_prompt", "")
381
458
  d["recap"] = log.get("recap", "")
459
+ d["compacted_at"] = log.get("compacted_at")
382
460
  return people
383
461
 
384
462
 
385
- def run(model: str = "sonnet", use_llm: bool = True) -> int:
463
+ def run(model: str = "haiku", use_llm: bool = True, quick: bool = False) -> int:
386
464
  hv = hivey_bin()
387
465
  if not hv:
388
466
  print("office: hivey not found", file=sys.stderr)
@@ -397,34 +475,49 @@ def run(model: str = "sonnet", use_llm: bool = True) -> int:
397
475
  print("office: a refresh is already running")
398
476
  return 0
399
477
  LOCK.unlink(missing_ok=True)
400
- return run(model, use_llm)
478
+ return run(model, use_llm, quick)
401
479
  try:
402
- return _run(hv, model, use_llm)
480
+ return _run(hv, model, use_llm, quick)
403
481
  finally:
404
482
  LOCK.unlink(missing_ok=True)
405
483
 
406
484
 
407
- def _run(hv: str, model: str, use_llm: bool) -> int:
485
+ def _run(hv: str, model: str, use_llm: bool, quick: bool = False) -> int:
486
+ """quick: the 1-minute live pass. Status, context and screen are fresh; a desk whose terminal moved
487
+ but whose status did not keeps its last summary (re-summarized at the next full pass), and only
488
+ desks whose status changed (blocked -> working, working -> done...) are sent to the model now."""
408
489
  start = time.time()
409
- people = collect(hv)
490
+ sessions = hv_sessions(hv)
491
+ people = collect(hv, sessions)
410
492
  try:
411
493
  cache = json.loads(CACHE.read_text())
412
494
  except (OSError, ValueError):
413
495
  cache = {}
414
- todo, error = [], ""
496
+ todo, error, stale = [], "", {}
415
497
  for d in people:
416
498
  d["fp"] = fingerprint(d)
417
499
  hit = cache.get(d["id"])
418
- if hit and hit.get("fp") == d["fp"] and (hit.get("by") != "fallback" or not use_llm):
500
+ if d.get("asleep") and not d["log_uuid"]: # stopped, and its session log is gone: nothing to summarize
501
+ day = dt.datetime.fromisoformat(d["stopped_at"]).astimezone().strftime("%b %-d")
502
+ crew = f" with {len(d['team'])} teammates" if d["team"] else ""
503
+ d["summary"] = {"job": f"Session {d['hv_session']} stopped", "bubble": f"💤 Asleep since {day}{crew}. Click to start session {d['hv_session']}.",
504
+ "next": f"Start session {d['hv_session']} to wake it", "needs_you": "", "done": [],
505
+ "advice": "keep", "advice_why": "its session is stopped", "by": "stopped"}
506
+ d["summarized_at"] = d["stopped_at"]
507
+ elif hit and hit.get("fp") == d["fp"] and (hit.get("by") != "fallback" or not use_llm):
419
508
  d["summary"] = hit["summary"]
420
509
  d["summarized_at"] = hit.get("at")
510
+ elif quick and hit and hit.get("status", d["status"]) == d["status"] and hit.get("by") != "fallback":
511
+ d["summary"] = hit["summary"]
512
+ d["summarized_at"] = hit.get("at")
513
+ stale[d["id"]] = hit # keep its old fingerprint so the next full pass re-summarizes it
421
514
  else:
422
515
  todo.append(d)
423
516
  if todo and use_llm:
424
517
  token = claude_token()
425
518
  batches = [todo[i:i + BATCH] for i in range(0, len(todo), BATCH)]
426
519
  with cf.ThreadPoolExecutor(max_workers=4) as pool:
427
- futures = {pool.submit(ask_sonnet, b, model, token): b for b in batches}
520
+ futures = {pool.submit(ask_model, b, model, token): b for b in batches}
428
521
  for fut in cf.as_completed(futures):
429
522
  try:
430
523
  got = {s["id"]: s for s in fut.result()}
@@ -441,10 +534,14 @@ def _run(hv: str, model: str, use_llm: bool) -> int:
441
534
  s = d["summary"]
442
535
  if d["context_pct"] >= 85 and s.get("advice") == "keep": # a model can be too gentle
443
536
  s["advice"], s["advice_why"] = "compact", f"context at {d['context_pct']}%"
537
+ if d["context_pct"] < 40 and s.get("advice") == "compact": # already compacted since that summary
538
+ s["advice"], s["advice_why"] = "keep", f"context at {d['context_pct']}% after compacting" \
539
+ if d.get("compacted_at") else f"context at {d['context_pct']}%"
444
540
  if d["status"] in ("working", "blocked") and s.get("advice") == "clear":
445
541
  s["advice"] = "keep"
446
- CACHE.write_text(json.dumps({d["id"]: {"fp": d["fp"], "summary": d["summary"], "at": d["summarized_at"],
447
- "by": d["summary"].get("by")} for d in people}))
542
+ CACHE.write_text(json.dumps({d["id"]: stale.get(d["id"]) or {
543
+ "fp": d["fp"], "summary": d["summary"], "at": d["summarized_at"], "by": d["summary"].get("by"),
544
+ "status": d["status"]} for d in people}))
448
545
  for d in people:
449
546
  log = d.pop("_log", {})
450
547
  d["tools"] = log.get("tools", [])[-5:]
@@ -453,11 +550,22 @@ def _run(hv: str, model: str, use_llm: bool) -> int:
453
550
  d.pop(k, None)
454
551
  order = {"blocked": 0, "working": 1, "done": 2, "idle": 3}
455
552
  people.sort(key=lambda d: (order.get(d["status"], 4), -d["context_pct"], d["name"]))
456
- counts = {k: sum(1 for d in people if d["status"] == k) for k in ("working", "blocked", "done", "idle")}
457
- data = {"generated": now_iso(), "seconds": round(time.time() - start, 1), "model": model if use_llm else None,
458
- "summarized": len(todo) if use_llm else 0, "error": error, "refresh_every": 300,
553
+ counts = {k: sum(1 for d in people if d["status"] == k and not d.get("asleep"))
554
+ for k in ("working", "blocked", "done", "idle")}
555
+ counts["asleep"] = sum(1 for d in people if d.get("asleep"))
556
+ full_at = now_iso()
557
+ if quick: # a live pass: the last full summary pass stays the one already on the page
558
+ try:
559
+ full_at = json.loads((OUT / "office.json").read_text()).get("full_at") or full_at
560
+ except (OSError, ValueError):
561
+ pass
562
+ data = {"generated": now_iso(), "kind": "quick" if quick else "full", "full_at": full_at, "seconds": round(time.time() - start, 1), "model": model if use_llm else None,
563
+ "summarized": len(todo) if use_llm else 0, "error": error, "refresh_every": 60,
459
564
  "counts": counts, "agents": people,
460
- "advice": {k: sum(1 for d in people if d["summary"].get("advice") == k) for k in ("compact", "clear")}}
565
+ "sessions": [{"name": hs["name"], "running": hs["running"], "default": hs["default"],
566
+ "agents": sum(1 for d in people if d["hv_session"] == hs["name"])} for hs in sessions],
567
+ "advice": {k: sum(1 for d in people if d["summary"].get("advice") == k and not d.get("asleep"))
568
+ for k in ("compact", "clear")}}
461
569
  write(data)
462
570
  print(f"office: {len(people)} desks, {len(todo) if use_llm else 0} summarized"
463
571
  f"{' (' + error + ')' if error else ''} in {data['seconds']}s → {OUT / 'index.html'}")
@@ -506,12 +614,13 @@ def main(argv: list[str] | None = None) -> int:
506
614
  sub = ap.add_subparsers(dest="cmd")
507
615
  r = sub.add_parser("run")
508
616
  r.add_argument("--no-llm", action="store_true")
509
- r.add_argument("--model", default="sonnet")
617
+ r.add_argument("--quick", action="store_true", help="live pass: summarize only desks whose status changed")
618
+ r.add_argument("--model", default="haiku")
510
619
  o = sub.add_parser("open")
511
- o.add_argument("--model", default="sonnet")
620
+ o.add_argument("--model", default="haiku")
512
621
  a = ap.parse_args(argv)
513
622
  if a.cmd == "run":
514
- return run(a.model, not a.no_llm)
623
+ return run(a.model, not a.no_llm, a.quick)
515
624
  if a.cmd == "open":
516
625
  return open_page(a.model)
517
626
  ap.print_help()