@hivey/cli 0.9.57 → 0.9.59

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.57",
3
+ "version": "0.9.59",
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",
@@ -139,6 +139,11 @@ hivey agent-map schedule install [--at 06:30] [--model haiku] # | remove | sta
139
139
  button works: it runs `agent_map.py refresh` (new scan into the latest report's pages, no model, a few
140
140
  seconds; the map keeps the night's boxes) and reloads. Only the served pages can trigger it (Origin
141
141
  check). Opened as plain files, the button says to open them from the hivey menu.
142
+ - **24 hours / 7 days:** every report (nightly and Refresh) also holds the same four pages for the last
143
+ 24 hours in `<report>/1d/` (`report.write_day_view`, a second scan with `days=1`); the navbar's
144
+ "24 h | 7 days" toggle opens the same page in the other window. The 24-hour map reuses the night's
145
+ boxes and flows (`day_spec` drops the 7-day dollar amounts and spend card the model wrote) and is
146
+ redrawn with archify; its colours, info cards and legend use the 24-hour numbers.
142
147
  - **Context window per agent** (`context_window.py`): the Sessions page shows each agent's window for its
143
148
  next session, 1M or the standard 200k (Claude Code compacts the session before it grows).
144
149
  `hivey agent-map context` lists every agent's window and peak; `hivey agent-map context <agent…> --set
@@ -102,6 +102,11 @@ def log_path(command: str) -> str | None:
102
102
  return os.path.expanduser(m.group(1)) if m else None
103
103
 
104
104
 
105
+ def _is_err(line: str) -> bool:
106
+ return bool(re.search(r"error|traceback|exception|failed|fatal", line, re.I)
107
+ and not re.search(r"\b0 failed|failed:? 0\b|0 errors?\b|errors?:? 0\b|rerun picks", line, re.I))
108
+
109
+
105
110
  def log_info(path: str | None) -> dict:
106
111
  if not path or not os.path.isfile(path):
107
112
  return {}
@@ -112,9 +117,11 @@ def log_info(path: str | None) -> dict:
112
117
  f.seek(max(0, st.st_size - 6000))
113
118
  tail = f.read().decode("utf-8", "replace").splitlines()[-40:]
114
119
  tail = [re.sub(r"\x1b\[[0-9;]*[A-Za-z]|\r", "", l)[:300] for l in tail]
115
- errs = [l.strip() for l in tail
116
- if re.search(r"error|traceback|exception|failed|fatal", l, re.I)
117
- and not re.search(r"\b0 failed|failed:? 0\b|0 errors?\b|errors?:? 0\b|rerun picks", l, re.I)]
120
+ # logs are appended run after run: an error from an earlier run that a later run's success line
121
+ # follows is history, not a current problem (a Baserow timeout stayed flagged after good runs)
122
+ ok = re.compile(r"\b(success(ful(ly)?)?|succeeded|finished|completed?|done|wrote|all ok)\b", re.I)
123
+ last_ok = max((i for i, l in enumerate(tail) if ok.search(l) and not _is_err(l)), default=-1)
124
+ errs = [l.strip() for l in tail[last_ok + 1:] if _is_err(l)]
118
125
  if errs:
119
126
  info["last_error"] = errs[-1][:200]
120
127
  info["errors"] = list(dict.fromkeys(e[:200] for e in errs))[-5:]
@@ -40,6 +40,8 @@ NAV_CSS = """
40
40
  .hv-nav a{color:inherit;opacity:.65;text-decoration:none;padding:4px 12px;border-radius:999px}
41
41
  .hv-nav a:hover{opacity:1;background:rgba(127,127,127,.14)}
42
42
  .hv-nav a.on{opacity:1;background:rgba(47,111,236,.16);color:#2f6fec}
43
+ .hv-nav .hv-span{display:inline-flex;margin-left:12px;border:1px solid rgba(127,127,127,.3);border-radius:999px;padding:2px}
44
+ .hv-nav .hv-span a{padding:2px 10px;font-weight:600;font-size:12px}
43
45
  .hv-nav .hv-when{margin-left:12px;opacity:.55;font-weight:400;font-size:12px;white-space:nowrap}
44
46
  .hv-nav .hv-refresh{margin-left:8px;font:600 12px/1.2 inherit;font-family:inherit;color:#2f6fec;cursor:pointer;
45
47
  background:rgba(47,111,236,.10);border:1px solid rgba(47,111,236,.35);border-radius:999px;padding:4px 11px}
@@ -67,12 +69,23 @@ svg text.hv-stage{cursor:help;text-decoration:underline dotted;text-underline-of
67
69
  """
68
70
 
69
71
 
70
- def nav(active: str, generated: str) -> str:
72
+ def span(days: int) -> str:
73
+ """The window in words: "24 hours" or "7 days"."""
74
+ return "24 hours" if days == 1 else f"{days} days"
75
+
76
+
77
+ DAY_DIR = "1d" # each report's 24-hour pages live in <report>/1d/, the 7-day ones in <report>/
78
+
79
+
80
+ def nav(active: str, generated: str, days: int = 7) -> str:
71
81
  links = [("agent-stats.html", "Stats"), ("agent-map.html", "Map"), ("agent-logs.html", "Logs"),
72
82
  ("agent-sessions.html", "Sessions")]
73
83
  items = "".join(f'<a href="{href}"{" class=on" if href == active else ""}>{label}</a>' for href, label in links)
74
84
  when = html.escape(generated[:16].replace("T", " "))
75
- return (f'<nav class="hv-nav">{items}<span class="hv-when">scan {when}</span>'
85
+ day = days == 1 # the toggle opens the same page in the other window
86
+ toggle = (f'<span class="hv-span"><a href="{active if day else DAY_DIR + "/" + active}"{" class=on" if day else ""}>24 h</a>'
87
+ f'<a href="{"../" + active if day else active}"{"" if day else " class=on"}>7 days</a></span>')
88
+ return (f'<nav class="hv-nav">{items}{toggle}<span class="hv-when">scan {when}</span>'
76
89
  '<button class="hv-refresh" type="button" title="Scan again now and reload (free: no model run)" '
77
90
  'onclick="hvRefresh(this)">↻ Refresh</button></nav>' + REFRESH_JS)
78
91
 
@@ -196,7 +209,7 @@ def node_data(snap: dict, spec: dict, meta: dict, job_state) -> dict:
196
209
 
197
210
  MAP_JS = r"""
198
211
  (function(){
199
- const D=__DATA__, STAGES=__STAGES__, DAYS=__DAYS__;
212
+ const D=__DATA__, STAGES=__STAGES__, SPAN=__SPAN__;
200
213
  const fmt=v=>'$'+v.toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2});
201
214
  const tok=n=>n>=1e6?(n/1e6).toFixed(1)+'M':n>=1e3?Math.round(n/1e3)+'k':String(n);
202
215
  const esc=s=>String(s).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
@@ -211,7 +224,7 @@ document.querySelectorAll('g[data-node-id]').forEach(g=>{
211
224
  g.classList.add('hv-alert');
212
225
  }
213
226
  const t=g.querySelector(':scope > title');
214
- 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');}
227
+ if(t){t.textContent=[g.dataset.nodeLabel, d.desc, d.subject?(fmt(d.cost)+' in '+SPAN+' · '+tok(d.tokens)+' tokens'+(d.models.length?' · '+d.models.join(', '):'')):''].filter(Boolean).concat((d.alerts||[]).map(a=>'⚠️ '+a.name+': '+a.words)).join('\n');}
215
228
  });
216
229
  document.querySelectorAll('svg text').forEach(t=>{
217
230
  const m=/^\s*\d+\s*\/\s*(.+?)\s*$/.exec(t.textContent||''); if(!m) return;
@@ -233,7 +246,7 @@ function fill(meta){
233
246
  const rows=[];
234
247
  (d.alerts||[]).forEach(a=>rows.push(['⚠️ Problem', esc(a.name)+': '+esc(a.words)+' · <a href="agent-logs.html#'+a.anchor+'">open its log</a>']));
235
248
  if(d.subject){
236
- rows.push(['Spend', fmt(d.cost)+' in '+DAYS+' days, automated runs only (API-equivalent)']);
249
+ rows.push(['Spend', fmt(d.cost)+' in '+SPAN+', automated runs only (API-equivalent)']);
237
250
  rows.push(['Tokens', tok(d.tokens)+' ('+tok(d.out)+' output) · '+d.calls.toLocaleString()+' calls']);
238
251
  }
239
252
  rows.push(['Models', d.models.length?'<span class="hv-models">'+d.models.map(m=>'<span>'+esc(m)+'</span>').join('')+'</span>':'none found']);
@@ -248,10 +261,10 @@ new MutationObserver(refill).observe(document.body,{childList:true,subtree:true,
248
261
 
249
262
 
250
263
  def enhance_folder(folder: Path, snap: dict, job_state) -> None:
251
- generated = snap.get("generated", "")
264
+ generated, days = snap.get("generated", ""), snap.get("window_days", 7)
252
265
  stats = folder / "agent-stats.html"
253
266
  if stats.is_file():
254
- stats.write_text(inject(stats.read_text(), NAV_CSS, nav("agent-stats.html", generated)))
267
+ stats.write_text(inject(stats.read_text(), NAV_CSS, nav("agent-stats.html", generated, days)))
255
268
  page, spec_path = folder / "agent-map.html", folder / "map.json"
256
269
  if page.is_file() and spec_path.is_file():
257
270
  spec = json.loads(spec_path.read_text())
@@ -263,9 +276,9 @@ def enhance_folder(folder: Path, snap: dict, job_state) -> None:
263
276
  stages = dict(STAGE_HELP)
264
277
  stages.update({k.lower(): v for k, v in (meta.get("stages") or {}).items()})
265
278
  script = (MAP_JS.replace("__DATA__", json.dumps(data)).replace("__STAGES__", json.dumps(stages))
266
- .replace("__DAYS__", json.dumps(snap.get("window_days", 7))))
267
- legend = (f'<div class="hv-legend"><b>Spend, last {snap.get("window_days", 7)} days</b><div class="bar"></div>'
279
+ .replace("__SPAN__", json.dumps(span(days))))
280
+ legend = (f'<div class="hv-legend"><b>Spend, last {span(days)}</b><div class="bar"></div>'
268
281
  f'<div class="ends"><span>$0</span><span>{money(top)}</span></div>'
269
282
  f'<div style="opacity:.65;margin-top:3px">click a box for what it does, tokens and models</div>'
270
283
  f'<div style="opacity:.65">⚠️ its last run failed, was missed or logged errors</div></div>')
271
- page.write_text(inject(page.read_text(), NAV_CSS + MAP_CSS, nav("agent-map.html", generated) + legend, script))
284
+ page.write_text(inject(page.read_text(), NAV_CSS + MAP_CSS, nav("agent-map.html", generated, days) + legend, script))
@@ -82,6 +82,7 @@ def write_stats(snap: dict, folder: Path) -> None:
82
82
 
83
83
  u = snap["usage"]
84
84
  days = snap["window_days"]
85
+ span = span_of(snap)
85
86
  total = u["total_cost_usd"] or 0.0
86
87
  agents = u["agents"]
87
88
  (folder / "snapshot.json").write_text(json.dumps(snap, indent=1, default=str))
@@ -109,12 +110,12 @@ def write_stats(snap: dict, folder: Path) -> None:
109
110
 
110
111
  L = []
111
112
  inter = snap.get("interactive", {})
112
- L.append(f"# What ran on its own on this Mac in the last {days} days, and what did it cost? {{#agent-stats}}\n")
113
+ L.append(f"# What ran on its own on this Mac in the last {span}, and what did it cost? {{#agent-stats}}\n")
113
114
  if top:
114
115
  L.append(f"Your scheduled jobs, scripts and headless agents used about **{money(total)} of tokens** in "
115
- f"{days} days; **{cell(top['agent'])} used {money(top['cost_usd'])}** of it ({pct(top['cost_usd'])}).\n")
116
+ f"{span}; **{cell(top['agent'])} used {money(top['cost_usd'])}** of it ({pct(top['cost_usd'])}).\n")
116
117
  else:
117
- L.append(f"No automated token use was recorded in the last {days} days.\n")
118
+ L.append(f"No automated token use was recorded in the last {span}.\n")
118
119
  L.append(f"- Headless agent runs cost {money(headless)} and scripts' direct API calls {money(api)}; local "
119
120
  f"models (JEV, Whisper) cost nothing.")
120
121
  if inter.get("total_cost_usd"):
@@ -126,7 +127,7 @@ def write_stats(snap: dict, folder: Path) -> None:
126
127
  tally = ", ".join(f"{emo} {states.count(emo)}" for emo in ("✅", "⚠️", "❌", "⏳", "❔") if states.count(emo))
127
128
  L.append(f"- {len(jobs)} scheduled jobs ({n_cron} cron, {len(jobs) - n_cron} launchd): {tally}; "
128
129
  f"{len(snap['links_confirmed'])} links between them; {len(gaps)} with LLM calls not logged yet.\n")
129
- L.append(f'@answer scope="last {days} days to {snap["generated"][:10]} · costs are list-price estimates · '
130
+ L.append(f'@answer scope="last {span} to {snap["generated"][:10]} · costs are list-price estimates · '
130
131
  f'Claude Code (Max) and Codex (Plus) are not billed per token"')
131
132
  L.append("@meta locale=en")
132
133
  L.append('@source scan title="hivey agent map snapshot (agent_map.py scan)" path=snapshot.json\n')
@@ -134,7 +135,7 @@ def write_stats(snap: dict, folder: Path) -> None:
134
135
  if agents:
135
136
  L.append("## Which agents spend the most? {#by-agent}\n")
136
137
  L.append(f'@chart type=bar data=agents.csv x=agent y=cost_usd unit=USD title="Cost by agent, '
137
- f'last {days} days (API-equivalent USD, estimated)"\n')
138
+ f'last {span} (API-equivalent USD, estimated)"\n')
138
139
  L.append("| Agent | Cost | Calls | Tokens | Main model |")
139
140
  L.append("| --- | --- | --- | --- | --- |")
140
141
  for a in agents[:8]:
@@ -317,7 +318,7 @@ def write_logs_page(snap: dict, folder: Path) -> None:
317
318
  u = usage.get(name, {})
318
319
  iu = inter_usage.get(name, {})
319
320
  parts = ([f"automated ${u['cost_usd']:,.2f}"] if u else []) + ([f"chats ${iu['cost_usd']:,.2f}"] if iu else [])
320
- cost = (" · ".join(parts) + f" in {snap['window_days']} days") if parts else "no token use"
321
+ cost = (" · ".join(parts) + f" in {span_of(snap)}") if parts else "no token use"
321
322
  body = [f"<p class=meta>{e(a['where'] if a else 'not open in hivey')} · {e(a.get('cwd', '') if a else '')}"
322
323
  f" · last active {e((u or iu).get('last_active') or '?')} · {e(cost)}"
323
324
  + (f" · {e(', '.join((u or iu).get('models', [])[:2]))}" if (u or iu) else "") + "</p>"]
@@ -334,7 +335,7 @@ def write_logs_page(snap: dict, folder: Path) -> None:
334
335
  f"<p class=meta>{e(', '.join(dormant))}</p></details>")
335
336
  summary = " · ".join(f"{k} {v}" for k, v in sorted(counts.items(), key=lambda kv: ORDER.get(kv[0], 9)))
336
337
  import enhance
337
- NAV, NAV_CSS = enhance.nav("agent-logs.html", snap['generated']), enhance.NAV_CSS
338
+ NAV, NAV_CSS = enhance.nav("agent-logs.html", snap['generated'], snap['window_days']), enhance.NAV_CSS
338
339
  page = f"""<!doctype html><html lang=en><meta charset=utf-8>
339
340
  <meta name=viewport content="width=device-width,initial-scale=1">
340
341
  {enhance.FAVICON}
@@ -510,6 +511,68 @@ def html_current(folder: Path, html: str, src: str) -> bool:
510
511
  return h.is_file() and s.is_file() and h.stat().st_mtime >= s.stat().st_mtime
511
512
 
512
513
 
514
+ def span_of(snap: dict) -> str:
515
+ import enhance
516
+ return enhance.span(snap.get("window_days", 7))
517
+
518
+
519
+ def write_day_view(scan, folder: Path) -> tuple[bool, str]:
520
+ """The same pages for the last 24 hours, in <folder>/1d/ (the navbar's "24 h" toggle). The map
521
+ keeps the boxes the night drew; its colours, info cards and legend use the 24-hour numbers."""
522
+ import enhance
523
+ import sessions_page
524
+ sub = folder / enhance.DAY_DIR
525
+ sub.mkdir(exist_ok=True)
526
+ snap = scan(1)
527
+ write_stats(snap, sub)
528
+ write_logs_page(snap, sub)
529
+ sessions_page.write_sessions_page(snap, sub)
530
+ ok, msg = finalize(sub, "explainer", "stats.archify.md", "agent-stats.html")
531
+ for name in ("map.json", "map-meta.json", "agent-map.html"):
532
+ if (sub / name).exists():
533
+ (sub / name).unlink()
534
+ if (folder / "map-meta.json").is_file():
535
+ shutil.copy2(folder / "map-meta.json", sub / "map-meta.json")
536
+ if (folder / "map.json").is_file():
537
+ (sub / "map.json").write_text(json.dumps(day_spec(json.loads((folder / "map.json").read_text())), indent=1))
538
+ good, why = finalize(sub, "dataflow", "map.json", "agent-map.html")
539
+ if not good and (folder / "agent-map.html").is_file(): # the 7-day drawing still beats no map
540
+ log(folder, f"24-hour map failed ({why}); using the 7-day drawing")
541
+ shutil.copy2(folder / "agent-map.html", sub / "agent-map.html")
542
+ enhance.enhance_folder(sub, snap, job_state)
543
+ return ok, msg
544
+
545
+
546
+ MONEY = r"\$[\d,.]+k?"
547
+
548
+
549
+ def day_spec(spec: dict) -> dict:
550
+ """The night's map for the 24-hour pages: same boxes and flows, without the 7-day dollar amounts
551
+ the model wrote into them (the colours and info cards carry the 24-hour numbers)."""
552
+ meta = dict(spec.get("meta") or {})
553
+ title = meta.get("title", "")
554
+ meta["title"] = re.sub(r"\(last \d+ days\)", "(last 24 hours)", title) if re.search(r"\(last \d+ days\)", title) \
555
+ else (title + " (last 24 hours)").strip()
556
+ nodes = []
557
+ for n in spec.get("nodes") or []:
558
+ n = dict(n)
559
+ if "sublabel" in n:
560
+ n["sublabel"] = re.sub(r"\s*·\s*" + MONEY + r"(?=\s*(·|$))", "", n["sublabel"]).strip(" ·")
561
+ if re.fullmatch(r"\s*" + MONEY + r"\s*", str(n.get("tag", ""))):
562
+ n.pop("tag")
563
+ nodes.append(n)
564
+ cards = [c for c in spec.get("cards") or [] if not re.search(r"last \d+ days|spend", str(c.get("title", "")), re.I)]
565
+ return {**spec, "meta": meta, "nodes": nodes, "cards": cards}
566
+
567
+
568
+ def day_view(scan, folder: Path) -> None:
569
+ try:
570
+ ok, msg = write_day_view(scan, folder)
571
+ log(folder, f"24-hour pages: {'ok' if ok else 'stats page FAILED ' + msg}")
572
+ except Exception as e: # the 7-day pages stand on their own
573
+ log(folder, f"24-hour pages failed: {e}")
574
+
575
+
513
576
  def nightly(scan, days: int, model: str, use_llm: bool) -> int:
514
577
  REPORTS.mkdir(parents=True, exist_ok=True)
515
578
  now = dt.datetime.now()
@@ -548,6 +611,7 @@ def nightly(scan, days: int, model: str, use_llm: bool) -> int:
548
611
  enhance.enhance_folder(folder, json.loads((folder / "snapshot.json").read_text()), job_state)
549
612
  except Exception as e: # the pages still work without hivey's layer
550
613
  log(folder, f"enhance failed: {e}")
614
+ day_view(scan, folder)
551
615
  if ok or (folder / "agent-logs.html").is_file(): # a failed stats page still publishes logs and sessions
552
616
  tmp = REPORTS / ".latest-new"
553
617
  if tmp.is_symlink() or tmp.exists():
@@ -581,6 +645,7 @@ def refresh(scan, days: int, model: str) -> int:
581
645
  enhance.enhance_folder(folder, json.loads((folder / "snapshot.json").read_text()), job_state)
582
646
  except Exception as e:
583
647
  log(folder, f"enhance failed: {e}")
648
+ day_view(scan, folder)
584
649
  log(folder, f"refresh: {'ok' if ok else 'stats page FAILED ' + msg}")
585
650
  return 0 if ok else 1
586
651
 
@@ -113,7 +113,7 @@ def write_sessions_page(snap: dict, folder: Path) -> None:
113
113
  n_total = sessions[0]["count_total"] if sessions else 0
114
114
 
115
115
  import enhance
116
- NAV, NAV_CSS = enhance.nav("agent-sessions.html", snap.get('generated', '')), enhance.NAV_CSS
116
+ NAV, NAV_CSS = enhance.nav("agent-sessions.html", snap.get('generated', ''), days), enhance.NAV_CSS
117
117
  page = f"""<!doctype html><html lang=en><meta charset=utf-8>
118
118
  <meta name=viewport content="width=device-width,initial-scale=1">
119
119
  {enhance.FAVICON}
@@ -145,7 +145,7 @@ td{{border-bottom:1px solid var(--line);padding:7px 8px;vertical-align:middle}}
145
145
  </style>
146
146
  <main>
147
147
  {NAV}
148
- <h1>Your interactive sessions, last {days} days</h1>
148
+ <h1>Your interactive sessions, last {enhance.span(days)}</h1>
149
149
  <p class=lead>Chats with agents in a terminal (Claude Code, Codex, Grok), kept apart from the automated jobs on the map.
150
150
  Costs are API-equivalent: a Max plan is not billed per token, but these use up its limits.</p>
151
151
  <div class=kpis>