@hivey/cli 0.9.51 → 0.9.53

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.51",
3
+ "version": "0.9.53",
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,8 +117,32 @@ 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.
128
+ - **Automated vs interactive:** the map, the stats page and map colours count AUTOMATED work only
129
+ (scheduled jobs, scripts, headless `claude -p` / `codex exec`, scripts' API calls; snapshot `usage`).
130
+ People chatting with agents (Claude Code, Codex, Grok in a terminal; snapshot `interactive`, with one
131
+ entry per session) go to **`agent-sessions.html`**: cost by agent and by day, the costliest sessions with
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
134
+ free one, in `~/.hivey/agent-map/server.json`; stops after 2 h unused) so the navbar's ↻ Refresh
135
+ button works: it runs `agent_map.py refresh` (new scan into the latest report's pages, no model, a few
136
+ seconds; the map keeps the night's boxes) and reloads. Only the served pages can trigger it (Origin
137
+ check). Opened as plain files, the button says to open them from the hivey menu.
138
+ - **Context window per agent** (`context_window.py`): the Sessions page shows each agent's window for its
139
+ next session, 1M or the standard 200k (Claude Code compacts the session before it grows).
140
+ `hivey agent-map context` lists every agent's window and peak; `hivey agent-map context <agent…> --set
141
+ standard|1M` writes `CLAUDE_CODE_DISABLE_1M_CONTEXT` into that agent's `.claude/settings.json` (old
142
+ file copied to `~/.hivey/old/`). A running session keeps its window until it restarts.
143
+ - **Models per job:** the scan reads each job's code for the models it uses, local ones included
144
+ (`nodes[].llm_api.models`: JEV-9B local or Jev on OpenRouter, Claude Opus/Sonnet/Haiku, Grok, DeepSeek,
145
+ Gemini, OpenAI/Codex, Muse, Whisper, Parakeet); the map's info card lists them next to recorded spend.
122
146
  - **Per day:** the stats page charts the top agents' cost per day and lists each day's cost, tokens and
123
147
  top agents (`usage.daily_by_agent` in the snapshot).
124
148
  - **`agent-logs.html`** (run log, written by code): every scheduled job with ✅ ran ok · ⚠️ errors in
@@ -176,6 +200,6 @@ the final message (or the last chunk carrying usage).
176
200
  as `{"model-substring": [in, out, cache_read, cache_write]}` per million tokens). Claude Code on a
177
201
  Max plan and Codex on Plus are not billed per token: call their cost "API-equivalent". Grok CLI and
178
202
  OpenRouter report real cost, used as is.
179
- - Antigravity (`agy`) keeps no token data on disk: it shows as running, not as spend.
203
+ - 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).
180
204
  - Codex sessions are zstd-compressed; without `zstd` on PATH they are skipped.
181
205
  - Read-only: the scan never edits jobs, plists or scripts.
@@ -304,19 +304,44 @@ def blank():
304
304
  return {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "cost_usd": 0.0, "calls": 0}
305
305
 
306
306
 
307
+ def is_interactive(kind: str) -> bool:
308
+ """A person chatting with an agent (Claude Code, Codex or Grok in a terminal), not an automated run
309
+ (scheduled job, headless `claude -p` / `codex exec`, a script's API call)."""
310
+ return kind.endswith("interactive")
311
+
312
+
307
313
  class Usage:
308
314
  def __init__(self, days: int):
309
315
  self.cutoff = since(days)
310
316
  self.table = prices()
311
317
  self.rows = [] # (day, agent, provider, model, kind, usage dict)
312
- self.last_seen: dict[str, dt.datetime] = {}
318
+ self.last_seen: dict[tuple, dt.datetime] = {}
319
+ self.sessions: dict[str, dict] = {} # interactive sessions, one entry each
320
+ self.prompts: dict[str, str] = {} # session id → its first prompt
313
321
 
314
- def add(self, ts, agent, provider, model, kind, inp=0, out=0, read=0, write=0, cost_usd=None, calls=1):
322
+ def add(self, ts, agent, provider, model, kind, inp=0, out=0, read=0, write=0, cost_usd=None, calls=1,
323
+ session=None):
315
324
  if ts is None or ts < self.cutoff:
316
325
  return
317
326
  c = cost(model, inp, out, read, write, self.table) if cost_usd is None else cost_usd
318
- if ts > self.last_seen.get(agent, ts.min.replace(tzinfo=dt.timezone.utc)):
319
- self.last_seen[agent] = ts
327
+ if session and is_interactive(kind):
328
+ se = self.sessions.setdefault(session, {
329
+ "session": session, "agent": agent, "tool": kind.split()[0], "start": ts, "end": ts,
330
+ "cost_usd": 0.0, "calls": 0, "tokens": 0, "output": 0, "max_context": 0, "models": []})
331
+ se.setdefault("agents", [])
332
+ if agent not in se["agents"]:
333
+ se["agents"].append(agent) # a session can move between folders
334
+ se["start"], se["end"] = min(se["start"], ts), max(se["end"], ts)
335
+ se["cost_usd"] += c
336
+ se["calls"] += calls
337
+ se["tokens"] += inp + out + read + write
338
+ se["output"] += out
339
+ se["max_context"] = max(se["max_context"], inp + read + write)
340
+ if model and model not in se["models"]:
341
+ se["models"].append(model)
342
+ key = (agent, is_interactive(kind))
343
+ if ts > self.last_seen.get(key, ts.min.replace(tzinfo=dt.timezone.utc)):
344
+ self.last_seen[key] = ts
320
345
  self.rows.append((ts.astimezone().date().isoformat(), agent, provider, model or "?", kind,
321
346
  {"input": inp, "output": out, "cache_read": read, "cache_write": write,
322
347
  "cost_usd": c, "calls": calls}))
@@ -334,6 +359,8 @@ class Usage:
334
359
  with fh:
335
360
  for line in fh:
336
361
  if '"usage"' not in line:
362
+ if '"type":"user"' in line:
363
+ self.first_prompt(line)
337
364
  continue
338
365
  try:
339
366
  d = json.loads(line)
@@ -353,7 +380,24 @@ class Usage:
353
380
  kind = "headless" if d.get("entrypoint") in ("sdk-cli", "sdk-ts", "sdk-py") else "interactive"
354
381
  self.add(parse_ts(d.get("timestamp", "")), agent_of(d.get("cwd")), provider, model,
355
382
  f"claude-code {kind}", u.get("input_tokens", 0) or 0, u.get("output_tokens", 0) or 0,
356
- u.get("cache_read_input_tokens", 0) or 0, u.get("cache_creation_input_tokens", 0) or 0)
383
+ u.get("cache_read_input_tokens", 0) or 0, u.get("cache_creation_input_tokens", 0) or 0,
384
+ session=d.get("sessionId"))
385
+
386
+ def first_prompt(self, line: str) -> None:
387
+ try:
388
+ d = json.loads(line)
389
+ except ValueError:
390
+ return
391
+ sid = d.get("sessionId")
392
+ if not sid or sid in self.prompts or d.get("isMeta"):
393
+ return
394
+ c = (d.get("message") or {}).get("content")
395
+ if isinstance(c, list):
396
+ c = " ".join(x.get("text", "") for x in c if isinstance(x, dict) and x.get("type") == "text")
397
+ if isinstance(c, str):
398
+ c = " ".join(c.split())
399
+ if c and not c.startswith(("<", "Caveat:", "[Request interrupted")):
400
+ self.prompts[sid] = c[:160]
357
401
 
358
402
  def codex(self):
359
403
  cutoff_epoch = self.cutoff.timestamp()
@@ -370,7 +414,7 @@ class Usage:
370
414
  text = Path(f).read_text(errors="replace")
371
415
  except OSError:
372
416
  continue
373
- cwd, model, last, ts = None, "", None, None
417
+ cwd, model, last, ts, origin, sid = None, "", None, None, "", None
374
418
  for line in text.splitlines():
375
419
  if '"session_meta"' in line or '"turn_context"' in line or '"token_count"' in line:
376
420
  try:
@@ -380,6 +424,8 @@ class Usage:
380
424
  p = d.get("payload") or {}
381
425
  if d.get("type") == "session_meta":
382
426
  cwd = p.get("cwd")
427
+ origin = str(p.get("originator", ""))
428
+ sid = p.get("id")
383
429
  elif d.get("type") == "turn_context":
384
430
  model = p.get("model") or model
385
431
  cwd = p.get("cwd") or cwd
@@ -388,9 +434,10 @@ class Usage:
388
434
  ts = parse_ts(d.get("timestamp", ""))
389
435
  if last:
390
436
  cached = last.get("cached_input_tokens", 0) or 0
391
- self.add(ts, agent_of(cwd), "openai", model or "codex", "codex",
437
+ self.add(ts, agent_of(cwd), "openai", model or "codex",
438
+ "codex headless" if "exec" in origin else "codex interactive",
392
439
  (last.get("input_tokens", 0) or 0) - cached, last.get("output_tokens", 0) or 0, cached,
393
- last.get("cache_write_input_tokens", 0) or 0)
440
+ last.get("cache_write_input_tokens", 0) or 0, session=sid)
394
441
 
395
442
  def grok(self):
396
443
  for f in glob.glob(str(HOME / ".grok/sessions/*/*/usage.json")):
@@ -398,10 +445,12 @@ class Usage:
398
445
  s = d.get("session") or {}
399
446
  folder = Path(f).parent.parent.name.replace("%2F", "/")
400
447
  ticks = s.get("costUsdTicks")
448
+ kind = "grok headless" if folder.startswith(("/tmp", "/private/tmp")) else "grok interactive"
401
449
  self.add(parse_ts(d.get("updatedAt", "")), agent_of(folder), "xai", s.get("primaryModelId", "grok"),
402
- "grok cli", s.get("inputTokens", 0) - s.get("cachedReadTokens", 0), s.get("outputTokens", 0),
450
+ kind, s.get("inputTokens", 0) - s.get("cachedReadTokens", 0), s.get("outputTokens", 0),
403
451
  s.get("cachedReadTokens", 0), s.get("cacheCreationTokens", 0),
404
- cost_usd=ticks / 1e10 if ticks is not None else None, calls=s.get("modelCalls", 1))
452
+ cost_usd=ticks / 1e10 if ticks is not None else None, calls=s.get("modelCalls", 1),
453
+ session=d.get("sessionId"))
405
454
 
406
455
  def ledgers(self):
407
456
  for path, provider_default in ((GUARD_LEDGER, "anthropic"), (SPEND_LOG, None)):
@@ -430,10 +479,13 @@ class Usage:
430
479
  print(f"warning: {step.__name__}: {e}", file=sys.stderr)
431
480
  return self
432
481
 
433
- def summary(self) -> dict:
482
+ def summary(self, interactive: bool = False) -> dict:
483
+ """Automated runs (default) or interactive sessions only."""
484
+ rows = [r for r in self.rows if is_interactive(r[4]) == interactive]
485
+
434
486
  def group(keyf):
435
487
  g = collections.defaultdict(blank)
436
- for row in self.rows:
488
+ for row in rows:
437
489
  acc = g[keyf(row)]
438
490
  for k, v in row[5].items():
439
491
  acc[k] += v
@@ -443,16 +495,16 @@ class Usage:
443
495
  for name, tot in sorted(by_agent.items(), key=lambda kv: -kv[1]["cost_usd"]):
444
496
  models = collections.Counter()
445
497
  providers = collections.Counter()
446
- for r in self.rows:
498
+ for r in rows:
447
499
  if r[1] == name:
448
500
  models[r[3]] += r[5]["cost_usd"] + 1e-12
449
501
  providers[r[2]] += r[5]["cost_usd"] + 1e-12
450
- seen = self.last_seen.get(name)
502
+ seen = self.last_seen.get((name, interactive))
451
503
  agents.append({"agent": name, "last_active": seen.astimezone().isoformat(timespec="minutes") if seen else None,
452
504
  **{k: round(v, 4) if isinstance(v, float) else v for k, v in tot.items()},
453
505
  "models": [m for m, _ in models.most_common()], "providers": [p for p, _ in providers.most_common()]})
454
506
  day_agent = collections.defaultdict(lambda: collections.defaultdict(blank))
455
- for r in self.rows:
507
+ for r in rows:
456
508
  acc = day_agent[r[0]][r[1]]
457
509
  for k, v in r[5].items():
458
510
  acc[k] += v
@@ -472,11 +524,23 @@ class Usage:
472
524
  "kinds": {k: round(v["cost_usd"], 4) for k, v in group(lambda r: r[4]).items()},
473
525
  "daily_cost_by_provider": dict(sorted(daily.items())),
474
526
  "daily_by_agent": daily_agents,
475
- "total_cost_usd": round(sum(r[5]["cost_usd"] for r in self.rows), 2),
476
- "total_tokens": sum(r[5]["input"] + r[5]["output"] + r[5]["cache_read"] + r[5]["cache_write"] for r in self.rows),
477
- "sources_without_tokens": ["antigravity (agy): no per-session token data on disk"],
527
+ "total_cost_usd": round(sum(r[5]["cost_usd"] for r in rows), 2),
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": [], # filled by scan() when something actually runs agy
530
+ **({"sessions": self.session_list()} if interactive else {}),
478
531
  }
479
532
 
533
+ def session_list(self, limit: int = 500) -> list[dict]:
534
+ out = []
535
+ for se in sorted(self.sessions.values(), key=lambda x: -x["cost_usd"])[:limit]:
536
+ out.append({**se, "start": se["start"].astimezone().isoformat(timespec="minutes"),
537
+ "end": se["end"].astimezone().isoformat(timespec="minutes"),
538
+ "hours": round((se["end"] - se["start"]).total_seconds() / 3600, 1),
539
+ "cost_usd": round(se["cost_usd"], 2), "prompt": self.prompts.get(se["session"], ""),
540
+ "count_total": len(self.sessions)})
541
+ return out
542
+
543
+
480
544
 
481
545
  # ---------------------------------------------------------------- descriptions
482
546
 
@@ -562,6 +626,29 @@ def describe_script(path: Path) -> str:
562
626
  return first_sentence(joined) if len(joined) > 20 and not BOILERPLATE.search(joined) else ""
563
627
 
564
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
+
565
652
  def describe_job(j: dict) -> str:
566
653
  for p in job_run_files(j["command"]):
567
654
  pp = Path(p)
@@ -651,6 +738,34 @@ API_MARKERS = {
651
738
  }
652
739
 
653
740
 
741
+ MODEL_PATTERNS = [ # (regex over a script's code, the model name shown)
742
+ (r"jev \(openrouter\)|openrouter[^\n]{0,80}\bjev\b|\bjev\b[^\n]{0,80}openrouter", "Jev (OpenRouter)"),
743
+ (r"\bJEV[-_ ]?9B\b|jev-server|127\.0\.0\.1:8090|localhost:8090|JEV_BACKEND", "JEV-9B (local)"),
744
+ (r"claude-opus-\d|--model[= ]+[\"']?opus\b", "Claude Opus"),
745
+ (r"claude-sonnet-\d|--model[= ]+[\"']?sonnet\b", "Claude Sonnet"),
746
+ (r"claude-haiku-\d|--model[= ]+[\"']?haiku\b", "Claude Haiku"),
747
+ (r"\bgrok-\d[\w.-]*", "Grok"),
748
+ (r"\bdeepseek[\w./-]*", "DeepSeek"),
749
+ (r"\bgemini-[\d.]+[\w.-]*", "Gemini"),
750
+ (r"\bgpt-[\d.]+[\w.-]*|\bcodex exec\b", "OpenAI / Codex"),
751
+ (r"\bmuse[-_ ]glimmer|muse-glimmer", "Muse Glimmer (local)"),
752
+ (r"\bwhisper\b|mlx[_-]whisper", "Whisper (local)"),
753
+ (r"\bparakeet\b", "Parakeet (local)"),
754
+ ]
755
+
756
+
757
+ def models_in(text: str) -> list[str]:
758
+ found = []
759
+ for rx, name in MODEL_PATTERNS:
760
+ if re.search(rx, text, re.I) and name not in found:
761
+ found.append(name)
762
+ if "JEV-9B (local)" in found and "Jev (OpenRouter)" in found:
763
+ pass # both backends: local first, hosted as fallback
764
+ if any(n.startswith("Claude ") for n in found) or not re.search(r"\bclaude\b", text):
765
+ return found
766
+ return found + ["Claude"] if re.search(API_MARKERS["claude-cli"], text) else found
767
+
768
+
654
769
  def run_files(paths: list[str]) -> list[Path]:
655
770
  """The files a node actually runs: its referenced scripts, the local modules they import and the
656
771
  scripts they call (one level). Agents (folders): their scripts folder."""
@@ -679,7 +794,7 @@ def run_files(paths: list[str]) -> list[Path]:
679
794
  def api_usage(paths: list[str], command: str = "") -> dict:
680
795
  """Which LLM APIs a node's code calls, and which of those already log their spend
681
796
  (hivey_spend logs any provider; claude-api-guard only Anthropic; claude -p is in the transcripts)."""
682
- providers, logged_by, files = set(), set(), []
797
+ providers, logged_by, files, models = set(), set(), [], models_in(command)
683
798
  if re.search(API_MARKERS["claude-cli"], command):
684
799
  providers.add("claude-cli")
685
800
  files.append("(job command)")
@@ -692,14 +807,15 @@ def api_usage(paths: list[str], command: str = "") -> dict:
692
807
  if hit:
693
808
  providers |= hit
694
809
  files.append(short(str(f)))
810
+ models += [m for m in models_in(text) if m not in models]
695
811
  if "hivey_spend" in text:
696
812
  logged_by.add("all")
697
813
  if re.search(r"claude[-_]api[-_]guard", text):
698
814
  logged_by.add("anthropic")
699
- if not providers:
815
+ if not providers and not models:
700
816
  return {}
701
817
  unlogged = sorted(p for p in providers if p != "claude-cli" and "all" not in logged_by and p not in logged_by)
702
- return {"providers": sorted(providers), "unlogged": unlogged, "files": files[:6]}
818
+ return {"providers": sorted(providers), "unlogged": unlogged, "files": files[:6], "models": models}
703
819
 
704
820
 
705
821
  def job_run_files(command: str) -> list[str]:
@@ -733,6 +849,8 @@ def build_links(jobs: list[dict], live: list[dict]) -> tuple[list[dict], dict]:
733
849
  nodes.setdefault(nid, {"id": nid, "label": a["agent"], "type": "agent", "agent": a["agent"], "paths": []})
734
850
  for n in nodes.values():
735
851
  u = api_usage(n["run"], n["command"]) if n["type"] == "job" else api_usage(n["paths"])
852
+ if u and "hivey-agent-map" in n.get("command", ""):
853
+ u["models"] = ["Claude Haiku"] # this map's own run (its code names every model it prices)
736
854
  if u:
737
855
  n["llm_api"] = u
738
856
  touches: dict[str, list[tuple[str, str]]] = collections.defaultdict(list)
@@ -763,8 +881,18 @@ def build_links(jobs: list[dict], live: list[dict]) -> tuple[list[dict], dict]:
763
881
  def scan(days: int) -> dict:
764
882
  jobs = cron_jobs() + launchd_jobs()
765
883
  live = live_agents()
766
- usage = Usage(days).collect().summary()
884
+ collected = Usage(days).collect()
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 ""
767
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"]
768
896
  overrides = load_json(DESCRIPTIONS, {})
769
897
  for j in jobs:
770
898
  j["description"] = overrides.get(j["id"]) or describe_job(j)
@@ -787,10 +915,13 @@ def scan(days: int) -> dict:
787
915
  "jobs": jobs,
788
916
  "live_agents": live,
789
917
  "agent_logs": agent_logs(),
790
- "usage": usage,
918
+ "usage": usage, # automated runs only: scheduled jobs, headless runs, scripts' API calls
919
+ "interactive": interactive, # people chatting with agents: the Sessions page
791
920
  "nodes": nodes,
792
921
  "links_confirmed": load_json(LINKS, []),
793
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),
794
925
  "notes": [
795
926
  "Costs are API-list-price estimates; Claude Code (Max) and Codex (Plus) usage is API-equivalent, not billed.",
796
927
  "Claude Code transcripts older than the weekly purge (15 days) are gone; longer windows undercount.",
@@ -843,6 +974,34 @@ def print_stats(snap: dict) -> None:
843
974
  print(f" {st['resource']}{owner}: " + ", ".join(dict.fromkeys(n['id'] for n in st['nodes'])))
844
975
 
845
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
+
846
1005
  def main() -> int:
847
1006
  ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
848
1007
  sub = ap.add_subparsers(dest="cmd", required=True)
@@ -877,6 +1036,12 @@ def main() -> int:
877
1036
  'e.g. "envsave get es_…" ("" = the normal claude login)')
878
1037
  sc.add_argument("--at", default="06:30", help="HH:MM, local time (default 06:30, after the night's jobs)")
879
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")
880
1045
  lk = sub.add_parser("link")
881
1046
  lk.add_argument("src")
882
1047
  lk.add_argument("dst")
@@ -922,6 +1087,14 @@ def main() -> int:
922
1087
  a.cost, a.kind, a.note)
923
1088
  print(json.dumps(entry))
924
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)
925
1098
  if a.cmd == "link":
926
1099
  links = [l for l in load_json(LINKS, []) if not (l["from"] == a.src and l["to"] == a.dst)]
927
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}
@@ -58,9 +63,23 @@ svg text.hv-stage{cursor:help;text-decoration:underline dotted;text-underline-of
58
63
 
59
64
 
60
65
  def nav(active: str, generated: str) -> str:
61
- links = [("agent-stats.html", "Stats"), ("agent-map.html", "Map"), ("agent-logs.html", "Logs")]
66
+ links = [("agent-stats.html", "Stats"), ("agent-map.html", "Map"), ("agent-logs.html", "Logs"),
67
+ ("agent-sessions.html", "Sessions")]
62
68
  items = "".join(f'<a href="{href}"{" class=on" if href == active else ""}>{label}</a>' for href, label in links)
63
- 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>"""
64
83
 
65
84
 
66
85
  def inject(page: str, css: str, top: str, script: str = "") -> str:
@@ -90,6 +109,11 @@ def model_name(m: str) -> str:
90
109
  return (f"{k.group(1).title()} {k.group(2)}" + (f".{k.group(3)}" if k.group(3) else "")) if k else m
91
110
 
92
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
+
93
117
  def node_data(snap: dict, spec: dict, meta: dict, job_state) -> dict:
94
118
  usage = {a["agent"]: a for a in snap["usage"]["agents"]}
95
119
  try: # what the nightly model (or you) wrote since the scan wins
@@ -116,7 +140,7 @@ def node_data(snap: dict, spec: dict, meta: dict, job_state) -> dict:
116
140
  if cand in jobs_by_name:
117
141
  refs.append(jobs_by_name[cand]["id"])
118
142
  break
119
- names, desc, states = [], m.get("description", ""), []
143
+ names, desc, states, code_models, alerts = [], m.get("description", ""), [], [], []
120
144
  for ref in refs:
121
145
  if overrides.get(ref) and not desc:
122
146
  desc = overrides[ref]
@@ -128,7 +152,11 @@ def node_data(snap: dict, spec: dict, meta: dict, job_state) -> dict:
128
152
  desc = desc or j.get("description", "")
129
153
  emo, words = job_state(j)
130
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"])})
131
157
  sn = snodes.get(ref)
158
+ if sn:
159
+ code_models += [m for m in (sn.get("llm_api") or {}).get("models", []) if m not in code_models]
132
160
  if sn:
133
161
  names.append(sn["label"])
134
162
  desc = desc or sn.get("description", "")
@@ -144,8 +172,12 @@ def node_data(snap: dict, spec: dict, meta: dict, job_state) -> dict:
144
172
  tot["out"] += a["output"]
145
173
  tot["calls"] += a["calls"]
146
174
  models += [model_name(x) for x in a["models"] if model_name(x) not in models]
175
+ # models seen in its code (also local ones that log no tokens), then the ones with recorded tokens
176
+ for mname in models:
177
+ if not any(mname.split()[0].lower() in c.lower() for c in code_models):
178
+ code_models.append(mname)
147
179
  out[n["id"]] = {"refs": refs, "desc": desc, "cost": round(tot["cost"], 2), "tokens": tot["tokens"],
148
- "out": tot["out"], "calls": tot["calls"], "models": models[:4], "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 [],
149
181
  "subject": bool(refs) and n.get("type") != "database"}
150
182
  spend = [d["cost"] for d in out.values() if d["subject"]]
151
183
  top = max(spend, default=0.0)
@@ -166,8 +198,14 @@ document.querySelectorAll('g[data-node-id]').forEach(g=>{
166
198
  const d=D[g.dataset.nodeId]; if(!d) return;
167
199
  if(d.hue!=null){g.querySelectorAll(':scope > rect:not(.c-mask)').forEach(r=>{
168
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
+ }
169
207
  const t=g.querySelector(':scope > title');
170
- 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');}
171
209
  });
172
210
  document.querySelectorAll('svg text').forEach(t=>{
173
211
  const m=/^\s*\d+\s*\/\s*(.+?)\s*$/.exec(t.textContent||''); if(!m) return;
@@ -177,24 +215,28 @@ document.querySelectorAll('svg text').forEach(t=>{
177
215
  t.style.pointerEvents='auto';
178
216
  });
179
217
  let current=null;
180
- 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);}};
181
220
  document.addEventListener('pointerdown',pick,true); document.addEventListener('focusin',pick,true);
182
221
  function fill(meta){
183
- 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();
184
226
  const d=D[current]; if(!d) return;
185
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>']));
186
229
  if(d.subject){
187
- rows.push(['Spend', fmt(d.cost)+' in '+DAYS+' days (API-equivalent)']);
230
+ rows.push(['Spend', fmt(d.cost)+' in '+DAYS+' days, automated runs only (API-equivalent)']);
188
231
  rows.push(['Tokens', tok(d.tokens)+' ('+tok(d.out)+' output) · '+d.calls.toLocaleString()+' calls']);
189
- rows.push(['Models', d.models.length?'<span class="hv-models">'+d.models.map(m=>'<span>'+esc(m)+'</span>').join('')+'</span>':'no LLM calls recorded']);
190
232
  }
233
+ rows.push(['Models', d.models.length?'<span class="hv-models">'+d.models.map(m=>'<span>'+esc(m)+'</span>').join('')+'</span>':'none found']);
191
234
  d.states.forEach(s=>rows.push(['Last run', esc(s)]));
192
- const div=document.createElement('div'); div.className='hv-info';
235
+ const div=document.createElement('div'); div.className='hv-info'; div.dataset.node=current;
193
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>':'');
194
237
  meta.insertAdjacentElement('afterend',div);
195
238
  }
196
- new MutationObserver(()=>document.querySelectorAll('.semantic-passport-meta').forEach(fill))
197
- .observe(document.body,{childList:true,subtree:true});
239
+ new MutationObserver(refill).observe(document.body,{childList:true,subtree:true,characterData:true});
198
240
  })();
199
241
  """
200
242
 
@@ -218,5 +260,6 @@ def enhance_folder(folder: Path, snap: dict, job_state) -> None:
218
260
  .replace("__DAYS__", json.dumps(snap.get("window_days", 7))))
219
261
  legend = (f'<div class="hv-legend"><b>Spend, last {snap.get("window_days", 7)} days</b><div class="bar"></div>'
220
262
  f'<div class="ends"><span>$0</span><span>{money(top)}</span></div>'
221
- 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>')
222
265
  page.write_text(inject(page.read_text(), NAV_CSS + MAP_CSS, nav("agent-map.html", generated) + legend, script))
@@ -96,9 +96,8 @@ def write_stats(snap: dict, folder: Path) -> None:
96
96
  w.writerow([a["agent"], round(a["cost_usd"], 2)])
97
97
 
98
98
  kinds = u["kinds"]
99
- interactive = sum(v for k, v in kinds.items() if "interactive" in k)
100
99
  headless = sum(v for k, v in kinds.items() if "headless" in k)
101
- api = total - interactive - headless
100
+ api = total - headless
102
101
  models = sorted(u["models"].items(), key=lambda kv: -kv[1]["cost_usd"])
103
102
  jobs = snap["jobs"]
104
103
  failing = [j for j in jobs if job_state(j)[0] == "❌"]
@@ -108,21 +107,24 @@ def write_stats(snap: dict, folder: Path) -> None:
108
107
  pct = lambda v: f"{100 * v / total:.0f}%" if total else "0%"
109
108
 
110
109
  L = []
111
- L.append(f"# What ran on this Mac in the last {days} days, and what did it cost? {{#agent-stats}}\n")
110
+ inter = snap.get("interactive", {})
111
+ L.append(f"# What ran on its own on this Mac in the last {days} days, and what did it cost? {{#agent-stats}}\n")
112
112
  if top:
113
- L.append(f"Your agents used about **{money(total)} of API-equivalent tokens** in {days} days; "
114
- f"**{cell(top['agent'])} used {money(top['cost_usd'])}** of it ({pct(top['cost_usd'])}).\n")
113
+ L.append(f"Your scheduled jobs, scripts and headless agents used about **{money(total)} of tokens** in "
114
+ f"{days} days; **{cell(top['agent'])} used {money(top['cost_usd'])}** of it ({pct(top['cost_usd'])}).\n")
115
115
  else:
116
- L.append(f"No token use was recorded in the last {days} days.\n")
117
- L.append(f"- {pct(interactive)} of the cost is interactive Claude Code ({money(interactive)}); "
118
- f"headless runs cost {money(headless)} and direct API calls {money(api)}.")
116
+ L.append(f"No automated token use was recorded in the last {days} days.\n")
117
+ L.append(f"- Headless agent runs cost {money(headless)} and scripts' direct API calls {money(api)}; local "
118
+ f"models (JEV, Whisper) cost nothing.")
119
+ if inter.get("total_cost_usd"):
120
+ L.append(f"- Your interactive sessions are not counted here: {money(inter['total_cost_usd'])} in "
121
+ f"{(inter.get('sessions') or [{}])[0].get('count_total', 0)} sessions, on the Sessions page (`agent-sessions.html`).")
119
122
  if models:
120
123
  L.append("- " + "; ".join(f"{cell(model_name(m))} {money(v['cost_usd'])}" for m, v in models[:3]) + ".")
121
124
  states = [job_state(j)[0] for j in jobs]
122
125
  tally = ", ".join(f"{emo} {states.count(emo)}" for emo in ("✅", "⚠️", "❌", "⏳", "❔") if states.count(emo))
123
- L.append(f"- {len(jobs)} scheduled jobs ({n_cron} cron, {len(jobs) - n_cron} launchd): {tally}.")
124
- L.append(f"- {len(snap['links_confirmed'])} confirmed links between jobs and agents; "
125
- f"{len(gaps)} with LLM calls not logged yet.\n")
126
+ L.append(f"- {len(jobs)} scheduled jobs ({n_cron} cron, {len(jobs) - n_cron} launchd): {tally}; "
127
+ f"{len(snap['links_confirmed'])} links between them; {len(gaps)} with LLM calls not logged yet.\n")
126
128
  L.append(f'@answer scope="last {days} days to {snap["generated"][:10]} · costs are list-price estimates · '
127
129
  f'Claude Code (Max) and Codex (Plus) are not billed per token"')
128
130
  L.append("@meta locale=en")
@@ -249,6 +251,11 @@ def job_state(j: dict) -> tuple[str, str]:
249
251
 
250
252
  AGENT_STATE = {"working": ("🟢", "working"), "running": ("🟢", "running"), "blocked": ("🔴", "blocked, needs you"),
251
253
  "idle": ("⚪", "idle"), "done": ("✅", "done"), "gone": ("⚫", "not running")}
254
+ def job_anchor(job_id: str) -> str:
255
+ """The logs page anchor of a job (the map links to it)."""
256
+ return "job-" + re.sub(r"[^a-z0-9]+", "-", job_id.lower()).strip("-")
257
+
258
+
252
259
  ORDER = {"❌": 0, "⚠️": 1, "🔴": 1, "⏳": 2, "🟢": 2, "❔": 3, "⚪": 4, "✅": 4, "⚫": 5}
253
260
 
254
261
 
@@ -257,6 +264,7 @@ def write_logs_page(snap: dict, folder: Path) -> None:
257
264
  e = html.escape
258
265
  jobs = sorted(snap["jobs"], key=lambda j: (ORDER.get(job_state(j)[0], 9), j["name"]))
259
266
  usage = {a["agent"]: a for a in snap["usage"]["agents"]}
267
+ inter_usage = {a["agent"]: a for a in (snap.get("interactive") or {}).get("agents", [])}
260
268
  logs = snap.get("agent_logs", {})
261
269
  live: dict[str, dict] = {}
262
270
  for a in snap["live_agents"]:
@@ -264,7 +272,8 @@ def write_logs_page(snap: dict, folder: Path) -> None:
264
272
  if not cur or ORDER.get(AGENT_STATE.get(a["status"], ("⚪",))[0], 9) < ORDER.get(AGENT_STATE.get(cur["status"], ("⚪",))[0], 9):
265
273
  live[a["agent"]] = a
266
274
  names = sorted(set(live) | {n["label"] for n in snap["nodes"] if n["type"] == "agent"}
267
- | {a for a in usage if usage[a]["cost_usd"] >= 0.5})
275
+ | {a for a in usage if usage[a]["cost_usd"] >= 0.5}
276
+ | {a for a in inter_usage if inter_usage[a]["cost_usd"] >= 0.5})
268
277
 
269
278
  def details(body: list[str]) -> str:
270
279
  return "".join(body)
@@ -291,12 +300,12 @@ def write_logs_page(snap: dict, folder: Path) -> None:
291
300
  f"<p class=meta>command <code>{e(j['command'][:400])}</code></p>"] + log_block(j)
292
301
  if not j.get("log"):
293
302
  body.append("<p class=meta>this job writes no log file hivey can find.</p>")
294
- rows.append(f"<details class=row data-state='{emo}'><summary><span class=emo>{emo}</span>"
303
+ rows.append(f"<details class=row id='{job_anchor(j['id'])}' data-state='{emo}'><summary><span class=emo>{emo}</span>"
295
304
  f"<span class=name><b>{e(j['name'])}</b><small class=desc>{e(j.get('description') or '')}</small></span>"
296
305
  f"<span class=sub>{e(words)}</span><span class=when>{e(last)}</span>"
297
306
  f"<span class=issue>{e(issue[:110])}</span></summary>{details(body)}</details>")
298
307
  arows = []
299
- dormant = [n for n in names if n not in live and n not in usage and not logs.get(n)]
308
+ dormant = [n for n in names if n not in live and n not in usage and n not in inter_usage and not logs.get(n)]
300
309
  names = [n for n in names if n not in dormant]
301
310
  for name in sorted(names, key=lambda n: (ORDER.get(AGENT_STATE.get(live.get(n, {}).get("status", "gone"), ("⚫",))[0], 9), n)):
302
311
  a = live.get(name)
@@ -305,15 +314,17 @@ def write_logs_page(snap: dict, folder: Path) -> None:
305
314
  if info.get("errors") and emo in ("⚪", "✅", "⚫"):
306
315
  emo, words = "⚠️", words + ", errors in its log"
307
316
  u = usage.get(name, {})
308
- cost = f"${u['cost_usd']:,.2f} in {snap['window_days']} days" if u else "no token use"
317
+ iu = inter_usage.get(name, {})
318
+ parts = ([f"automated ${u['cost_usd']:,.2f}"] if u else []) + ([f"chats ${iu['cost_usd']:,.2f}"] if iu else [])
319
+ cost = (" · ".join(parts) + f" in {snap['window_days']} days") if parts else "no token use"
309
320
  body = [f"<p class=meta>{e(a['where'] if a else 'not open in hivey')} · {e(a.get('cwd', '') if a else '')}"
310
- f" · last active {e(u.get('last_active') or '?')} · {e(cost)}"
311
- + (f" · {e(', '.join(u.get('models', [])[:2]))}" if u else "") + "</p>"]
321
+ f" · last active {e((u or iu).get('last_active') or '?')} · {e(cost)}"
322
+ + (f" · {e(', '.join((u or iu).get('models', [])[:2]))}" if (u or iu) else "") + "</p>"]
312
323
  body += log_block(info) if info else ["<p class=meta>no <code>logs/</code> folder in this agent.</p>"]
313
324
  adesc = next((n.get("description", "") for n in snap["nodes"] if n["type"] == "agent" and n["label"] == name), "")
314
325
  arows.append(f"<details class=row><summary><span class=emo>{emo}</span>"
315
326
  f"<span class=name><b>{e(name)}</b><small class=desc>{e(adesc)}</small></span>"
316
- f"<span class=sub>{e(words)}</span><span class=when>{e((u.get('last_active') or '')[:16].replace('T', ' '))}</span>"
327
+ f"<span class=sub>{e(words)}</span><span class=when>{e(((u or iu).get('last_active') or '')[:16].replace('T', ' '))}</span>"
317
328
  f"<span class=issue>{e(cost)}</span></summary>{details(body)}</details>")
318
329
  if dormant:
319
330
  arows.append(f"<details class=row><summary><span class=emo>⚫</span><b>{len(dormant)} dormant agents</b>"
@@ -321,6 +332,8 @@ def write_logs_page(snap: dict, folder: Path) -> None:
321
332
  f"<span class=issue>{e(', '.join(dormant[:8]))}…</span></summary>"
322
333
  f"<p class=meta>{e(', '.join(dormant))}</p></details>")
323
334
  summary = " · ".join(f"{k} {v}" for k, v in sorted(counts.items(), key=lambda kv: ORDER.get(kv[0], 9)))
335
+ import enhance
336
+ NAV, NAV_CSS = enhance.nav("agent-logs.html", snap['generated']), enhance.NAV_CSS
324
337
  page = f"""<!doctype html><html lang=en><meta charset=utf-8>
325
338
  <meta name=viewport content="width=device-width,initial-scale=1">
326
339
  <title>Agent logs · {e(snap['generated'][:16])}</title>
@@ -329,7 +342,7 @@ def write_logs_page(snap: dict, folder: Path) -> None:
329
342
  @media (prefers-color-scheme:dark){{:root{{--bg:#0d1117;--fg:#e6edf3;--mute:#8b949e;--line:#30363d;--card:#161b22;--accent:#79a8ff;--pre:#0b0f14}}}}
330
343
  body{{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}}
331
344
  main{{max-width:1180px;margin:0 auto;padding:28px 24px 60px}}
332
- nav a{{color:var(--accent);margin-right:18px;text-decoration:none;font-weight:600}} nav a.on{{color:var(--fg)}}
345
+ {NAV_CSS}
333
346
  h1{{font-size:26px;margin:18px 0 4px}} h2{{font-size:19px;margin:34px 0 10px}}
334
347
  .lead{{color:var(--mute);margin:0 0 6px}} .counts{{font-size:17px;margin:10px 0 0}}
335
348
  .row{{border:1px solid var(--line);background:var(--card);border-radius:10px;margin:7px 0}}
@@ -345,7 +358,7 @@ pre{{background:var(--pre);border:1px solid var(--line);border-radius:8px;paddin
345
358
  @media (max-width:760px){{summary{{grid-template-columns:28px 1fr}} .sub,.when,.issue{{grid-column:2}}}}
346
359
  </style>
347
360
  <main>
348
- <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></nav>
361
+ {NAV}
349
362
  <h1>Did every job and agent run?</h1>
350
363
  <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>
351
364
  <p class=counts>Scheduled jobs: {summary}</p>
@@ -356,7 +369,10 @@ pre{{background:var(--pre);border:1px solid var(--line);border-radius:8px;paddin
356
369
  <p class=legend>✅ ran ok · ⚠️ errors in its log or a missed run · ❌ failed (non-zero exit) or not loaded · ⏳ running ·
357
370
  ❔ no log · 🟢 working · 🔴 blocked, needs you · ⚪ idle · ⚫ not running. "Issues" are the error lines among the
358
371
  last 40 lines of each log, so an old error can show until the log moves on.</p>
359
- </main></html>"""
372
+ </main>
373
+ <script>(function(){{const open=()=>{{const d=location.hash&&document.getElementById(location.hash.slice(1));
374
+ if(d&&d.tagName==='DETAILS'){{d.open=true;d.scrollIntoView({{block:'start'}});}}}};open();addEventListener('hashchange',open);}})();</script>
375
+ </html>"""
360
376
  (folder / "agent-logs.html").write_text(page)
361
377
 
362
378
 
@@ -394,12 +410,22 @@ already built: do not touch stats.archify.md or agent-stats.html.
394
410
  python3 -I {scripts}/agent_map.py link <from-id> <to-id> --via "<what flows>" --evidence "<file:line>"
395
411
  Skip anything unclear or coincidental. Then rerun: python3 -I {scripts}/agent_map.py scan --out snapshot.json
396
412
  2. Map: {map_task}
397
- Costs and status go in each node's sublabel (from usage.agents and jobs in snapshot.json); keep at most
398
- 25 nodes on 5 stages x rows 0-4; refresh the numbers in the cards.
399
- 3. Descriptions: every node in snapshot.json has a "description" (what it does). For each job and agent
400
- whose description is empty or does not say what it does (an instruction to the agent, "You are X"),
401
- read its brief or script (first lines only) and write ONE plain sentence of at most 18 words into
402
- ~/.hivey/agent-map/descriptions.json ({{"<node id>": "<sentence>"}}; keep the entries already there).
413
+ The map shows AUTOMATED work only: scheduled jobs, scripts and headless agents, the data they pass
414
+ to each other, and the models each one uses (any model: JEV, Claude, DeepSeek, Grok, Codex, Whisper;
415
+ nodes[].llm_api.models in snapshot.json). People chatting with agents (interactive sessions) are on
416
+ another page: never show their spend; drop an agent that has no automated runs and no data links,
417
+ and keep a consumer agent (one a job feeds) without its interactive cost. Each node's sublabel holds
418
+ its schedule or role, its models and its automated cost when it has one ("cron 04:15 · Grok + Sonnet ·
419
+ $0.40"); spend is usage.agents (automated only). Keep at most 25 nodes on 5 stages x rows 0-4;
420
+ refresh the numbers in the cards (automated spend, models in use, needs attention).
421
+ 3. Descriptions: every node in snapshot.json has a "description" (what it does). snapshot.json
422
+ "descriptions_to_write" lists the ids whose description is empty, cut off, copied from a brief
423
+ ("You are X", "Own the…") or shared with another job. For each, read its brief, script or command
424
+ (first lines only) and write ONE plain sentence into ~/.hivey/agent-map/descriptions.json
425
+ ({{"<node id>": "<sentence>"}}; keep the entries already there). Rules: 8 to 18 words; start with a
426
+ verb ("Ranks…", "Downloads…", "Paper-trades…"); say what it does and what it produces or where;
427
+ no "you", no dates, no ids, no trailing "…"; different jobs get different sentences (say what
428
+ sets each apart, e.g. "places the orders" vs "writes the report").
403
429
  Then write map-meta.json in this folder: {{"nodes": {{"<map node id>": {{"refs": [<snapshot node ids
404
430
  this box stands for>], "description": "<one sentence>"}}}}, "stages": {{"<stage label>": "<what this
405
431
  column holds, one sentence>"}}}}. A box that folds several jobs lists all of them in refs.
@@ -494,6 +520,8 @@ def nightly(scan, days: int, model: str, use_llm: bool) -> int:
494
520
  (STATE / "snapshot.json").write_text(json.dumps(snap, indent=1, default=str))
495
521
  write_stats(snap, folder)
496
522
  write_logs_page(snap, folder)
523
+ import sessions_page
524
+ sessions_page.write_sessions_page(snap, folder)
497
525
  ok, msg = finalize(folder, "explainer", "stats.archify.md", "agent-stats.html")
498
526
  log(folder, f"stats page: {'ok' if ok else 'FAILED ' + msg}")
499
527
 
@@ -531,6 +559,30 @@ def nightly(scan, days: int, model: str, use_llm: bool) -> int:
531
559
  return 0 if ok else 1
532
560
 
533
561
 
562
+ def refresh(scan, days: int, model: str) -> int:
563
+ """The Refresh button: a new scan rewrites the latest report's pages in place (stats, run log,
564
+ sessions, the map's colours and info cards). No model run, so it is free; the map's boxes stay
565
+ as the night drew them. With no report yet it builds one (also without a model)."""
566
+ folder = latest_report()
567
+ if not folder:
568
+ return nightly(scan, days, model, False)
569
+ log(folder, f"refresh: scan, last {days} days")
570
+ snap = scan(days)
571
+ (STATE / "snapshot.json").write_text(json.dumps(snap, indent=1, default=str))
572
+ write_stats(snap, folder)
573
+ write_logs_page(snap, folder)
574
+ import sessions_page
575
+ sessions_page.write_sessions_page(snap, folder)
576
+ ok, msg = finalize(folder, "explainer", "stats.archify.md", "agent-stats.html")
577
+ try:
578
+ import enhance
579
+ enhance.enhance_folder(folder, json.loads((folder / "snapshot.json").read_text()), job_state)
580
+ except Exception as e:
581
+ log(folder, f"enhance failed: {e}")
582
+ log(folder, f"refresh: {'ok' if ok else 'stats page FAILED ' + msg}")
583
+ return 0 if ok else 1
584
+
585
+
534
586
  # ---------------------------------------------------------------- open
535
587
 
536
588
  def latest_report() -> Path | None:
@@ -549,10 +601,14 @@ def notify(text: str) -> None:
549
601
  def open_latest(model: str) -> int:
550
602
  folder = latest_report()
551
603
  if folder:
552
- for page in ("agent-stats.html", "agent-map.html", "agent-logs.html"):
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"):
553
609
  if (folder / page).is_file():
554
- subprocess.run(["open", str(folder / page)], capture_output=True)
555
- print(f"opened {folder}")
610
+ subprocess.run(["open", base + page if base else str(folder / page)], capture_output=True)
611
+ print(f"opened {base or folder}")
556
612
  return 0
557
613
  # No report yet: build the first one in the background and open it when it is ready.
558
614
  REPORTS.mkdir(parents=True, exist_ok=True)
@@ -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
@@ -0,0 +1,169 @@
1
+ """The Sessions page (agent-sessions.html): what your interactive sessions with agents cost.
2
+
3
+ Interactive = a person chatting with an agent in a terminal (Claude Code, Codex, Grok). These are
4
+ kept out of the map and the stats page, which show automated work only. Written from the snapshot's
5
+ `interactive` summary, without an LLM. Python standard library only.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import collections
10
+ import datetime as dt
11
+ import html
12
+ import re
13
+ from pathlib import Path
14
+
15
+ e = html.escape
16
+ LONG_CONTEXT = 300_000 # tokens: above this every reply re-reads a very large session
17
+
18
+
19
+ def money(v: float) -> str:
20
+ return f"${v:,.2f}"
21
+
22
+
23
+ def mtok(n: int) -> str:
24
+ return f"{n / 1e6:,.1f}M" if n >= 1e6 else f"{n / 1e3:,.0f}k" if n >= 1e3 else str(n)
25
+
26
+
27
+ def model_name(m: str) -> str:
28
+ m = m.rsplit("/", 1)[-1]
29
+ k = re.match(r"claude-(opus|sonnet|haiku)-(\d+)(?:-(\d{1,2}))?(?!\d)", m)
30
+ return (f"{k.group(1).title()} {k.group(2)}" + (f".{k.group(3)}" if k.group(3) else "")) if k else m
31
+
32
+
33
+ def bar(value: float, top: float) -> str:
34
+ pct = 0 if top <= 0 else max(1.5, 100 * value / top)
35
+ return f'<span class=bar><i style="width:{pct:.1f}%"></i></span>'
36
+
37
+
38
+ def write_sessions_page(snap: dict, folder: Path) -> None:
39
+ inter = snap.get("interactive") or {}
40
+ sessions = inter.get("sessions") or []
41
+ days = snap.get("window_days", 7)
42
+ total = inter.get("total_cost_usd", 0.0)
43
+ agents = inter.get("agents") or []
44
+ per_agent = collections.defaultdict(lambda: {"n": 0, "peak": 0, "long": 0})
45
+ for s in sessions:
46
+ for name in s.get("agents") or [s["agent"]]:
47
+ pa = per_agent[name]
48
+ pa["n"] += 1
49
+ pa["peak"] = max(pa["peak"], s["max_context"])
50
+ pa["long"] += s["max_context"] > LONG_CONTEXT
51
+ long_cost = sum(s["cost_usd"] for s in sessions if s["max_context"] > LONG_CONTEXT)
52
+ long_n = sum(1 for s in sessions if s["max_context"] > LONG_CONTEXT)
53
+ day_long = sum(1 for s in sessions if s["hours"] >= 12)
54
+ models = sorted((inter.get("models") or {}).items(), key=lambda kv: -kv[1]["cost_usd"])
55
+
56
+ top_agent = max((a["cost_usd"] for a in agents), default=0.0)
57
+ arows = []
58
+ for a in agents[:25]:
59
+ pa = per_agent[a["agent"]]
60
+ tok = a["input"] + a["output"] + a["cache_read"] + a["cache_write"]
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>')
65
+ arows.append(
66
+ f"<tr><td><b>{e(a['agent'])}</b></td><td class=num>{pa['n']}</td>"
67
+ f"<td class=cost>{bar(a['cost_usd'], top_agent)}<span>{money(a['cost_usd'])}</span></td>"
68
+ f"<td class=num>{mtok(tok)}</td><td class=num>{mtok(pa['peak'])}{warn}</td><td>{win_cell}</td>"
69
+ f"<td>{e(', '.join(model_name(m) for m in a['models'][:2]))}</td>"
70
+ f"<td class=dim>{e((a.get('last_active') or '')[:16].replace('T', ' '))}</td></tr>")
71
+
72
+ per_day = inter.get("daily_by_agent") or {}
73
+ day_cost = {d: sum(r["cost_usd"] for r in rows) for d, rows in per_day.items()}
74
+ top_day = max(day_cost.values(), default=0.0)
75
+ drows = []
76
+ for d, rows in per_day.items():
77
+ tops = ", ".join(f"{e(r['agent'])} {money(r['cost_usd'])}" for r in rows[:3])
78
+ drows.append(
79
+ f"<tr><td><b>{dt.date.fromisoformat(d):%a %d %b}</b></td>"
80
+ f"<td class=cost>{bar(day_cost[d], top_day)}<span>{money(day_cost[d])}</span></td>"
81
+ f"<td class=num>{mtok(sum(r['tokens'] for r in rows))}</td><td>{tops}</td></tr>")
82
+
83
+ srows = []
84
+ for s in sessions[:20]:
85
+ ctx_warn = " ⚠️" if s["max_context"] > LONG_CONTEXT else ""
86
+ srows.append(
87
+ f"<tr><td class=num><b>{money(s['cost_usd'])}</b></td><td>{e(s['agent'])}</td>"
88
+ f"<td class=dim>{e(s['start'][5:16].replace('T', ' '))} → {e(s['end'][5:16].replace('T', ' '))}"
89
+ f" · {s['hours']}h</td><td class=num>{s['calls']:,}</td>"
90
+ f"<td class=num>{mtok(s['max_context'])}{ctx_warn}</td>"
91
+ f"<td>{e(', '.join(model_name(m) for m in s['models'][:2]))}</td>"
92
+ f"<td class=prompt title=\"{e(s.get('prompt', ''))}\">{e(s.get('prompt', '') or '—')}</td></tr>")
93
+
94
+ tips = []
95
+ if long_n:
96
+ tips.append(f"<li><b>{long_n} sessions grew past {LONG_CONTEXT // 1000}k tokens of context</b> and cost "
97
+ f"{money(long_cost)} ({100 * long_cost / total:.0f}% of the total): every reply re-reads the whole "
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>")
107
+ if day_long:
108
+ tips.append(f"<li><b>{day_long} sessions stayed open 12 hours or more.</b> After a pause the cached context "
109
+ "expires and is written again in full, which costs more than reading it.</li>")
110
+ if models and "opus" in models[0][0]:
111
+ tips.append(f"<li><b>{e(model_name(models[0][0]))} is {money(models[0][1]['cost_usd'])}</b> of it: drafting, "
112
+ "reviews and diagrams cost half on Sonnet (<code>/model sonnet</code>).</li>")
113
+ n_total = sessions[0]["count_total"] if sessions else 0
114
+
115
+ import enhance
116
+ NAV, NAV_CSS = enhance.nav("agent-sessions.html", snap.get('generated', '')), enhance.NAV_CSS
117
+ page = f"""<!doctype html><html lang=en><meta charset=utf-8>
118
+ <meta name=viewport content="width=device-width,initial-scale=1">
119
+ <title>Interactive sessions · {e(snap.get('generated', '')[:16])}</title>
120
+ <style>
121
+ :root{{--bg:#fff;--fg:#1d2330;--mute:#667085;--line:#e4e7ec;--card:#f8f9fb;--accent:#2f6fec}}
122
+ @media (prefers-color-scheme:dark){{:root{{--bg:#0d1117;--fg:#e6edf3;--mute:#8b949e;--line:#30363d;--card:#161b22;--accent:#79a8ff}}}}
123
+ body{{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}}
124
+ main{{max-width:1180px;margin:0 auto;padding:28px 24px 60px}}
125
+ {NAV_CSS}
126
+ h1{{font-size:26px;margin:18px 0 4px}} h2{{font-size:19px;margin:34px 0 10px}}
127
+ .lead{{color:var(--mute);margin:0 0 14px}}
128
+ .kpis{{display:flex;gap:12px;flex-wrap:wrap;margin:14px 0}}
129
+ .kpi{{border:1px solid var(--line);background:var(--card);border-radius:10px;padding:10px 16px;min-width:150px}}
130
+ .kpi b{{display:block;font-size:22px}} .kpi span{{color:var(--mute);font-size:13px}}
131
+ table{{width:100%;border-collapse:collapse;font-size:14px}}
132
+ th{{text-align:left;color:var(--mute);font-weight:600;font-size:12.5px;border-bottom:1px solid var(--line);padding:6px 8px}}
133
+ td{{border-bottom:1px solid var(--line);padding:7px 8px;vertical-align:middle}}
134
+ .num{{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}} .dim{{color:var(--mute);font-size:13px;white-space:nowrap}}
135
+ .cost{{display:flex;align-items:center;gap:8px;min-width:200px}} .cost span{{font-variant-numeric:tabular-nums}}
136
+ .bar{{flex:1;height:8px;border-radius:4px;background:color-mix(in srgb,var(--line) 70%,transparent);overflow:hidden;max-width:160px}}
137
+ .bar i{{display:block;height:100%;background:linear-gradient(90deg,hsl(40,85%,52%),hsl(0,72%,52%))}}
138
+ .prompt{{max-width:330px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--mute);font-size:13px}}
139
+ .tips{{border:1px solid var(--line);background:var(--card);border-radius:10px;padding:6px 18px}}
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)}}
143
+ .note{{color:var(--mute);font-size:13px;margin-top:30px}}
144
+ </style>
145
+ <main>
146
+ {NAV}
147
+ <h1>Your interactive sessions, last {days} days</h1>
148
+ <p class=lead>Chats with agents in a terminal (Claude Code, Codex, Grok), kept apart from the automated jobs on the map.
149
+ Costs are API-equivalent: a Max plan is not billed per token, but these use up its limits.</p>
150
+ <div class=kpis>
151
+ <div class=kpi><b>{money(total)}</b><span>API-equivalent cost</span></div>
152
+ <div class=kpi><b>{n_total}</b><span>sessions</span></div>
153
+ <div class=kpi><b>{mtok(inter.get('total_tokens', 0))}</b><span>tokens (mostly re-read context)</span></div>
154
+ <div class=kpi><b>{e(', '.join(model_name(m) for m, _ in models[:2]) or '—')}</b><span>main models</span></div>
155
+ </div>
156
+ {f'<h2>How to spend less</h2><ul class=tips>{"".join(tips)}</ul>' if tips else ''}
157
+ <h2>By agent</h2>
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>
160
+ <h2>By day</h2>
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>
162
+ <h2>Costliest sessions</h2>
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>
164
+ {''.join(srows)}</table>
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
167
+ Mac; Claude Code keeps 15 days of them. Scan {e(snap.get('generated', '')[:16].replace('T', ' '))}.</p>
168
+ </main></html>"""
169
+ (folder / "agent-sessions.html").write_text(page)