@hivey/cli 0.9.54 → 0.9.58

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.54",
3
+ "version": "0.9.58",
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",
@@ -130,15 +130,20 @@ hivey agent-map schedule install [--at 06:30] [--model haiku] # | remove | sta
130
130
  People chatting with agents (Claude Code, Codex, Grok in a terminal; snapshot `interactive`, with one
131
131
  entry per session) go to **`agent-sessions.html`**: cost by agent and by day, the costliest sessions with
132
132
  their peak context (⚠️ over 300k tokens), length and first message, and tips to spend less.
133
- - **Open:** `hivey agent-map open` (hivey menu → agent map) opens `http://127.0.0.1:8754/latest/agent-map.html`
133
+ - **Open:** `hivey agent-map open` (hivey menu → agent map) opens `http://127.0.0.1:42817/latest/agent-map.html`
134
134
  (the map first; the stats page when there is no map yet). With no report yet it builds the pages without
135
135
  a model in seconds, opens them, then draws the map in the background (`first-run.json` stops a second
136
136
  click from starting another build). If a stats page fails, the logs and sessions pages still publish.
137
- - **Refresh:** `hivey agent-map open` serves the pages from 127.0.0.1 (`serve.py`, port 8754 or any
137
+ - **Refresh:** `hivey agent-map open` serves the pages from 127.0.0.1 (`serve.py`, port 42817 (unregistered, below macOS's temporary ports) or any
138
138
  free one, in `~/.hivey/agent-map/server.json`; stops after 2 h unused) so the navbar's ↻ Refresh
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
@@ -563,6 +563,9 @@ def describe_markdown(path: Path) -> str:
563
563
  return ""
564
564
  fm = re.match(r"---\n(.*?)\n---", text, re.S)
565
565
  if fm:
566
+ m = re.search(r"^description:[ \t]*[>|]-?[ \t]*\n((?:[ \t]+.*\n?)+)", fm.group(1) + "\n", re.M)
567
+ if m: # folded or literal block: the indented lines
568
+ return first_sentence(" ".join(l.strip() for l in m.group(1).splitlines()))
566
569
  m = re.search(r"^description:\s*\"?(.+?)\"?\s*$", fm.group(1), re.M)
567
570
  if m:
568
571
  return first_sentence(m.group(1))
@@ -28,6 +28,11 @@ STAGE_HELP = {
28
28
  "outputs": "What leaves the system: posts, messages, published files.",
29
29
  }
30
30
 
31
+ # The tab icon: hivey's logo (assets/logo.svg), embedded so the pages need no other file.
32
+ FAVICON = ('<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,'
33
+ "%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' rx='9' "
34
+ "fill='%239befc8'/%3E%3Cpath d='M10 9h7v9h6V9h7v23h-7V22h-6v10h-7z' fill='%23122319'/%3E%3C/svg%3E\">")
35
+
31
36
  NAV_CSS = """
32
37
  .hv-nav{position:relative;z-index:50;display:flex;flex-wrap:wrap;gap:4px;align-items:center;justify-content:flex-start;
33
38
  padding:6px 16px;font:600 13px/1.2 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;
@@ -35,6 +40,8 @@ NAV_CSS = """
35
40
  .hv-nav a{color:inherit;opacity:.65;text-decoration:none;padding:4px 12px;border-radius:999px}
36
41
  .hv-nav a:hover{opacity:1;background:rgba(127,127,127,.14)}
37
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}
38
45
  .hv-nav .hv-when{margin-left:12px;opacity:.55;font-weight:400;font-size:12px;white-space:nowrap}
39
46
  .hv-nav .hv-refresh{margin-left:8px;font:600 12px/1.2 inherit;font-family:inherit;color:#2f6fec;cursor:pointer;
40
47
  background:rgba(47,111,236,.10);border:1px solid rgba(47,111,236,.35);border-radius:999px;padding:4px 11px}
@@ -62,12 +69,23 @@ svg text.hv-stage{cursor:help;text-decoration:underline dotted;text-underline-of
62
69
  """
63
70
 
64
71
 
65
- 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:
66
81
  links = [("agent-stats.html", "Stats"), ("agent-map.html", "Map"), ("agent-logs.html", "Logs"),
67
82
  ("agent-sessions.html", "Sessions")]
68
83
  items = "".join(f'<a href="{href}"{" class=on" if href == active else ""}>{label}</a>' for href, label in links)
69
84
  when = html.escape(generated[:16].replace("T", " "))
70
- 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>'
71
89
  '<button class="hv-refresh" type="button" title="Scan again now and reload (free: no model run)" '
72
90
  'onclick="hvRefresh(this)">↻ Refresh</button></nav>' + REFRESH_JS)
73
91
 
@@ -85,7 +103,8 @@ catch(e){clearInterval(tick);b.disabled=false;b.textContent='refresh failed: ser
85
103
  def inject(page: str, css: str, top: str, script: str = "") -> str:
86
104
  """Adds hivey's pieces, each wrapped in <!--hv--> markers so a rerun replaces them."""
87
105
  page = re.sub(r"<!--hv-->.*?<!--/hv-->", "", page, flags=re.S)
88
- page = page.replace("</head>", f"<!--hv--><style>{css}</style><!--/hv--></head>", 1)
106
+ page = re.sub(r"<link\b[^>]*\brel=[\"']?(?:shortcut )?icon\b[^>]*>", "", page, flags=re.I) # hivey's icon only
107
+ page = page.replace("</head>", f"<!--hv-->{FAVICON}<style>{css}</style><!--/hv--></head>", 1)
89
108
  m = re.search(r"<body[^>]*>", page)
90
109
  if m:
91
110
  page = page[: m.end()] + f"<!--hv-->{top}<!--/hv-->" + page[m.end():]
@@ -190,7 +209,7 @@ def node_data(snap: dict, spec: dict, meta: dict, job_state) -> dict:
190
209
 
191
210
  MAP_JS = r"""
192
211
  (function(){
193
- const D=__DATA__, STAGES=__STAGES__, DAYS=__DAYS__;
212
+ const D=__DATA__, STAGES=__STAGES__, SPAN=__SPAN__;
194
213
  const fmt=v=>'$'+v.toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2});
195
214
  const tok=n=>n>=1e6?(n/1e6).toFixed(1)+'M':n>=1e3?Math.round(n/1e3)+'k':String(n);
196
215
  const esc=s=>String(s).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
@@ -205,7 +224,7 @@ document.querySelectorAll('g[data-node-id]').forEach(g=>{
205
224
  g.classList.add('hv-alert');
206
225
  }
207
226
  const t=g.querySelector(':scope > title');
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');}
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');}
209
228
  });
210
229
  document.querySelectorAll('svg text').forEach(t=>{
211
230
  const m=/^\s*\d+\s*\/\s*(.+?)\s*$/.exec(t.textContent||''); if(!m) return;
@@ -227,7 +246,7 @@ function fill(meta){
227
246
  const rows=[];
228
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>']));
229
248
  if(d.subject){
230
- 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)']);
231
250
  rows.push(['Tokens', tok(d.tokens)+' ('+tok(d.out)+' output) · '+d.calls.toLocaleString()+' calls']);
232
251
  }
233
252
  rows.push(['Models', d.models.length?'<span class="hv-models">'+d.models.map(m=>'<span>'+esc(m)+'</span>').join('')+'</span>':'none found']);
@@ -242,10 +261,10 @@ new MutationObserver(refill).observe(document.body,{childList:true,subtree:true,
242
261
 
243
262
 
244
263
  def enhance_folder(folder: Path, snap: dict, job_state) -> None:
245
- generated = snap.get("generated", "")
264
+ generated, days = snap.get("generated", ""), snap.get("window_days", 7)
246
265
  stats = folder / "agent-stats.html"
247
266
  if stats.is_file():
248
- 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)))
249
268
  page, spec_path = folder / "agent-map.html", folder / "map.json"
250
269
  if page.is_file() and spec_path.is_file():
251
270
  spec = json.loads(spec_path.read_text())
@@ -257,9 +276,9 @@ def enhance_folder(folder: Path, snap: dict, job_state) -> None:
257
276
  stages = dict(STAGE_HELP)
258
277
  stages.update({k.lower(): v for k, v in (meta.get("stages") or {}).items()})
259
278
  script = (MAP_JS.replace("__DATA__", json.dumps(data)).replace("__STAGES__", json.dumps(stages))
260
- .replace("__DAYS__", json.dumps(snap.get("window_days", 7))))
261
- 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>'
262
281
  f'<div class="ends"><span>$0</span><span>{money(top)}</span></div>'
263
282
  f'<div style="opacity:.65;margin-top:3px">click a box for what it does, tokens and models</div>'
264
283
  f'<div style="opacity:.65">⚠️ its last run failed, was missed or logged errors</div></div>')
265
- 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,9 +335,10 @@ 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">
341
+ {enhance.FAVICON}
340
342
  <title>Agent logs · {e(snap['generated'][:16])}</title>
341
343
  <style>
342
344
  :root{{--bg:#fff;--fg:#1d2330;--mute:#667085;--line:#e4e7ec;--card:#f8f9fb;--accent:#2f6fec;--pre:#f2f4f7}}
@@ -509,6 +511,68 @@ def html_current(folder: Path, html: str, src: str) -> bool:
509
511
  return h.is_file() and s.is_file() and h.stat().st_mtime >= s.stat().st_mtime
510
512
 
511
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
+
512
576
  def nightly(scan, days: int, model: str, use_llm: bool) -> int:
513
577
  REPORTS.mkdir(parents=True, exist_ok=True)
514
578
  now = dt.datetime.now()
@@ -547,6 +611,7 @@ def nightly(scan, days: int, model: str, use_llm: bool) -> int:
547
611
  enhance.enhance_folder(folder, json.loads((folder / "snapshot.json").read_text()), job_state)
548
612
  except Exception as e: # the pages still work without hivey's layer
549
613
  log(folder, f"enhance failed: {e}")
614
+ day_view(scan, folder)
550
615
  if ok or (folder / "agent-logs.html").is_file(): # a failed stats page still publishes logs and sessions
551
616
  tmp = REPORTS / ".latest-new"
552
617
  if tmp.is_symlink() or tmp.exists():
@@ -580,6 +645,7 @@ def refresh(scan, days: int, model: str) -> int:
580
645
  enhance.enhance_folder(folder, json.loads((folder / "snapshot.json").read_text()), job_state)
581
646
  except Exception as e:
582
647
  log(folder, f"enhance failed: {e}")
648
+ day_view(scan, folder)
583
649
  log(folder, f"refresh: {'ok' if ok else 'stats page FAILED ' + msg}")
584
650
  return 0 if ok else 1
585
651
 
@@ -22,7 +22,7 @@ STATE = Path.home() / ".hivey" / "agent-map"
22
22
  REPORTS = STATE / "reports"
23
23
  INFO = STATE / "server.json"
24
24
  SCRIPTS = Path(__file__).resolve().parent
25
- PREFERRED_PORT = 8754
25
+ PREFERRED_PORT = 42817 # unregistered and below macOS's temporary-port range, so no other app picks it
26
26
  IDLE_SECONDS = 2 * 3600
27
27
  PING = "/hv-ping"
28
28
  MARK = b"hivey-agent-map"
@@ -40,11 +40,27 @@ def running() -> int | None:
40
40
  return None
41
41
 
42
42
 
43
+ def port_free(port: int) -> bool:
44
+ import socket
45
+ with socket.socket() as sock:
46
+ try:
47
+ sock.bind(("127.0.0.1", port))
48
+ return True
49
+ except OSError:
50
+ return False
51
+
52
+
43
53
  def ensure() -> int | None:
44
54
  """The running server's port, starting one in the background when there is none."""
45
55
  port = running()
46
- if port:
56
+ if port and (port == PREFERRED_PORT or not port_free(PREFERRED_PORT)):
47
57
  return port
58
+ if port: # an older server on another port while ours is free: replace it
59
+ try:
60
+ os.kill(int(json.loads(INFO.read_text())["pid"]), 15)
61
+ time.sleep(0.3)
62
+ except (OSError, ValueError, KeyError, TypeError):
63
+ pass
48
64
  STATE.mkdir(parents=True, exist_ok=True)
49
65
  with open(STATE / "server.log", "a") as fh:
50
66
  subprocess.Popen([sys.executable, "-I", str(SCRIPTS / "agent_map.py"), "serve"], stdin=subprocess.DEVNULL,
@@ -113,9 +113,10 @@ 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
+ {enhance.FAVICON}
119
120
  <title>Interactive sessions · {e(snap.get('generated', '')[:16])}</title>
120
121
  <style>
121
122
  :root{{--bg:#fff;--fg:#1d2330;--mute:#667085;--line:#e4e7ec;--card:#f8f9fb;--accent:#2f6fec}}
@@ -144,7 +145,7 @@ td{{border-bottom:1px solid var(--line);padding:7px 8px;vertical-align:middle}}
144
145
  </style>
145
146
  <main>
146
147
  {NAV}
147
- <h1>Your interactive sessions, last {days} days</h1>
148
+ <h1>Your interactive sessions, last {enhance.span(days)}</h1>
148
149
  <p class=lead>Chats with agents in a terminal (Claude Code, Codex, Grok), kept apart from the automated jobs on the map.
149
150
  Costs are API-equivalent: a Max plan is not billed per token, but these use up its limits.</p>
150
151
  <div class=kpis>
@@ -1,6 +1,14 @@
1
1
  ---
2
2
  name: hivey-grok
3
- description: Run tasks with xAI's Grok Build CLI (`grok`, installed at ~/.grok/bin/grok) headless through a bundled uv Python runner — research questions (web search, "what's X/Twitter saying about…", trend scans with source links), quick answers, structured JSON extraction, or coding work in a folder — then check the result and report cost. Also manages grok itself: models, sessions, resuming, login, usage limits, updates, config and docs. Use whenever the user says "grok", "ask Grok", "with Grok", "grok -p", wants a Grok/xAI second opinion, or wants a Grok-powered scan of X/Twitter discussion, even if they don't say "CLI". Not for the grok.com web app in Chrome (use grok-research / deep-research-duo) and not for calling the xAI API from code.
3
+ description: >-
4
+ Run tasks with xAI's Grok Build CLI (`grok`, installed at ~/.grok/bin/grok) headless through a
5
+ bundled uv Python runner — research questions (web search, "what's X/Twitter saying about…", trend
6
+ scans with source links), quick answers, structured JSON extraction, or coding work in a folder —
7
+ then check the result and report cost. Also manages grok itself: models, sessions, resuming, login,
8
+ usage limits, updates, config and docs. Use whenever the user says "grok", "ask Grok", "with Grok",
9
+ "grok -p", wants a Grok/xAI second opinion, or wants a Grok-powered scan of X/Twitter discussion,
10
+ even if they don't say "CLI". Not for the grok.com web app in Chrome (use grok-research /
11
+ deep-research-duo) and not for calling the xAI API from code.
4
12
  ---
5
13
 
6
14
  > Local additions: if `EXTRA_SKILL.md` exists in this skill's folder, read it too and follow it.