@hivey/cli 0.9.51 → 0.9.52

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.52",
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",
@@ -119,6 +119,14 @@ hivey agent-map schedule install [--at 06:30] [--model haiku] # | remove | sta
119
119
  - **Descriptions** ("what it does"): from a brief's mission, a skill's description or a script's module
120
120
  docstring; the nightly model writes the missing or weak ones to `~/.hivey/agent-map/descriptions.json`
121
121
  (kept, edit freely), which wins over the extracted ones. They show in the map's info cards and the run log.
122
+ - **Automated vs interactive:** the map, the stats page and map colours count AUTOMATED work only
123
+ (scheduled jobs, scripts, headless `claude -p` / `codex exec`, scripts' API calls; snapshot `usage`).
124
+ People chatting with agents (Claude Code, Codex, Grok in a terminal; snapshot `interactive`, with one
125
+ entry per session) go to **`agent-sessions.html`**: cost by agent and by day, the costliest sessions with
126
+ their peak context (⚠️ over 300k tokens), length and first message, and tips to spend less.
127
+ - **Models per job:** the scan reads each job's code for the models it uses, local ones included
128
+ (`nodes[].llm_api.models`: JEV-9B local or Jev on OpenRouter, Claude Opus/Sonnet/Haiku, Grok, DeepSeek,
129
+ Gemini, OpenAI/Codex, Muse, Whisper, Parakeet); the map's info card lists them next to recorded spend.
122
130
  - **Per day:** the stats page charts the top agents' cost per day and lists each day's cost, tokens and
123
131
  top agents (`usage.daily_by_agent` in the snapshot).
124
132
  - **`agent-logs.html`** (run log, written by code): every scheduled job with ✅ ran ok · ⚠️ errors in
@@ -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),
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),
477
529
  "sources_without_tokens": ["antigravity (agy): no per-session token data on disk"],
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
 
@@ -651,6 +715,34 @@ API_MARKERS = {
651
715
  }
652
716
 
653
717
 
718
+ MODEL_PATTERNS = [ # (regex over a script's code, the model name shown)
719
+ (r"jev \(openrouter\)|openrouter[^\n]{0,80}\bjev\b|\bjev\b[^\n]{0,80}openrouter", "Jev (OpenRouter)"),
720
+ (r"\bJEV[-_ ]?9B\b|jev-server|127\.0\.0\.1:8090|localhost:8090|JEV_BACKEND", "JEV-9B (local)"),
721
+ (r"claude-opus-\d|--model[= ]+[\"']?opus\b", "Claude Opus"),
722
+ (r"claude-sonnet-\d|--model[= ]+[\"']?sonnet\b", "Claude Sonnet"),
723
+ (r"claude-haiku-\d|--model[= ]+[\"']?haiku\b", "Claude Haiku"),
724
+ (r"\bgrok-\d[\w.-]*", "Grok"),
725
+ (r"\bdeepseek[\w./-]*", "DeepSeek"),
726
+ (r"\bgemini-[\d.]+[\w.-]*", "Gemini"),
727
+ (r"\bgpt-[\d.]+[\w.-]*|\bcodex exec\b", "OpenAI / Codex"),
728
+ (r"\bmuse[-_ ]glimmer|muse-glimmer", "Muse Glimmer (local)"),
729
+ (r"\bwhisper\b|mlx[_-]whisper", "Whisper (local)"),
730
+ (r"\bparakeet\b", "Parakeet (local)"),
731
+ ]
732
+
733
+
734
+ def models_in(text: str) -> list[str]:
735
+ found = []
736
+ for rx, name in MODEL_PATTERNS:
737
+ if re.search(rx, text, re.I) and name not in found:
738
+ found.append(name)
739
+ if "JEV-9B (local)" in found and "Jev (OpenRouter)" in found:
740
+ pass # both backends: local first, hosted as fallback
741
+ if any(n.startswith("Claude ") for n in found) or not re.search(r"\bclaude\b", text):
742
+ return found
743
+ return found + ["Claude"] if re.search(API_MARKERS["claude-cli"], text) else found
744
+
745
+
654
746
  def run_files(paths: list[str]) -> list[Path]:
655
747
  """The files a node actually runs: its referenced scripts, the local modules they import and the
656
748
  scripts they call (one level). Agents (folders): their scripts folder."""
@@ -679,7 +771,7 @@ def run_files(paths: list[str]) -> list[Path]:
679
771
  def api_usage(paths: list[str], command: str = "") -> dict:
680
772
  """Which LLM APIs a node's code calls, and which of those already log their spend
681
773
  (hivey_spend logs any provider; claude-api-guard only Anthropic; claude -p is in the transcripts)."""
682
- providers, logged_by, files = set(), set(), []
774
+ providers, logged_by, files, models = set(), set(), [], models_in(command)
683
775
  if re.search(API_MARKERS["claude-cli"], command):
684
776
  providers.add("claude-cli")
685
777
  files.append("(job command)")
@@ -692,14 +784,15 @@ def api_usage(paths: list[str], command: str = "") -> dict:
692
784
  if hit:
693
785
  providers |= hit
694
786
  files.append(short(str(f)))
787
+ models += [m for m in models_in(text) if m not in models]
695
788
  if "hivey_spend" in text:
696
789
  logged_by.add("all")
697
790
  if re.search(r"claude[-_]api[-_]guard", text):
698
791
  logged_by.add("anthropic")
699
- if not providers:
792
+ if not providers and not models:
700
793
  return {}
701
794
  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]}
795
+ return {"providers": sorted(providers), "unlogged": unlogged, "files": files[:6], "models": models}
703
796
 
704
797
 
705
798
  def job_run_files(command: str) -> list[str]:
@@ -733,6 +826,8 @@ def build_links(jobs: list[dict], live: list[dict]) -> tuple[list[dict], dict]:
733
826
  nodes.setdefault(nid, {"id": nid, "label": a["agent"], "type": "agent", "agent": a["agent"], "paths": []})
734
827
  for n in nodes.values():
735
828
  u = api_usage(n["run"], n["command"]) if n["type"] == "job" else api_usage(n["paths"])
829
+ if u and "hivey-agent-map" in n.get("command", ""):
830
+ u["models"] = ["Claude Haiku"] # this map's own run (its code names every model it prices)
736
831
  if u:
737
832
  n["llm_api"] = u
738
833
  touches: dict[str, list[tuple[str, str]]] = collections.defaultdict(list)
@@ -763,7 +858,8 @@ def build_links(jobs: list[dict], live: list[dict]) -> tuple[list[dict], dict]:
763
858
  def scan(days: int) -> dict:
764
859
  jobs = cron_jobs() + launchd_jobs()
765
860
  live = live_agents()
766
- usage = Usage(days).collect().summary()
861
+ collected = Usage(days).collect()
862
+ usage, interactive = collected.summary(), collected.summary(interactive=True)
767
863
  nodes, candidates = build_links(jobs, live)
768
864
  overrides = load_json(DESCRIPTIONS, {})
769
865
  for j in jobs:
@@ -787,7 +883,8 @@ def scan(days: int) -> dict:
787
883
  "jobs": jobs,
788
884
  "live_agents": live,
789
885
  "agent_logs": agent_logs(),
790
- "usage": usage,
886
+ "usage": usage, # automated runs only: scheduled jobs, headless runs, scripts' API calls
887
+ "interactive": interactive, # people chatting with agents: the Sessions page
791
888
  "nodes": nodes,
792
889
  "links_confirmed": load_json(LINKS, []),
793
890
  "links_candidates": candidates,
@@ -58,7 +58,8 @@ svg text.hv-stage{cursor:help;text-decoration:underline dotted;text-underline-of
58
58
 
59
59
 
60
60
  def nav(active: str, generated: str) -> str:
61
- links = [("agent-stats.html", "Stats"), ("agent-map.html", "Map"), ("agent-logs.html", "Logs")]
61
+ links = [("agent-stats.html", "Stats"), ("agent-map.html", "Map"), ("agent-logs.html", "Logs"),
62
+ ("agent-sessions.html", "Sessions")]
62
63
  items = "".join(f'<a href="{href}"{" class=on" if href == active else ""}>{label}</a>' for href, label in links)
63
64
  return f'<nav class="hv-nav">{items}<span class="hv-when">scan {html.escape(generated[:16].replace("T", " "))}</span></nav>'
64
65
 
@@ -116,7 +117,7 @@ def node_data(snap: dict, spec: dict, meta: dict, job_state) -> dict:
116
117
  if cand in jobs_by_name:
117
118
  refs.append(jobs_by_name[cand]["id"])
118
119
  break
119
- names, desc, states = [], m.get("description", ""), []
120
+ names, desc, states, code_models = [], m.get("description", ""), [], []
120
121
  for ref in refs:
121
122
  if overrides.get(ref) and not desc:
122
123
  desc = overrides[ref]
@@ -129,6 +130,8 @@ def node_data(snap: dict, spec: dict, meta: dict, job_state) -> dict:
129
130
  emo, words = job_state(j)
130
131
  states.append(f"{emo} {words} · {(j.get('last_run') or j.get('log_modified') or '?').replace('T', ' ')}")
131
132
  sn = snodes.get(ref)
133
+ if sn:
134
+ code_models += [m for m in (sn.get("llm_api") or {}).get("models", []) if m not in code_models]
132
135
  if sn:
133
136
  names.append(sn["label"])
134
137
  desc = desc or sn.get("description", "")
@@ -144,8 +147,12 @@ def node_data(snap: dict, spec: dict, meta: dict, job_state) -> dict:
144
147
  tot["out"] += a["output"]
145
148
  tot["calls"] += a["calls"]
146
149
  models += [model_name(x) for x in a["models"] if model_name(x) not in models]
150
+ # models seen in its code (also local ones that log no tokens), then the ones with recorded tokens
151
+ for mname in models:
152
+ if not any(mname.split()[0].lower() in c.lower() for c in code_models):
153
+ code_models.append(mname)
147
154
  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],
155
+ "out": tot["out"], "calls": tot["calls"], "models": code_models[:5], "states": states[:3],
149
156
  "subject": bool(refs) and n.get("type") != "database"}
150
157
  spend = [d["cost"] for d in out.values() if d["subject"]]
151
158
  top = max(spend, default=0.0)
@@ -184,10 +191,10 @@ function fill(meta){
184
191
  const d=D[current]; if(!d) return;
185
192
  const rows=[];
186
193
  if(d.subject){
187
- rows.push(['Spend', fmt(d.cost)+' in '+DAYS+' days (API-equivalent)']);
194
+ rows.push(['Spend', fmt(d.cost)+' in '+DAYS+' days, automated runs only (API-equivalent)']);
188
195
  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
196
  }
197
+ rows.push(['Models', d.models.length?'<span class="hv-models">'+d.models.map(m=>'<span>'+esc(m)+'</span>').join('')+'</span>':'none found']);
191
198
  d.states.forEach(s=>rows.push(['Last run', esc(s)]));
192
199
  const div=document.createElement('div'); div.className='hv-info';
193
200
  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>':'');
@@ -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")
@@ -257,6 +259,7 @@ def write_logs_page(snap: dict, folder: Path) -> None:
257
259
  e = html.escape
258
260
  jobs = sorted(snap["jobs"], key=lambda j: (ORDER.get(job_state(j)[0], 9), j["name"]))
259
261
  usage = {a["agent"]: a for a in snap["usage"]["agents"]}
262
+ inter_usage = {a["agent"]: a for a in (snap.get("interactive") or {}).get("agents", [])}
260
263
  logs = snap.get("agent_logs", {})
261
264
  live: dict[str, dict] = {}
262
265
  for a in snap["live_agents"]:
@@ -264,7 +267,8 @@ def write_logs_page(snap: dict, folder: Path) -> None:
264
267
  if not cur or ORDER.get(AGENT_STATE.get(a["status"], ("⚪",))[0], 9) < ORDER.get(AGENT_STATE.get(cur["status"], ("⚪",))[0], 9):
265
268
  live[a["agent"]] = a
266
269
  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})
270
+ | {a for a in usage if usage[a]["cost_usd"] >= 0.5}
271
+ | {a for a in inter_usage if inter_usage[a]["cost_usd"] >= 0.5})
268
272
 
269
273
  def details(body: list[str]) -> str:
270
274
  return "".join(body)
@@ -296,7 +300,7 @@ def write_logs_page(snap: dict, folder: Path) -> None:
296
300
  f"<span class=sub>{e(words)}</span><span class=when>{e(last)}</span>"
297
301
  f"<span class=issue>{e(issue[:110])}</span></summary>{details(body)}</details>")
298
302
  arows = []
299
- dormant = [n for n in names if n not in live and n not in usage and not logs.get(n)]
303
+ 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
304
  names = [n for n in names if n not in dormant]
301
305
  for name in sorted(names, key=lambda n: (ORDER.get(AGENT_STATE.get(live.get(n, {}).get("status", "gone"), ("⚫",))[0], 9), n)):
302
306
  a = live.get(name)
@@ -305,15 +309,17 @@ def write_logs_page(snap: dict, folder: Path) -> None:
305
309
  if info.get("errors") and emo in ("⚪", "✅", "⚫"):
306
310
  emo, words = "⚠️", words + ", errors in its log"
307
311
  u = usage.get(name, {})
308
- cost = f"${u['cost_usd']:,.2f} in {snap['window_days']} days" if u else "no token use"
312
+ iu = inter_usage.get(name, {})
313
+ parts = ([f"automated ${u['cost_usd']:,.2f}"] if u else []) + ([f"chats ${iu['cost_usd']:,.2f}"] if iu else [])
314
+ cost = (" · ".join(parts) + f" in {snap['window_days']} days") if parts else "no token use"
309
315
  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>"]
316
+ f" · last active {e((u or iu).get('last_active') or '?')} · {e(cost)}"
317
+ + (f" · {e(', '.join((u or iu).get('models', [])[:2]))}" if (u or iu) else "") + "</p>"]
312
318
  body += log_block(info) if info else ["<p class=meta>no <code>logs/</code> folder in this agent.</p>"]
313
319
  adesc = next((n.get("description", "") for n in snap["nodes"] if n["type"] == "agent" and n["label"] == name), "")
314
320
  arows.append(f"<details class=row><summary><span class=emo>{emo}</span>"
315
321
  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>"
322
+ f"<span class=sub>{e(words)}</span><span class=when>{e(((u or iu).get('last_active') or '')[:16].replace('T', ' '))}</span>"
317
323
  f"<span class=issue>{e(cost)}</span></summary>{details(body)}</details>")
318
324
  if dormant:
319
325
  arows.append(f"<details class=row><summary><span class=emo>⚫</span><b>{len(dormant)} dormant agents</b>"
@@ -345,7 +351,7 @@ pre{{background:var(--pre);border:1px solid var(--line);border-radius:8px;paddin
345
351
  @media (max-width:760px){{summary{{grid-template-columns:28px 1fr}} .sub,.when,.issue{{grid-column:2}}}}
346
352
  </style>
347
353
  <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>
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>
349
355
  <h1>Did every job and agent run?</h1>
350
356
  <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
357
  <p class=counts>Scheduled jobs: {summary}</p>
@@ -394,8 +400,14 @@ already built: do not touch stats.archify.md or agent-stats.html.
394
400
  python3 -I {scripts}/agent_map.py link <from-id> <to-id> --via "<what flows>" --evidence "<file:line>"
395
401
  Skip anything unclear or coincidental. Then rerun: python3 -I {scripts}/agent_map.py scan --out snapshot.json
396
402
  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.
403
+ The map shows AUTOMATED work only: scheduled jobs, scripts and headless agents, the data they pass
404
+ to each other, and the models each one uses (any model: JEV, Claude, DeepSeek, Grok, Codex, Whisper;
405
+ nodes[].llm_api.models in snapshot.json). People chatting with agents (interactive sessions) are on
406
+ another page: never show their spend; drop an agent that has no automated runs and no data links,
407
+ and keep a consumer agent (one a job feeds) without its interactive cost. Each node's sublabel holds
408
+ its schedule or role, its models and its automated cost when it has one ("cron 04:15 · Grok + Sonnet ·
409
+ $0.40"); spend is usage.agents (automated only). Keep at most 25 nodes on 5 stages x rows 0-4;
410
+ refresh the numbers in the cards (automated spend, models in use, needs attention).
399
411
  3. Descriptions: every node in snapshot.json has a "description" (what it does). For each job and agent
400
412
  whose description is empty or does not say what it does (an instruction to the agent, "You are X"),
401
413
  read its brief or script (first lines only) and write ONE plain sentence of at most 18 words into
@@ -494,6 +506,8 @@ def nightly(scan, days: int, model: str, use_llm: bool) -> int:
494
506
  (STATE / "snapshot.json").write_text(json.dumps(snap, indent=1, default=str))
495
507
  write_stats(snap, folder)
496
508
  write_logs_page(snap, folder)
509
+ import sessions_page
510
+ sessions_page.write_sessions_page(snap, folder)
497
511
  ok, msg = finalize(folder, "explainer", "stats.archify.md", "agent-stats.html")
498
512
  log(folder, f"stats page: {'ok' if ok else 'FAILED ' + msg}")
499
513
 
@@ -549,7 +563,7 @@ def notify(text: str) -> None:
549
563
  def open_latest(model: str) -> int:
550
564
  folder = latest_report()
551
565
  if folder:
552
- for page in ("agent-stats.html", "agent-map.html", "agent-logs.html"):
566
+ for page in ("agent-stats.html", "agent-map.html", "agent-logs.html", "agent-sessions.html"):
553
567
  if (folder / page).is_file():
554
568
  subprocess.run(["open", str(folder / page)], capture_output=True)
555
569
  print(f"opened {folder}")
@@ -0,0 +1,153 @@
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
+ arows.append(
63
+ f"<tr><td><b>{e(a['agent'])}</b></td><td class=num>{pa['n']}</td>"
64
+ 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>"
66
+ f"<td>{e(', '.join(model_name(m) for m in a['models'][:2]))}</td>"
67
+ f"<td class=dim>{e((a.get('last_active') or '')[:16].replace('T', ' '))}</td></tr>")
68
+
69
+ per_day = inter.get("daily_by_agent") or {}
70
+ day_cost = {d: sum(r["cost_usd"] for r in rows) for d, rows in per_day.items()}
71
+ top_day = max(day_cost.values(), default=0.0)
72
+ drows = []
73
+ for d, rows in per_day.items():
74
+ tops = ", ".join(f"{e(r['agent'])} {money(r['cost_usd'])}" for r in rows[:3])
75
+ drows.append(
76
+ f"<tr><td><b>{dt.date.fromisoformat(d):%a %d %b}</b></td>"
77
+ f"<td class=cost>{bar(day_cost[d], top_day)}<span>{money(day_cost[d])}</span></td>"
78
+ f"<td class=num>{mtok(sum(r['tokens'] for r in rows))}</td><td>{tops}</td></tr>")
79
+
80
+ srows = []
81
+ for s in sessions[:20]:
82
+ ctx_warn = " ⚠️" if s["max_context"] > LONG_CONTEXT else ""
83
+ srows.append(
84
+ f"<tr><td class=num><b>{money(s['cost_usd'])}</b></td><td>{e(s['agent'])}</td>"
85
+ f"<td class=dim>{e(s['start'][5:16].replace('T', ' '))} → {e(s['end'][5:16].replace('T', ' '))}"
86
+ f" · {s['hours']}h</td><td class=num>{s['calls']:,}</td>"
87
+ f"<td class=num>{mtok(s['max_context'])}{ctx_warn}</td>"
88
+ f"<td>{e(', '.join(model_name(m) for m in s['models'][:2]))}</td>"
89
+ f"<td class=prompt title=\"{e(s.get('prompt', ''))}\">{e(s.get('prompt', '') or '—')}</td></tr>")
90
+
91
+ tips = []
92
+ if long_n:
93
+ tips.append(f"<li><b>{long_n} sessions grew past {LONG_CONTEXT // 1000}k tokens of context</b> and cost "
94
+ f"{money(long_cost)} ({100 * long_cost / total:.0f}% of the total): every reply re-reads the whole "
95
+ f"session. Start a new session per task (<code>/clear</code>) and <code>/compact</code> a long one.</li>")
96
+ if day_long:
97
+ tips.append(f"<li><b>{day_long} sessions stayed open 12 hours or more.</b> After a pause the cached context "
98
+ "expires and is written again in full, which costs more than reading it.</li>")
99
+ if models and "opus" in models[0][0]:
100
+ tips.append(f"<li><b>{e(model_name(models[0][0]))} is {money(models[0][1]['cost_usd'])}</b> of it: drafting, "
101
+ "reviews and diagrams cost half on Sonnet (<code>/model sonnet</code>).</li>")
102
+ n_total = sessions[0]["count_total"] if sessions else 0
103
+
104
+ page = f"""<!doctype html><html lang=en><meta charset=utf-8>
105
+ <meta name=viewport content="width=device-width,initial-scale=1">
106
+ <title>Interactive sessions · {e(snap.get('generated', '')[:16])}</title>
107
+ <style>
108
+ :root{{--bg:#fff;--fg:#1d2330;--mute:#667085;--line:#e4e7ec;--card:#f8f9fb;--accent:#2f6fec}}
109
+ @media (prefers-color-scheme:dark){{:root{{--bg:#0d1117;--fg:#e6edf3;--mute:#8b949e;--line:#30363d;--card:#161b22;--accent:#79a8ff}}}}
110
+ body{{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}}
111
+ 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)}}
113
+ h1{{font-size:26px;margin:18px 0 4px}} h2{{font-size:19px;margin:34px 0 10px}}
114
+ .lead{{color:var(--mute);margin:0 0 14px}}
115
+ .kpis{{display:flex;gap:12px;flex-wrap:wrap;margin:14px 0}}
116
+ .kpi{{border:1px solid var(--line);background:var(--card);border-radius:10px;padding:10px 16px;min-width:150px}}
117
+ .kpi b{{display:block;font-size:22px}} .kpi span{{color:var(--mute);font-size:13px}}
118
+ table{{width:100%;border-collapse:collapse;font-size:14px}}
119
+ th{{text-align:left;color:var(--mute);font-weight:600;font-size:12.5px;border-bottom:1px solid var(--line);padding:6px 8px}}
120
+ td{{border-bottom:1px solid var(--line);padding:7px 8px;vertical-align:middle}}
121
+ .num{{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}} .dim{{color:var(--mute);font-size:13px;white-space:nowrap}}
122
+ .cost{{display:flex;align-items:center;gap:8px;min-width:200px}} .cost span{{font-variant-numeric:tabular-nums}}
123
+ .bar{{flex:1;height:8px;border-radius:4px;background:color-mix(in srgb,var(--line) 70%,transparent);overflow:hidden;max-width:160px}}
124
+ .bar i{{display:block;height:100%;background:linear-gradient(90deg,hsl(40,85%,52%),hsl(0,72%,52%))}}
125
+ .prompt{{max-width:330px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--mute);font-size:13px}}
126
+ .tips{{border:1px solid var(--line);background:var(--card);border-radius:10px;padding:6px 18px}}
127
+ .tips li{{margin:8px 0}} code{{font:12.5px ui-monospace,Menlo,monospace}}
128
+ .note{{color:var(--mute);font-size:13px;margin-top:30px}}
129
+ </style>
130
+ <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>
132
+ <h1>Your interactive sessions, last {days} days</h1>
133
+ <p class=lead>Chats with agents in a terminal (Claude Code, Codex, Grok), kept apart from the automated jobs on the map.
134
+ Costs are API-equivalent: a Max plan is not billed per token, but these use up its limits.</p>
135
+ <div class=kpis>
136
+ <div class=kpi><b>{money(total)}</b><span>API-equivalent cost</span></div>
137
+ <div class=kpi><b>{n_total}</b><span>sessions</span></div>
138
+ <div class=kpi><b>{mtok(inter.get('total_tokens', 0))}</b><span>tokens (mostly re-read context)</span></div>
139
+ <div class=kpi><b>{e(', '.join(model_name(m) for m, _ in models[:2]) or '—')}</b><span>main models</span></div>
140
+ </div>
141
+ {f'<h2>How to spend less</h2><ul class=tips>{"".join(tips)}</ul>' if tips else ''}
142
+ <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>
145
+ <h2>By day</h2>
146
+ <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
+ <h2>Costliest sessions</h2>
148
+ <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
+ {''.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
151
+ Mac; Claude Code keeps 15 days of them. Scan {e(snap.get('generated', '')[:16].replace('T', ' '))}.</p>
152
+ </main></html>"""
153
+ (folder / "agent-sessions.html").write_text(page)