@hivey/cli 0.9.52 → 0.9.54

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.52",
3
+ "version": "0.9.54",
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",
@@ -117,13 +117,33 @@ hivey agent-map schedule install [--at 06:30] [--model haiku] # | remove | sta
117
117
  `map-meta.json` (`{"nodes": {"<box id>": {"refs": [...], "description": "…"}}, "stages": {...}}`,
118
118
  written by the nightly model), else by label. A job counts only its own spend, not its agent's.
119
119
  - **Descriptions** ("what it does"): from a brief's mission, a skill's description or a script's module
120
- docstring; the nightly model writes the missing or weak ones to `~/.hivey/agent-map/descriptions.json`
121
- (kept, edit freely), which wins over the extracted ones. They show in the map's info cards and the run log.
120
+ docstring; the scan lists the weak ones in snapshot `descriptions_to_write` (empty, cut off with "…",
121
+ copied from a brief like "You are X" / "Own the…", or shared by two jobs) and the nightly model writes
122
+ a sentence for each (8–18 words, starts with a verb, says what it does and produces) to
123
+ `~/.hivey/agent-map/descriptions.json` (kept, edit freely), which wins over the extracted ones. They
124
+ show in the map's info cards and the run log.
125
+ - **Failing boxes:** a box whose job failed (❌), missed its run or logged errors (⚠️) gets ⚠️ after its
126
+ label and a dashed outline; its info card has a "⚠️ Problem" row linking to that job in
127
+ `agent-logs.html#job-<id>` (the logs page opens the row). Data stores are never flagged.
122
128
  - **Automated vs interactive:** the map, the stats page and map colours count AUTOMATED work only
123
129
  (scheduled jobs, scripts, headless `claude -p` / `codex exec`, scripts' API calls; snapshot `usage`).
124
130
  People chatting with agents (Claude Code, Codex, Grok in a terminal; snapshot `interactive`, with one
125
131
  entry per session) go to **`agent-sessions.html`**: cost by agent and by day, the costliest sessions with
126
132
  their peak context (⚠️ over 300k tokens), length and first message, and tips to spend less.
133
+ - **Open:** `hivey agent-map open` (hivey menu → agent map) opens `http://127.0.0.1:8754/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 8754 or any
138
+ free one, in `~/.hivey/agent-map/server.json`; stops after 2 h unused) so the navbar's ↻ Refresh
139
+ button works: it runs `agent_map.py refresh` (new scan into the latest report's pages, no model, a few
140
+ seconds; the map keeps the night's boxes) and reloads. Only the served pages can trigger it (Origin
141
+ check). Opened as plain files, the button says to open them from the hivey menu.
142
+ - **Context window per agent** (`context_window.py`): the Sessions page shows each agent's window for its
143
+ next session, 1M or the standard 200k (Claude Code compacts the session before it grows).
144
+ `hivey agent-map context` lists every agent's window and peak; `hivey agent-map context <agent…> --set
145
+ standard|1M` writes `CLAUDE_CODE_DISABLE_1M_CONTEXT` into that agent's `.claude/settings.json` (old
146
+ file copied to `~/.hivey/old/`). A running session keeps its window until it restarts.
127
147
  - **Models per job:** the scan reads each job's code for the models it uses, local ones included
128
148
  (`nodes[].llm_api.models`: JEV-9B local or Jev on OpenRouter, Claude Opus/Sonnet/Haiku, Grok, DeepSeek,
129
149
  Gemini, OpenAI/Codex, Muse, Whisper, Parakeet); the map's info card lists them next to recorded spend.
@@ -184,6 +204,6 @@ the final message (or the last chunk carrying usage).
184
204
  as `{"model-substring": [in, out, cache_read, cache_write]}` per million tokens). Claude Code on a
185
205
  Max plan and Codex on Plus are not billed per token: call their cost "API-equivalent". Grok CLI and
186
206
  OpenRouter report real cost, used as is.
187
- - Antigravity (`agy`) keeps no token data on disk: it shows as running, not as spend.
207
+ - Antigravity (`agy`) keeps no token data on disk: it shows as running, not as spend (the stats page notes it only when a job or hivey agent runs agy).
188
208
  - Codex sessions are zstd-compressed; without `zstd` on PATH they are skipped.
189
209
  - Read-only: the scan never edits jobs, plists or scripts.
@@ -526,7 +526,7 @@ class Usage:
526
526
  "daily_by_agent": daily_agents,
527
527
  "total_cost_usd": round(sum(r[5]["cost_usd"] for r in rows), 2),
528
528
  "total_tokens": sum(r[5]["input"] + r[5]["output"] + r[5]["cache_read"] + r[5]["cache_write"] for r in rows),
529
- "sources_without_tokens": ["antigravity (agy): no per-session token data on disk"],
529
+ "sources_without_tokens": [], # filled by scan() when something actually runs agy
530
530
  **({"sessions": self.session_list()} if interactive else {}),
531
531
  }
532
532
 
@@ -626,6 +626,29 @@ def describe_script(path: Path) -> str:
626
626
  return first_sentence(joined) if len(joined) > 20 and not BOILERPLATE.search(joined) else ""
627
627
 
628
628
 
629
+ WEAK_START = re.compile(r"^(you\b|your\b|own\b|goal\b|job:|example\b|since\b|wrapper\b|always\b|never\b|"
630
+ r"this (file|folder|repo)\b|#|-|\d)", re.I)
631
+
632
+
633
+ def weak_description(text: str) -> bool:
634
+ """True when a description doesn't plainly say what the thing does: empty, cut off, copied from a
635
+ brief ("You are…", "Own the…"), a stray list number, too short or too long."""
636
+ t = (text or "").strip()
637
+ return (len(t) < 25 or len(t) > 170 or t.endswith(("…", "...", ":")) or bool(WEAK_START.match(t))
638
+ or bool(re.search(r"(:|\s)\d+\.$", t)))
639
+
640
+
641
+ def descriptions_to_write(jobs: list, nodes: list, live: list) -> list:
642
+ active = {a["agent"] for a in live}
643
+ seen = collections.Counter(j.get("description", "") for j in jobs)
644
+ out = [j["id"] for j in jobs if weak_description(j.get("description", "")) or seen[j.get("description", "")] > 1]
645
+ for n in nodes: # agents: the active ones and those with scheduled work (the dormant are folded away)
646
+ if n["type"] != "job" and weak_description(n.get("description", "")) and (
647
+ n["label"] in active or any(j.get("agent") == n["label"] for j in jobs)):
648
+ out.append(n["id"])
649
+ return out
650
+
651
+
629
652
  def describe_job(j: dict) -> str:
630
653
  for p in job_run_files(j["command"]):
631
654
  pp = Path(p)
@@ -860,7 +883,16 @@ def scan(days: int) -> dict:
860
883
  live = live_agents()
861
884
  collected = Usage(days).collect()
862
885
  usage, interactive = collected.summary(), collected.summary(interactive=True)
886
+ import context_window
887
+ for a in interactive.get("agents", []): # which window each agent's chats get (Sessions page)
888
+ folder = context_window.folder_of(a["agent"])
889
+ a["folder"] = str(folder) if folder else ""
890
+ a["window"] = context_window.window(folder) if folder else ""
863
891
  nodes, candidates = build_links(jobs, live)
892
+ # Antigravity keeps no token data on disk: say so only when a job or a hivey agent runs it
893
+ if any(re.search(r"(^|[\s/;&|])agy(\s|$)", j.get("command", "")) for j in jobs) or \
894
+ any(a.get("cli") == "agy" for a in live):
895
+ usage["sources_without_tokens"] = ["antigravity (agy): no per-session token data on disk"]
864
896
  overrides = load_json(DESCRIPTIONS, {})
865
897
  for j in jobs:
866
898
  j["description"] = overrides.get(j["id"]) or describe_job(j)
@@ -888,6 +920,8 @@ def scan(days: int) -> dict:
888
920
  "nodes": nodes,
889
921
  "links_confirmed": load_json(LINKS, []),
890
922
  "links_candidates": candidates,
923
+ # ids whose description the nightly model should rewrite: weak, or the same text as another job's
924
+ "descriptions_to_write": descriptions_to_write(jobs, nodes, live),
891
925
  "notes": [
892
926
  "Costs are API-list-price estimates; Claude Code (Max) and Codex (Plus) usage is API-equivalent, not billed.",
893
927
  "Claude Code transcripts older than the weekly purge (15 days) are gone; longer windows undercount.",
@@ -940,6 +974,34 @@ def print_stats(snap: dict) -> None:
940
974
  print(f" {st['resource']}{owner}: " + ", ".join(dict.fromkeys(n['id'] for n in st['nodes'])))
941
975
 
942
976
 
977
+ def context_cmd(agents: list, size: str | None) -> int:
978
+ import context_window as cw
979
+ snap = load_json(STATE / "snapshot.json", {})
980
+ peaks = {}
981
+ for sess in (snap.get("interactive") or {}).get("sessions", []):
982
+ for name in sess.get("agents") or [sess["agent"]]:
983
+ peaks[name] = max(peaks.get(name, 0), sess.get("max_context", 0))
984
+ if not agents:
985
+ if size:
986
+ print("name the agents to change, e.g.: hivey agent-map context superintel x-content --set standard")
987
+ return 2
988
+ agents = sorted(peaks, key=lambda n: -peaks[n])
989
+ code = 0
990
+ for name in agents:
991
+ folder = Path(name).expanduser() if "/" in name and Path(name).expanduser().is_dir() else cw.folder_of(name)
992
+ if not folder:
993
+ print(f"{name}: no folder found")
994
+ code = 1
995
+ continue
996
+ if size:
997
+ now = cw.set_window(folder, cw.LARGE if size.lower() == "1m" else cw.STANDARD)
998
+ print(f"{name}: {now} (from its next start; a running session keeps its window)")
999
+ else:
1000
+ peak = peaks.get(name, 0)
1001
+ print(f"{name:28} {cw.window(folder):9} peak {peak // 1000}k {short(str(folder))}")
1002
+ return code
1003
+
1004
+
943
1005
  def main() -> int:
944
1006
  ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
945
1007
  sub = ap.add_subparsers(dest="cmd", required=True)
@@ -974,6 +1036,12 @@ def main() -> int:
974
1036
  'e.g. "envsave get es_…" ("" = the normal claude login)')
975
1037
  sc.add_argument("--at", default="06:30", help="HH:MM, local time (default 06:30, after the night's jobs)")
976
1038
  sc.add_argument("--model", default="haiku")
1039
+ rf = sub.add_parser("refresh", help="new scan into the latest report's pages, no model (the Refresh button)")
1040
+ rf.add_argument("--days", type=int, default=7)
1041
+ sub.add_parser("serve", help="serve the report pages on 127.0.0.1 (`open` starts it)")
1042
+ cx = sub.add_parser("context", help="context window per agent: list, or set standard | 1M")
1043
+ cx.add_argument("agents", nargs="*", help="agent names (as on the Sessions page) or folders")
1044
+ cx.add_argument("--set", choices=["standard", "1M", "1m"], help="standard = 200k, compacts early; 1M = large")
977
1045
  lk = sub.add_parser("link")
978
1046
  lk.add_argument("src")
979
1047
  lk.add_argument("dst")
@@ -1019,6 +1087,14 @@ def main() -> int:
1019
1087
  a.cost, a.kind, a.note)
1020
1088
  print(json.dumps(entry))
1021
1089
  return 0 if entry else 1
1090
+ if a.cmd == "refresh":
1091
+ import report
1092
+ return report.refresh(scan, a.days, "haiku")
1093
+ if a.cmd == "serve":
1094
+ import serve
1095
+ return serve.serve()
1096
+ if a.cmd == "context":
1097
+ return context_cmd(a.agents, a.set)
1022
1098
  if a.cmd == "link":
1023
1099
  links = [l for l in load_json(LINKS, []) if not (l["from"] == a.src and l["to"] == a.dst)]
1024
1100
  if not a.remove:
@@ -0,0 +1,88 @@
1
+ """Context window per agent: the standard window (Claude Code compacts the session before it gets
2
+ large) or 1M tokens (Opus's default in Claude Code, where every reply re-reads the whole session).
3
+
4
+ Set per agent folder in <folder>/.claude/settings.json → "env": {"CLAUDE_CODE_DISABLE_1M_CONTEXT": "1"},
5
+ so it only affects that agent and survives hivey updates. A running session keeps its window until it
6
+ restarts. Python standard library only.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import shutil
13
+ import time
14
+ from pathlib import Path
15
+
16
+ HOME = Path.home()
17
+ KEY = "CLAUDE_CODE_DISABLE_1M_CONTEXT"
18
+ STANDARD = "standard" # 200k tokens
19
+ LARGE = "1M"
20
+
21
+
22
+ def folder_of(agent: str) -> Path | None:
23
+ """The working folder of an agent name as the spend log names it (see hivey_spend.agent_of)."""
24
+ try:
25
+ aliases = json.loads((HOME / ".hivey/spend/aliases.json").read_text())
26
+ except (OSError, ValueError):
27
+ aliases = {}
28
+ for prefix, name in aliases.items():
29
+ if name == agent:
30
+ return Path(os.path.expanduser(prefix))
31
+ if agent == "hivey":
32
+ cand = HOME / ".hivey/agent"
33
+ elif agent.startswith("swarm:"):
34
+ cand = HOME / "swarms" / agent.split(":", 1)[1]
35
+ elif agent.startswith("project:"):
36
+ cand = HOME / "projects" / agent.split(":", 1)[1]
37
+ elif agent.startswith("~/"):
38
+ cand = HOME / agent[2:]
39
+ elif "/" not in agent and ":" not in agent and " " not in agent:
40
+ cand = HOME / "agents" / agent
41
+ else:
42
+ return None
43
+ return cand if cand.is_dir() else None
44
+
45
+
46
+ def _env(path: Path) -> dict:
47
+ try:
48
+ return json.loads(path.read_text()).get("env") or {}
49
+ except (OSError, ValueError, AttributeError):
50
+ return {}
51
+
52
+
53
+ def window(folder: Path | None) -> str:
54
+ """STANDARD or LARGE for sessions started in this folder (folder settings win over the user's)."""
55
+ layers = [HOME / ".claude/settings.json"]
56
+ if folder:
57
+ layers += [folder / ".claude/settings.json", folder / ".claude/settings.local.json"]
58
+ value = None
59
+ for path in layers:
60
+ if KEY in _env(path):
61
+ value = str(_env(path)[KEY])
62
+ return STANDARD if value in ("1", "true", "True") else LARGE
63
+
64
+
65
+ def set_window(folder: Path, size: str) -> str:
66
+ """Write the agent's choice into <folder>/.claude/settings.json (a copy of the old file goes to
67
+ ~/.hivey/old/). Returns what the folder now uses."""
68
+ path = folder / ".claude/settings.json"
69
+ try:
70
+ data = json.loads(path.read_text()) if path.is_file() else {}
71
+ except ValueError as e:
72
+ raise SystemExit(f"{path} is not valid JSON ({e}); fix it first")
73
+ if path.is_file():
74
+ old = HOME / ".hivey/old"
75
+ old.mkdir(parents=True, exist_ok=True)
76
+ shutil.copy2(path, old / f"{folder.name}-settings-{time.strftime('%Y%m%d-%H%M%S')}.json")
77
+ env = dict(data.get("env") or {})
78
+ if size == STANDARD:
79
+ env[KEY] = "1"
80
+ else:
81
+ env.pop(KEY, None)
82
+ if str(_env(HOME / ".claude/settings.json").get(KEY)) in ("1", "true", "True"):
83
+ env[KEY] = "0" # the user's settings turn 1M off everywhere: turn it back on here
84
+ data = {"env": env, **{k: v for k, v in data.items() if k != "env"}} if env else \
85
+ {k: v for k, v in data.items() if k != "env"}
86
+ path.parent.mkdir(parents=True, exist_ok=True)
87
+ path.write_text(json.dumps(data, indent=2) + "\n")
88
+ return window(folder)
@@ -29,13 +29,16 @@ STAGE_HELP = {
29
29
  }
30
30
 
31
31
  NAV_CSS = """
32
- .hv-nav{position:relative;z-index:50;display:flex;gap:4px;align-items:center;justify-content:center;
33
- padding:6px 10px;font:600 13px/1.2 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;
32
+ .hv-nav{position:relative;z-index:50;display:flex;flex-wrap:wrap;gap:4px;align-items:center;justify-content:flex-start;
33
+ padding:6px 16px;font:600 13px/1.2 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;
34
34
  border-bottom:1px solid rgba(127,127,127,.25);background:rgba(127,127,127,.06)}
35
35
  .hv-nav a{color:inherit;opacity:.65;text-decoration:none;padding:4px 12px;border-radius:999px}
36
36
  .hv-nav a:hover{opacity:1;background:rgba(127,127,127,.14)}
37
37
  .hv-nav a.on{opacity:1;background:rgba(47,111,236,.16);color:#2f6fec}
38
- .hv-nav .hv-when{margin-left:12px;opacity:.5;font-weight:400;font-size:12px}
38
+ .hv-nav .hv-when{margin-left:12px;opacity:.55;font-weight:400;font-size:12px;white-space:nowrap}
39
+ .hv-nav .hv-refresh{margin-left:8px;font:600 12px/1.2 inherit;font-family:inherit;color:#2f6fec;cursor:pointer;
40
+ background:rgba(47,111,236,.10);border:1px solid rgba(47,111,236,.35);border-radius:999px;padding:4px 11px}
41
+ .hv-nav .hv-refresh:hover{background:rgba(47,111,236,.18)} .hv-nav .hv-refresh:disabled{opacity:.6;cursor:wait}
39
42
  """
40
43
 
41
44
  MAP_CSS = """
@@ -50,6 +53,8 @@ html[data-theme="dark"] .hv-legend{background:rgba(22,27,34,.92);color:#e6edf3}
50
53
  .hv-info{margin-top:.7rem;padding-top:.6rem;border-top:1px solid rgba(127,127,127,.25);font-size:.78rem;line-height:1.45}
51
54
  .hv-info .hv-desc{margin:0 0 .5rem;font-size:.85rem}
52
55
  .hv-info dl{display:grid;grid-template-columns:auto 1fr;gap:.18rem .7rem;margin:0}
56
+ .hv-alert > rect:not(.c-mask){stroke-dasharray:5 3;stroke-width:2.2px}
57
+ .hv-info a{color:inherit;text-decoration:underline}
53
58
  .hv-info dt{opacity:.6}.hv-info dd{margin:0;font-variant-numeric:tabular-nums}
54
59
  .hv-info .hv-models{display:flex;flex-wrap:wrap;gap:.25rem}
55
60
  .hv-info .hv-models span{padding:.05rem .4rem;border:1px solid rgba(127,127,127,.35);border-radius:999px;font-size:.7rem}
@@ -61,7 +66,20 @@ def nav(active: str, generated: str) -> str:
61
66
  links = [("agent-stats.html", "Stats"), ("agent-map.html", "Map"), ("agent-logs.html", "Logs"),
62
67
  ("agent-sessions.html", "Sessions")]
63
68
  items = "".join(f'<a href="{href}"{" class=on" if href == active else ""}>{label}</a>' for href, label in links)
64
- return f'<nav class="hv-nav">{items}<span class="hv-when">scan {html.escape(generated[:16].replace("T", " "))}</span></nav>'
69
+ when = html.escape(generated[:16].replace("T", " "))
70
+ return (f'<nav class="hv-nav">{items}<span class="hv-when">scan {when}</span>'
71
+ '<button class="hv-refresh" type="button" title="Scan again now and reload (free: no model run)" '
72
+ 'onclick="hvRefresh(this)">↻ Refresh</button></nav>' + REFRESH_JS)
73
+
74
+
75
+ # The Refresh button: the pages are served by `hivey agent-map open` (serve.py) on 127.0.0.1,
76
+ # which reruns the scan on POST /hv-refresh. Opened as plain files, it says how to get there.
77
+ REFRESH_JS = """<script>async function hvRefresh(b){
78
+ if(location.protocol==='file:'){b.textContent='open from the hivey menu → agent map to refresh';return;}
79
+ b.disabled=true;const t0=Date.now();const tick=setInterval(()=>{b.textContent='↻ Scanning… '+Math.round((Date.now()-t0)/1000)+'s';},500);
80
+ try{const r=await fetch('/hv-refresh',{method:'POST'});const j=await r.json();clearInterval(tick);
81
+ if(j.ok){location.reload();}else{b.disabled=false;b.textContent='refresh failed';b.title=j.error||'';}}
82
+ catch(e){clearInterval(tick);b.disabled=false;b.textContent='refresh failed: server not running (reopen from the hivey menu)';}}</script>"""
65
83
 
66
84
 
67
85
  def inject(page: str, css: str, top: str, script: str = "") -> str:
@@ -91,6 +109,11 @@ def model_name(m: str) -> str:
91
109
  return (f"{k.group(1).title()} {k.group(2)}" + (f".{k.group(3)}" if k.group(3) else "")) if k else m
92
110
 
93
111
 
112
+ def job_anchor(job_id: str) -> str:
113
+ """The logs page anchor of a job (same as report.job_anchor)."""
114
+ return "job-" + re.sub(r"[^a-z0-9]+", "-", job_id.lower()).strip("-")
115
+
116
+
94
117
  def node_data(snap: dict, spec: dict, meta: dict, job_state) -> dict:
95
118
  usage = {a["agent"]: a for a in snap["usage"]["agents"]}
96
119
  try: # what the nightly model (or you) wrote since the scan wins
@@ -117,7 +140,7 @@ def node_data(snap: dict, spec: dict, meta: dict, job_state) -> dict:
117
140
  if cand in jobs_by_name:
118
141
  refs.append(jobs_by_name[cand]["id"])
119
142
  break
120
- names, desc, states, code_models = [], m.get("description", ""), [], []
143
+ names, desc, states, code_models, alerts = [], m.get("description", ""), [], [], []
121
144
  for ref in refs:
122
145
  if overrides.get(ref) and not desc:
123
146
  desc = overrides[ref]
@@ -129,6 +152,8 @@ def node_data(snap: dict, spec: dict, meta: dict, job_state) -> dict:
129
152
  desc = desc or j.get("description", "")
130
153
  emo, words = job_state(j)
131
154
  states.append(f"{emo} {words} · {(j.get('last_run') or j.get('log_modified') or '?').replace('T', ' ')}")
155
+ if emo in ("❌", "⚠️"): # failed, missed or errors in its log: flag the box
156
+ alerts.append({"name": j["name"], "words": words, "anchor": job_anchor(j["id"])})
132
157
  sn = snodes.get(ref)
133
158
  if sn:
134
159
  code_models += [m for m in (sn.get("llm_api") or {}).get("models", []) if m not in code_models]
@@ -152,7 +177,7 @@ def node_data(snap: dict, spec: dict, meta: dict, job_state) -> dict:
152
177
  if not any(mname.split()[0].lower() in c.lower() for c in code_models):
153
178
  code_models.append(mname)
154
179
  out[n["id"]] = {"refs": refs, "desc": desc, "cost": round(tot["cost"], 2), "tokens": tot["tokens"],
155
- "out": tot["out"], "calls": tot["calls"], "models": code_models[:5], "states": states[:3],
180
+ "out": tot["out"], "calls": tot["calls"], "models": code_models[:5], "states": states[:3], "alerts": alerts if n.get("type") != "database" else [],
156
181
  "subject": bool(refs) and n.get("type") != "database"}
157
182
  spend = [d["cost"] for d in out.values() if d["subject"]]
158
183
  top = max(spend, default=0.0)
@@ -173,8 +198,14 @@ document.querySelectorAll('g[data-node-id]').forEach(g=>{
173
198
  const d=D[g.dataset.nodeId]; if(!d) return;
174
199
  if(d.hue!=null){g.querySelectorAll(':scope > rect:not(.c-mask)').forEach(r=>{
175
200
  r.style.fill='hsla('+d.hue+',75%,50%,.18)'; r.style.stroke='hsl('+d.hue+',68%,42%)';});}
201
+ if(d.alerts&&d.alerts.length){
202
+ const lab=g.querySelector(':scope > text[data-node-label]');
203
+ if(lab&&!lab.querySelector('.hv-warn')){const w=document.createElementNS('http://www.w3.org/2000/svg','tspan');
204
+ w.setAttribute('class','hv-warn'); w.textContent=' ⚠️'; lab.appendChild(w);}
205
+ g.classList.add('hv-alert');
206
+ }
176
207
  const t=g.querySelector(':scope > title');
177
- if(t){t.textContent=[g.dataset.nodeLabel, d.desc, d.subject?(fmt(d.cost)+' in '+DAYS+' days · '+tok(d.tokens)+' tokens'+(d.models.length?' · '+d.models.join(', '):'')):''].filter(Boolean).join('\n');}
208
+ if(t){t.textContent=[g.dataset.nodeLabel, d.desc, d.subject?(fmt(d.cost)+' in '+DAYS+' days · '+tok(d.tokens)+' tokens'+(d.models.length?' · '+d.models.join(', '):'')):''].filter(Boolean).concat((d.alerts||[]).map(a=>'⚠️ '+a.name+': '+a.words)).join('\n');}
178
209
  });
179
210
  document.querySelectorAll('svg text').forEach(t=>{
180
211
  const m=/^\s*\d+\s*\/\s*(.+?)\s*$/.exec(t.textContent||''); if(!m) return;
@@ -184,24 +215,28 @@ document.querySelectorAll('svg text').forEach(t=>{
184
215
  t.style.pointerEvents='auto';
185
216
  });
186
217
  let current=null;
187
- const pick=e=>{const g=e.target.closest&&e.target.closest('g[data-node-id]'); if(g) current=g.dataset.nodeId;};
218
+ const refill=()=>document.querySelectorAll('.semantic-passport-meta').forEach(fill);
219
+ const pick=e=>{const g=e.target.closest&&e.target.closest('g[data-node-id]'); if(g){current=g.dataset.nodeId; setTimeout(refill,0); requestAnimationFrame(refill);}};
188
220
  document.addEventListener('pointerdown',pick,true); document.addEventListener('focusin',pick,true);
189
221
  function fill(meta){
190
- const box=meta.parentElement; if(!box||box.querySelector('.hv-info')) return;
222
+ const box=meta.parentElement; if(!box) return;
223
+ const old=box.querySelector('.hv-info');
224
+ if(old&&old.dataset.node===current) return; // the card is reused for every box: refill on a new pick
225
+ if(old) old.remove();
191
226
  const d=D[current]; if(!d) return;
192
227
  const rows=[];
228
+ (d.alerts||[]).forEach(a=>rows.push(['⚠️ Problem', esc(a.name)+': '+esc(a.words)+' · <a href="agent-logs.html#'+a.anchor+'">open its log</a>']));
193
229
  if(d.subject){
194
230
  rows.push(['Spend', fmt(d.cost)+' in '+DAYS+' days, automated runs only (API-equivalent)']);
195
231
  rows.push(['Tokens', tok(d.tokens)+' ('+tok(d.out)+' output) · '+d.calls.toLocaleString()+' calls']);
196
232
  }
197
233
  rows.push(['Models', d.models.length?'<span class="hv-models">'+d.models.map(m=>'<span>'+esc(m)+'</span>').join('')+'</span>':'none found']);
198
234
  d.states.forEach(s=>rows.push(['Last run', esc(s)]));
199
- const div=document.createElement('div'); div.className='hv-info';
235
+ const div=document.createElement('div'); div.className='hv-info'; div.dataset.node=current;
200
236
  div.innerHTML=(d.desc?'<p class="hv-desc">'+esc(d.desc)+'</p>':'')+(rows.length?'<dl>'+rows.map(r=>'<dt>'+r[0]+'</dt><dd>'+r[1]+'</dd>').join('')+'</dl>':'');
201
237
  meta.insertAdjacentElement('afterend',div);
202
238
  }
203
- new MutationObserver(()=>document.querySelectorAll('.semantic-passport-meta').forEach(fill))
204
- .observe(document.body,{childList:true,subtree:true});
239
+ new MutationObserver(refill).observe(document.body,{childList:true,subtree:true,characterData:true});
205
240
  })();
206
241
  """
207
242
 
@@ -225,5 +260,6 @@ def enhance_folder(folder: Path, snap: dict, job_state) -> None:
225
260
  .replace("__DAYS__", json.dumps(snap.get("window_days", 7))))
226
261
  legend = (f'<div class="hv-legend"><b>Spend, last {snap.get("window_days", 7)} days</b><div class="bar"></div>'
227
262
  f'<div class="ends"><span>$0</span><span>{money(top)}</span></div>'
228
- f'<div style="opacity:.65;margin-top:3px">click a box for what it does, tokens and models</div></div>')
263
+ f'<div style="opacity:.65;margin-top:3px">click a box for what it does, tokens and models</div>'
264
+ f'<div style="opacity:.65">⚠️ its last run failed, was missed or logged errors</div></div>')
229
265
  page.write_text(inject(page.read_text(), NAV_CSS + MAP_CSS, nav("agent-map.html", generated) + legend, script))
@@ -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()
@@ -251,6 +252,11 @@ def job_state(j: dict) -> tuple[str, str]:
251
252
 
252
253
  AGENT_STATE = {"working": ("🟢", "working"), "running": ("🟢", "running"), "blocked": ("🔴", "blocked, needs you"),
253
254
  "idle": ("⚪", "idle"), "done": ("✅", "done"), "gone": ("⚫", "not running")}
255
+ def job_anchor(job_id: str) -> str:
256
+ """The logs page anchor of a job (the map links to it)."""
257
+ return "job-" + re.sub(r"[^a-z0-9]+", "-", job_id.lower()).strip("-")
258
+
259
+
254
260
  ORDER = {"❌": 0, "⚠️": 1, "🔴": 1, "⏳": 2, "🟢": 2, "❔": 3, "⚪": 4, "✅": 4, "⚫": 5}
255
261
 
256
262
 
@@ -295,7 +301,7 @@ def write_logs_page(snap: dict, folder: Path) -> None:
295
301
  f"<p class=meta>command <code>{e(j['command'][:400])}</code></p>"] + log_block(j)
296
302
  if not j.get("log"):
297
303
  body.append("<p class=meta>this job writes no log file hivey can find.</p>")
298
- rows.append(f"<details class=row data-state='{emo}'><summary><span class=emo>{emo}</span>"
304
+ rows.append(f"<details class=row id='{job_anchor(j['id'])}' data-state='{emo}'><summary><span class=emo>{emo}</span>"
299
305
  f"<span class=name><b>{e(j['name'])}</b><small class=desc>{e(j.get('description') or '')}</small></span>"
300
306
  f"<span class=sub>{e(words)}</span><span class=when>{e(last)}</span>"
301
307
  f"<span class=issue>{e(issue[:110])}</span></summary>{details(body)}</details>")
@@ -327,6 +333,8 @@ def write_logs_page(snap: dict, folder: Path) -> None:
327
333
  f"<span class=issue>{e(', '.join(dormant[:8]))}…</span></summary>"
328
334
  f"<p class=meta>{e(', '.join(dormant))}</p></details>")
329
335
  summary = " · ".join(f"{k} {v}" for k, v in sorted(counts.items(), key=lambda kv: ORDER.get(kv[0], 9)))
336
+ import enhance
337
+ NAV, NAV_CSS = enhance.nav("agent-logs.html", snap['generated']), enhance.NAV_CSS
330
338
  page = f"""<!doctype html><html lang=en><meta charset=utf-8>
331
339
  <meta name=viewport content="width=device-width,initial-scale=1">
332
340
  <title>Agent logs · {e(snap['generated'][:16])}</title>
@@ -335,7 +343,7 @@ def write_logs_page(snap: dict, folder: Path) -> None:
335
343
  @media (prefers-color-scheme:dark){{:root{{--bg:#0d1117;--fg:#e6edf3;--mute:#8b949e;--line:#30363d;--card:#161b22;--accent:#79a8ff;--pre:#0b0f14}}}}
336
344
  body{{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}}
337
345
  main{{max-width:1180px;margin:0 auto;padding:28px 24px 60px}}
338
- nav a{{color:var(--accent);margin-right:18px;text-decoration:none;font-weight:600}} nav a.on{{color:var(--fg)}}
346
+ {NAV_CSS}
339
347
  h1{{font-size:26px;margin:18px 0 4px}} h2{{font-size:19px;margin:34px 0 10px}}
340
348
  .lead{{color:var(--mute);margin:0 0 6px}} .counts{{font-size:17px;margin:10px 0 0}}
341
349
  .row{{border:1px solid var(--line);background:var(--card);border-radius:10px;margin:7px 0}}
@@ -351,7 +359,7 @@ pre{{background:var(--pre);border:1px solid var(--line);border-radius:8px;paddin
351
359
  @media (max-width:760px){{summary{{grid-template-columns:28px 1fr}} .sub,.when,.issue{{grid-column:2}}}}
352
360
  </style>
353
361
  <main>
354
- <nav class=hv-top><a href="agent-stats.html">Stats</a><a href="agent-map.html">Map</a><a class=on href="agent-logs.html">Logs</a><a href="agent-sessions.html">Sessions</a></nav>
362
+ {NAV}
355
363
  <h1>Did every job and agent run?</h1>
356
364
  <p class=lead>Scan of {e(snap['generated'][:16].replace('T', ' '))}. Click a row for its issues and the last lines of its log.</p>
357
365
  <p class=counts>Scheduled jobs: {summary}</p>
@@ -362,7 +370,10 @@ pre{{background:var(--pre);border:1px solid var(--line);border-radius:8px;paddin
362
370
  <p class=legend>✅ ran ok · ⚠️ errors in its log or a missed run · ❌ failed (non-zero exit) or not loaded · ⏳ running ·
363
371
  ❔ no log · 🟢 working · 🔴 blocked, needs you · ⚪ idle · ⚫ not running. "Issues" are the error lines among the
364
372
  last 40 lines of each log, so an old error can show until the log moves on.</p>
365
- </main></html>"""
373
+ </main>
374
+ <script>(function(){{const open=()=>{{const d=location.hash&&document.getElementById(location.hash.slice(1));
375
+ if(d&&d.tagName==='DETAILS'){{d.open=true;d.scrollIntoView({{block:'start'}});}}}};open();addEventListener('hashchange',open);}})();</script>
376
+ </html>"""
366
377
  (folder / "agent-logs.html").write_text(page)
367
378
 
368
379
 
@@ -408,10 +419,14 @@ already built: do not touch stats.archify.md or agent-stats.html.
408
419
  its schedule or role, its models and its automated cost when it has one ("cron 04:15 · Grok + Sonnet ·
409
420
  $0.40"); spend is usage.agents (automated only). Keep at most 25 nodes on 5 stages x rows 0-4;
410
421
  refresh the numbers in the cards (automated spend, models in use, needs attention).
411
- 3. Descriptions: every node in snapshot.json has a "description" (what it does). For each job and agent
412
- whose description is empty or does not say what it does (an instruction to the agent, "You are X"),
413
- read its brief or script (first lines only) and write ONE plain sentence of at most 18 words into
414
- ~/.hivey/agent-map/descriptions.json ({{"<node id>": "<sentence>"}}; keep the entries already there).
422
+ 3. Descriptions: every node in snapshot.json has a "description" (what it does). snapshot.json
423
+ "descriptions_to_write" lists the ids whose description is empty, cut off, copied from a brief
424
+ ("You are X", "Own the…") or shared with another job. For each, read its brief, script or command
425
+ (first lines only) and write ONE plain sentence into ~/.hivey/agent-map/descriptions.json
426
+ ({{"<node id>": "<sentence>"}}; keep the entries already there). Rules: 8 to 18 words; start with a
427
+ verb ("Ranks…", "Downloads…", "Paper-trades…"); say what it does and what it produces or where;
428
+ no "you", no dates, no ids, no trailing "…"; different jobs get different sentences (say what
429
+ sets each apart, e.g. "places the orders" vs "writes the report").
415
430
  Then write map-meta.json in this folder: {{"nodes": {{"<map node id>": {{"refs": [<snapshot node ids
416
431
  this box stands for>], "description": "<one sentence>"}}}}, "stages": {{"<stage label>": "<what this
417
432
  column holds, one sentence>"}}}}. A box that folds several jobs lists all of them in refs.
@@ -532,7 +547,7 @@ def nightly(scan, days: int, model: str, use_llm: bool) -> int:
532
547
  enhance.enhance_folder(folder, json.loads((folder / "snapshot.json").read_text()), job_state)
533
548
  except Exception as e: # the pages still work without hivey's layer
534
549
  log(folder, f"enhance failed: {e}")
535
- if ok:
550
+ if ok or (folder / "agent-logs.html").is_file(): # a failed stats page still publishes logs and sessions
536
551
  tmp = REPORTS / ".latest-new"
537
552
  if tmp.is_symlink() or tmp.exists():
538
553
  tmp.unlink()
@@ -545,12 +560,38 @@ def nightly(scan, days: int, model: str, use_llm: bool) -> int:
545
560
  return 0 if ok else 1
546
561
 
547
562
 
563
+ def refresh(scan, days: int, model: str) -> int:
564
+ """The Refresh button: a new scan rewrites the latest report's pages in place (stats, run log,
565
+ sessions, the map's colours and info cards). No model run, so it is free; the map's boxes stay
566
+ as the night drew them. With no report yet it builds one (also without a model)."""
567
+ folder = latest_report()
568
+ if not folder:
569
+ return nightly(scan, days, model, False)
570
+ log(folder, f"refresh: scan, last {days} days")
571
+ snap = scan(days)
572
+ (STATE / "snapshot.json").write_text(json.dumps(snap, indent=1, default=str))
573
+ write_stats(snap, folder)
574
+ write_logs_page(snap, folder)
575
+ import sessions_page
576
+ sessions_page.write_sessions_page(snap, folder)
577
+ ok, msg = finalize(folder, "explainer", "stats.archify.md", "agent-stats.html")
578
+ try:
579
+ import enhance
580
+ enhance.enhance_folder(folder, json.loads((folder / "snapshot.json").read_text()), job_state)
581
+ except Exception as e:
582
+ log(folder, f"enhance failed: {e}")
583
+ log(folder, f"refresh: {'ok' if ok else 'stats page FAILED ' + msg}")
584
+ return 0 if ok else 1
585
+
586
+
548
587
  # ---------------------------------------------------------------- open
549
588
 
550
589
  def latest_report() -> Path | None:
551
- if LATEST.exists() and (LATEST / "agent-stats.html").is_file():
590
+ def has_pages(p: Path) -> bool:
591
+ return (p / "agent-stats.html").is_file() or (p / "agent-logs.html").is_file()
592
+ if LATEST.exists() and has_pages(LATEST):
552
593
  return LATEST.resolve()
553
- folders = sorted(p for p in REPORTS.glob("*-*-*-*") if (p / "agent-stats.html").is_file()) if REPORTS.is_dir() else []
594
+ folders = sorted(p for p in REPORTS.glob("*-*-*-*") if has_pages(p)) if REPORTS.is_dir() else []
554
595
  return folders[-1] if folders else None
555
596
 
556
597
 
@@ -560,21 +601,61 @@ def notify(text: str) -> None:
560
601
  capture_output=True)
561
602
 
562
603
 
604
+ PAGES = ("agent-map.html", "agent-stats.html", "agent-logs.html", "agent-sessions.html") # the first one found opens
605
+ FIRST_RUN = STATE / "first-run.json"
606
+
607
+
608
+ def open_page(folder: Path) -> bool:
609
+ """Open the map (else the first page there is) from the local server, so Refresh works; the
610
+ navbar reaches the other pages. Without the server, the file itself."""
611
+ page = next((p for p in PAGES if (folder / p).is_file()), None)
612
+ if not page:
613
+ return False
614
+ import serve
615
+ port = serve.ensure()
616
+ rel = "latest" if LATEST.exists() and LATEST.resolve() == folder.resolve() else folder.name
617
+ target = f"http://127.0.0.1:{port}/{rel}/{page}" if port else str(folder / page)
618
+ p = subprocess.run(["open", target], capture_output=True, text=True)
619
+ if p.returncode:
620
+ notify(f"Could not open the agent map: {(p.stderr or '').strip()[:120]}")
621
+ return False
622
+ print(f"opened {target}")
623
+ return True
624
+
625
+
626
+ def first_run_busy() -> bool:
627
+ try:
628
+ info = json.loads(FIRST_RUN.read_text())
629
+ os.kill(int(info["pid"]), 0)
630
+ return time.time() - info.get("started", 0) < 1800
631
+ except (OSError, ValueError, KeyError, TypeError):
632
+ return False
633
+
634
+
563
635
  def open_latest(model: str) -> int:
564
636
  folder = latest_report()
565
637
  if folder:
566
- for page in ("agent-stats.html", "agent-map.html", "agent-logs.html", "agent-sessions.html"):
567
- if (folder / page).is_file():
568
- subprocess.run(["open", str(folder / page)], capture_output=True)
569
- print(f"opened {folder}")
638
+ return 0 if open_page(folder) else 1
639
+ # No report yet: the pages without a model first (seconds), open them, then the map in the background.
640
+ if first_run_busy(): # a second click while the first report is being built
641
+ notify("Your first agent map is still being built; it opens when ready.")
570
642
  return 0
571
- # No report yet: build the first one in the background and open it when it is ready.
572
643
  REPORTS.mkdir(parents=True, exist_ok=True)
644
+ FIRST_RUN.write_text(json.dumps({"pid": os.getpid(), "started": time.time()}))
645
+ notify("Building your first agent map (a few seconds)…")
573
646
  with open(STATE / "first-run.log", "a") as fh:
574
- subprocess.Popen([sys.executable, "-I", str(SCRIPTS / "agent_map.py"), "nightly", "--model", model, "--open"],
575
- stdout=fh, stderr=fh, stdin=subprocess.DEVNULL, start_new_session=True)
576
- notify("Building your first agent map (a few minutes); it opens when ready.")
577
- print("no report yet: building the first one in the background (log: ~/.hivey/agent-map/first-run.log)")
647
+ subprocess.run([sys.executable, "-I", str(SCRIPTS / "agent_map.py"), "refresh"], stdout=fh, stderr=fh,
648
+ stdin=subprocess.DEVNULL, timeout=600)
649
+ folder = latest_report()
650
+ if folder:
651
+ open_page(folder)
652
+ # the map needs the model: drawn in the background; the page's Refresh (or reopening) shows it
653
+ bg = subprocess.Popen([sys.executable, "-I", str(SCRIPTS / "agent_map.py"), "nightly", "--model", model],
654
+ stdout=fh, stderr=fh, stdin=subprocess.DEVNULL, start_new_session=True)
655
+ FIRST_RUN.write_text(json.dumps({"pid": bg.pid, "started": time.time()}))
656
+ if folder:
657
+ notify("Stats, logs and sessions are open; the map is being drawn (a few minutes).")
658
+ print("first report: pages built; the map is being drawn in the background (log: ~/.hivey/agent-map/first-run.log)")
578
659
  return 0
579
660
 
580
661
 
@@ -0,0 +1,134 @@
1
+ """Local server for the agent map pages, so their Refresh button can rerun the scan.
2
+
3
+ `hivey agent-map open` starts it (once; later opens reuse it) and opens the pages from
4
+ http://127.0.0.1:<port>/latest/. It listens on 127.0.0.1 only, serves ~/.hivey/agent-map/reports, and
5
+ has one action: POST /hv-refresh runs `agent_map.py refresh` (free: no model) and only answers the
6
+ pages it serves (Origin check), so other web pages can't trigger it. It stops after 2 hours unused.
7
+ Python standard library only.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import http.server
12
+ import json
13
+ import os
14
+ import subprocess
15
+ import sys
16
+ import threading
17
+ import time
18
+ import urllib.request
19
+ from pathlib import Path
20
+
21
+ STATE = Path.home() / ".hivey" / "agent-map"
22
+ REPORTS = STATE / "reports"
23
+ INFO = STATE / "server.json"
24
+ SCRIPTS = Path(__file__).resolve().parent
25
+ PREFERRED_PORT = 8754
26
+ IDLE_SECONDS = 2 * 3600
27
+ PING = "/hv-ping"
28
+ MARK = b"hivey-agent-map"
29
+
30
+
31
+ def running() -> int | None:
32
+ try:
33
+ port = int(json.loads(INFO.read_text())["port"])
34
+ except (OSError, ValueError, KeyError, TypeError):
35
+ return None
36
+ try:
37
+ with urllib.request.urlopen(f"http://127.0.0.1:{port}{PING}", timeout=1) as r:
38
+ return port if r.read() == MARK else None
39
+ except OSError:
40
+ return None
41
+
42
+
43
+ def ensure() -> int | None:
44
+ """The running server's port, starting one in the background when there is none."""
45
+ port = running()
46
+ if port:
47
+ return port
48
+ STATE.mkdir(parents=True, exist_ok=True)
49
+ with open(STATE / "server.log", "a") as fh:
50
+ subprocess.Popen([sys.executable, "-I", str(SCRIPTS / "agent_map.py"), "serve"], stdin=subprocess.DEVNULL,
51
+ stdout=fh, stderr=fh, start_new_session=True)
52
+ for _ in range(50):
53
+ time.sleep(0.1)
54
+ port = running()
55
+ if port:
56
+ return port
57
+ return None
58
+
59
+
60
+ class Handler(http.server.SimpleHTTPRequestHandler):
61
+ server_version = "hivey-agent-map"
62
+ busy = threading.Lock()
63
+ last_used = time.time()
64
+
65
+ def __init__(self, *args, **kwargs):
66
+ super().__init__(*args, directory=str(REPORTS), **kwargs)
67
+
68
+ def log_message(self, *args) -> None: # quiet
69
+ pass
70
+
71
+ def end_headers(self) -> None:
72
+ self.send_header("Cache-Control", "no-store") # a refresh must show the new pages
73
+ super().end_headers()
74
+
75
+ def answer(self, code: int, body: bytes, kind: str = "application/json") -> None:
76
+ self.send_response(code)
77
+ self.send_header("Content-Type", kind)
78
+ self.send_header("Content-Length", str(len(body)))
79
+ self.end_headers()
80
+ self.wfile.write(body)
81
+
82
+ def do_GET(self) -> None:
83
+ Handler.last_used = time.time()
84
+ if self.path == PING:
85
+ return self.answer(200, MARK, "text/plain")
86
+ return super().do_GET()
87
+
88
+ def do_POST(self) -> None:
89
+ Handler.last_used = time.time()
90
+ port = self.server.server_address[1]
91
+ if self.path != "/hv-refresh":
92
+ return self.answer(404, b'{"ok":false,"error":"not found"}')
93
+ if self.headers.get("Origin") not in (f"http://127.0.0.1:{port}", f"http://localhost:{port}"):
94
+ return self.answer(403, b'{"ok":false,"error":"only the agent map pages can refresh"}')
95
+ start = time.time()
96
+ with Handler.busy: # two clicks: the second waits and then sees the fresh pages
97
+ try:
98
+ p = subprocess.run([sys.executable, "-I", str(SCRIPTS / "agent_map.py"), "refresh"],
99
+ capture_output=True, text=True, timeout=900)
100
+ ok, err = p.returncode == 0, (p.stderr or p.stdout).strip()[-300:]
101
+ except (OSError, subprocess.SubprocessError) as e:
102
+ ok, err = False, str(e)
103
+ Handler.last_used = time.time()
104
+ body = {"ok": ok, "seconds": round(time.time() - start)}
105
+ if not ok:
106
+ body["error"] = err or "the scan failed (see ~/.hivey/agent-map/reports/latest/nightly.log)"
107
+ return self.answer(200, json.dumps(body).encode())
108
+
109
+
110
+ def serve() -> int:
111
+ REPORTS.mkdir(parents=True, exist_ok=True)
112
+ try:
113
+ httpd = http.server.ThreadingHTTPServer(("127.0.0.1", PREFERRED_PORT), Handler)
114
+ except OSError: # taken: any free port
115
+ httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
116
+ port = httpd.server_address[1]
117
+ INFO.write_text(json.dumps({"port": port, "pid": os.getpid()}))
118
+
119
+ def watchdog() -> None:
120
+ while True:
121
+ time.sleep(60)
122
+ if time.time() - Handler.last_used > IDLE_SECONDS and not Handler.busy.locked():
123
+ httpd.shutdown()
124
+ return
125
+
126
+ threading.Thread(target=watchdog, daemon=True).start()
127
+ print(f"agent map pages: http://127.0.0.1:{port}/latest/agent-stats.html", flush=True)
128
+ httpd.serve_forever()
129
+ try:
130
+ if json.loads(INFO.read_text()).get("pid") == os.getpid():
131
+ INFO.unlink()
132
+ except (OSError, ValueError):
133
+ pass
134
+ return 0
@@ -59,10 +59,13 @@ def write_sessions_page(snap: dict, folder: Path) -> None:
59
59
  pa = per_agent[a["agent"]]
60
60
  tok = a["input"] + a["output"] + a["cache_read"] + a["cache_write"]
61
61
  warn = " ⚠️" if pa["long"] else ""
62
+ win = a.get("window") or ""
63
+ win_cell = (f'<span class="win {"big" if win == "1M" else "std"}">{"1M" if win == "1M" else "200k"}</span>'
64
+ if win else '<span class=dim>—</span>')
62
65
  arows.append(
63
66
  f"<tr><td><b>{e(a['agent'])}</b></td><td class=num>{pa['n']}</td>"
64
67
  f"<td class=cost>{bar(a['cost_usd'], top_agent)}<span>{money(a['cost_usd'])}</span></td>"
65
- f"<td class=num>{mtok(tok)}</td><td class=num>{mtok(pa['peak'])}{warn}</td>"
68
+ f"<td class=num>{mtok(tok)}</td><td class=num>{mtok(pa['peak'])}{warn}</td><td>{win_cell}</td>"
66
69
  f"<td>{e(', '.join(model_name(m) for m in a['models'][:2]))}</td>"
67
70
  f"<td class=dim>{e((a.get('last_active') or '')[:16].replace('T', ' '))}</td></tr>")
68
71
 
@@ -93,6 +96,14 @@ def write_sessions_page(snap: dict, folder: Path) -> None:
93
96
  tips.append(f"<li><b>{long_n} sessions grew past {LONG_CONTEXT // 1000}k tokens of context</b> and cost "
94
97
  f"{money(long_cost)} ({100 * long_cost / total:.0f}% of the total): every reply re-reads the whole "
95
98
  f"session. Start a new session per task (<code>/clear</code>) and <code>/compact</code> a long one.</li>")
99
+ big = [a["agent"] for a in agents if a.get("window") == "1M" and per_agent[a["agent"]]["long"]]
100
+ if big:
101
+ names = " ".join(big[:8])
102
+ tips.append(f"<li><b>{len(big)} agents with long sessions still get the 1M window</b> ({e(', '.join(big[:8]))}). "
103
+ "The standard window (200k) makes Claude Code compact the session before it grows, so replies "
104
+ f"re-read far less: <code>hivey agent-map context {e(names)} --set standard</code>. "
105
+ "Give one agent the large window back with <code>--set 1M</code>. It applies from the agent's next "
106
+ "start; <code>hivey agent-map context</code> lists every agent's window and peak.</li>")
96
107
  if day_long:
97
108
  tips.append(f"<li><b>{day_long} sessions stayed open 12 hours or more.</b> After a pause the cached context "
98
109
  "expires and is written again in full, which costs more than reading it.</li>")
@@ -101,6 +112,8 @@ def write_sessions_page(snap: dict, folder: Path) -> None:
101
112
  "reviews and diagrams cost half on Sonnet (<code>/model sonnet</code>).</li>")
102
113
  n_total = sessions[0]["count_total"] if sessions else 0
103
114
 
115
+ import enhance
116
+ NAV, NAV_CSS = enhance.nav("agent-sessions.html", snap.get('generated', '')), enhance.NAV_CSS
104
117
  page = f"""<!doctype html><html lang=en><meta charset=utf-8>
105
118
  <meta name=viewport content="width=device-width,initial-scale=1">
106
119
  <title>Interactive sessions · {e(snap.get('generated', '')[:16])}</title>
@@ -109,7 +122,7 @@ def write_sessions_page(snap: dict, folder: Path) -> None:
109
122
  @media (prefers-color-scheme:dark){{:root{{--bg:#0d1117;--fg:#e6edf3;--mute:#8b949e;--line:#30363d;--card:#161b22;--accent:#79a8ff}}}}
110
123
  body{{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}}
111
124
  main{{max-width:1180px;margin:0 auto;padding:28px 24px 60px}}
112
- nav a{{color:var(--accent);margin-right:18px;text-decoration:none;font-weight:600}} nav a.on{{color:var(--fg)}}
125
+ {NAV_CSS}
113
126
  h1{{font-size:26px;margin:18px 0 4px}} h2{{font-size:19px;margin:34px 0 10px}}
114
127
  .lead{{color:var(--mute);margin:0 0 14px}}
115
128
  .kpis{{display:flex;gap:12px;flex-wrap:wrap;margin:14px 0}}
@@ -125,10 +138,12 @@ td{{border-bottom:1px solid var(--line);padding:7px 8px;vertical-align:middle}}
125
138
  .prompt{{max-width:330px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--mute);font-size:13px}}
126
139
  .tips{{border:1px solid var(--line);background:var(--card);border-radius:10px;padding:6px 18px}}
127
140
  .tips li{{margin:8px 0}} code{{font:12.5px ui-monospace,Menlo,monospace}}
141
+ .win{{font-size:12px;font-weight:600;padding:1px 7px;border-radius:9px;white-space:nowrap}}
142
+ .win.big{{background:color-mix(in srgb,hsl(30,90%,55%) 22%,transparent)}} .win.std{{background:color-mix(in srgb,hsl(130,55%,45%) 20%,transparent)}}
128
143
  .note{{color:var(--mute);font-size:13px;margin-top:30px}}
129
144
  </style>
130
145
  <main>
131
- <nav><a href="agent-stats.html">Stats</a><a href="agent-map.html">Map</a><a href="agent-logs.html">Logs</a><a class=on href="agent-sessions.html">Sessions</a></nav>
146
+ {NAV}
132
147
  <h1>Your interactive sessions, last {days} days</h1>
133
148
  <p class=lead>Chats with agents in a terminal (Claude Code, Codex, Grok), kept apart from the automated jobs on the map.
134
149
  Costs are API-equivalent: a Max plan is not billed per token, but these use up its limits.</p>
@@ -140,14 +155,15 @@ Costs are API-equivalent: a Max plan is not billed per token, but these use up i
140
155
  </div>
141
156
  {f'<h2>How to spend less</h2><ul class=tips>{"".join(tips)}</ul>' if tips else ''}
142
157
  <h2>By agent</h2>
143
- <table><tr><th>Agent</th><th class=num>Sessions</th><th>Cost</th><th class=num>Tokens</th><th class=num>Peak context</th><th>Models</th><th>Last active</th></tr>
144
- {''.join(arows) or '<tr><td colspan=7>No interactive sessions in this window.</td></tr>'}</table>
158
+ <table><tr><th>Agent</th><th class=num>Sessions</th><th>Cost</th><th class=num>Tokens</th><th class=num>Peak context</th><th title="context window of this agent's next session">Window</th><th>Models</th><th>Last active</th></tr>
159
+ {''.join(arows) or '<tr><td colspan=8>No interactive sessions in this window.</td></tr>'}</table>
145
160
  <h2>By day</h2>
146
161
  <table><tr><th>Day</th><th>Cost</th><th class=num>Tokens</th><th>Agents that day (top 3)</th></tr>{''.join(drows)}</table>
147
162
  <h2>Costliest sessions</h2>
148
163
  <table><tr><th class=num>Cost</th><th>Agent</th><th>When</th><th class=num>Calls</th><th class=num>Peak context</th><th>Models</th><th>First message</th></tr>
149
164
  {''.join(srows)}</table>
150
- <p class=note>⚠️ peak context over {LONG_CONTEXT // 1000}k tokens. From the Claude Code, Codex and Grok session files on this
165
+ <p class=note>⚠️ peak context over {LONG_CONTEXT // 1000}k tokens. Window: the context size this agent's next session
166
+ gets (1M, or the standard 200k that compacts early), from its folder's <code>.claude/settings.json</code>. From the Claude Code, Codex and Grok session files on this
151
167
  Mac; Claude Code keeps 15 days of them. Scan {e(snap.get('generated', '')[:16].replace('T', ' '))}.</p>
152
168
  </main></html>"""
153
169
  (folder / "agent-sessions.html").write_text(page)