@hivey/cli 0.9.77 → 0.9.81

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.77",
3
+ "version": "0.9.81",
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",
@@ -35,6 +35,9 @@ for Codex, Grok and agy** below when the agent isn't on Claude Code.
35
35
  - **Spend:** a script you write that calls an LLM API directly (not through Claude Code, Codex
36
36
  or Grok CLI) logs each call with `hivey_spend.record(response, agent="<agent name>")` from
37
37
  `~/.claude/skills/hivey-agent-map/scripts/hivey_spend.py`, so the agent map counts its cost.
38
+ - **Dashboards:** when you build or deploy a dashboard, report site or web view, follow the
39
+ `hivey-dashboards` skill: give it the token login, then register it on the agent fleet with
40
+ `hivey agent-map dashboard add "<name>" <url> --agent <agent name> --note "<what it shows>" --token default`.
38
41
  - Ask before anything destructive or outward-facing (deleting data, publishing, sending
39
42
  email or posts, spending money). Draft first, then ask.
40
43
  - Commit your work in this folder; never push.
@@ -218,6 +218,17 @@ each swarm's coordinator get a desk; a swarm's workers and critics stand beside
218
218
  Quaternius, CC0: Idle + nods when working, Wave when blocked, ThumbsUp when done, Sitting when idle), Kenney
219
219
  Space Kit and Space Station Kit pieces (CC0: desks, chairs, generators, dishes, small craft, astronauts,
220
220
  consoles, crates), licences in `models/LICENSE-*`; 10 MusicGen electronic space tracks (`music/README.txt` has their prompts), 🔇/🎵 or `m`; the 🎵 menu plays a new one each time (moving on when one ends) or always one (saved with the other settings). Browsers allow sound only after you touch the page, so when playing at once is refused the music starts with your first click or key press anywhere.
221
+ - **🖥 Dashboards tab** (key 5): the dashboards the user's agents keep, listed on the left; the one you pick loads
222
+ in a frame on the right (⟳, Open in tab ↗, Edit, Remove), with a live up/down dot per dashboard (`GET
223
+ /hv-dashboard-status`, checked from this Mac). The list is in `fleet-settings.json` under `dashboards`
224
+ (owner-only file); **+ Add** on the page or `hivey agent-map dashboard add|list|edit|remove …` (`scripts/dashboards.py`,
225
+ the `hivey-dashboards` skill) edit the same list. A dashboard can carry a login token: `default` (the user's
226
+ default dashboard token, `dashboard_token` in the settings file, an EnvSave key that opens all their dashboards),
227
+ its own EnvSave `es_…` key, or a value. The frame opens `GET /hv-dashboard-open?id=…`, which redirects to its URL
228
+ with the token added as a query parameter (`token_param`, default `token`), so the page never holds tokens; the
229
+ dashboard trades it for its own session cookie (token login: hivey-dashboards skill, `references/token-login.md`).
230
+ A site that sends you to another site first (a hosting login wall) or forbids framing shows why and an Open in
231
+ tab button.
221
232
  - **CEO**: the space named `ceo` gets the captain's bridge, its own room in the ship's nose (gold trim, main
222
233
  viewscreen); its master sits at the captain's console.
223
234
 
@@ -1050,6 +1050,9 @@ def context_cmd(agents: list, size: str | None) -> int:
1050
1050
 
1051
1051
 
1052
1052
  def main() -> int:
1053
+ if sys.argv[1:2] in (["dashboard"], ["dashboards"]): # the fleet page's Dashboards list, from the shell
1054
+ import dashboards
1055
+ return dashboards.main(sys.argv[2:])
1053
1056
  ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
1054
1057
  sub = ap.add_subparsers(dest="cmd", required=True)
1055
1058
  s = sub.add_parser("scan")
@@ -0,0 +1,350 @@
1
+ """The dashboards your agents keep: one list, shown on the fleet page's 🖥 Dashboards tab.
2
+
3
+ Each entry is {"id", "name", "url", "agent", "note", "token", "token_param"}; they live in
4
+ ~/.hivey/agent-map/fleet-settings.json (owner-only) under "dashboards", so every browser sees the same list.
5
+ The page lists them on the left and shows the one you pick in a frame on the right; it adds, edits and
6
+ removes them (POST /hv-fleet-settings {"dashboards": [...]}). An agent that builds or deploys a dashboard
7
+ registers it from the shell:
8
+
9
+ python3 -I dashboards.py add "Trading dashboard" https://example.vercel.app --agent trading-strategies
10
+ python3 -I dashboards.py add "Trading dashboard" https://example.vercel.app --token default
11
+ python3 -I dashboards.py token es_… (your default dashboard token; `token` shows it)
12
+ python3 -I dashboards.py list [--json]
13
+ python3 -I dashboards.py edit "Trading dashboard" --name "Paper trading" --url https://… --note "…"
14
+ python3 -I dashboards.py remove "Trading dashboard" (by name, id or URL)
15
+
16
+ The same commands run as `hivey agent-map dashboard add|list|edit|remove …` (the hivey-dashboards skill).
17
+ `add` with a name or URL already in the list updates that entry.
18
+
19
+ Logins: a dashboard can carry a token. Opening it (GET /hv-dashboard-open?id=…) redirects to its URL with
20
+ the token added as a query parameter (`token_param`, default `token`), so a dashboard with token login
21
+ (the hivey-dashboards skill's references/token-login.md) logs you in by itself. The token is a literal value,
22
+ an EnvSave opaque key (`es_…`, read with `envsave get` when the dashboard opens; no Touch ID), or `default`:
23
+ your default dashboard token (one EnvSave key, `dashboard_token` in the settings file) that opens all your
24
+ dashboards, so changing it updates every one. Tokens are never sent to the page's list.
25
+ Python standard library only.
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import concurrent.futures
31
+ import json
32
+ import os
33
+ import re
34
+ import shutil
35
+ import subprocess
36
+ import sys
37
+ import time
38
+ import urllib.error
39
+ import urllib.parse
40
+ import urllib.request
41
+ from pathlib import Path
42
+
43
+ SETTINGS = Path.home() / ".hivey" / "agent-map" / "fleet-settings.json"
44
+ MAX = 100
45
+ LIMITS = {"name": 80, "url": 2000, "agent": 80, "note": 300}
46
+ DEFAULT = "default" # the token value meaning "my default dashboard token"
47
+ PARAM = re.compile(r"^[A-Za-z0-9_.-]{1,64}$")
48
+ FIELDS = ("name", "url", "agent", "note", "token", "token_param")
49
+
50
+
51
+ def _settings() -> dict:
52
+ try:
53
+ got = json.loads(SETTINGS.read_text())
54
+ return got if isinstance(got, dict) else {}
55
+ except (OSError, ValueError):
56
+ return {}
57
+
58
+
59
+ def valid_url(url: str) -> bool:
60
+ p = urllib.parse.urlsplit(url)
61
+ return p.scheme in ("http", "https") and bool(p.netloc) and not any(c.isspace() for c in url)
62
+
63
+
64
+ def _slug(text: str) -> str:
65
+ return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")[:40] or "dashboard"
66
+
67
+
68
+ def clean(items: object, old: list[dict] | None = None) -> list[dict]:
69
+ """Keep well-formed entries only: an http(s) URL, a name (the host when missing), short fields, unique ids.
70
+
71
+ With `old` (the saved list), an entry whose id is saved and that has no "token" key keeps its saved
72
+ token: the page never sees tokens, so it sends none back unless you typed a new one ("" removes it)."""
73
+ saved = {d["id"]: d for d in old or []}
74
+ out, ids = [], set()
75
+ for d in items if isinstance(items, list) else []:
76
+ if not isinstance(d, dict):
77
+ continue
78
+ e = {k: str(d.get(k) or "").strip()[:n] for k, n in LIMITS.items()}
79
+ if not valid_url(e["url"]):
80
+ continue
81
+ e["name"] = e["name"] or urllib.parse.urlsplit(e["url"]).netloc
82
+ prev = saved.get(str(d.get("id") or ""), {})
83
+ token = d["token"] if "token" in d else prev.get("token", "")
84
+ e["token"] = str(token or "").strip()[:4000]
85
+ param = str(d.get("token_param") or (prev.get("token_param") if "token_param" not in d else "") or "").strip()
86
+ e["token_param"] = param if PARAM.match(param) else ""
87
+ base = _slug(str(d.get("id") or "") or e["name"])
88
+ i, n = base, 2
89
+ while i in ids:
90
+ i, n = f"{base}-{n}", n + 1
91
+ ids.add(i)
92
+ out.append({"id": i, **e})
93
+ if len(out) >= MAX:
94
+ break
95
+ return out
96
+
97
+
98
+ def public(items: list[dict]) -> list[dict]:
99
+ """The list for the page: tokens replaced by what kind of login each one has."""
100
+ out = []
101
+ for d in items:
102
+ p = {k: v for k, v in d.items() if k != "token"}
103
+ tok = d.get("token") or ""
104
+ p["login"] = "" if not tok else DEFAULT if tok == DEFAULT else "envsave" if tok.startswith("es_") else "token"
105
+ out.append(p)
106
+ return out
107
+
108
+
109
+ def load() -> list[dict]:
110
+ return clean(_settings().get("dashboards"))
111
+
112
+
113
+ def write(cur: dict) -> None:
114
+ """Save the settings file readable by you only (it can hold dashboard tokens)."""
115
+ SETTINGS.parent.mkdir(parents=True, exist_ok=True)
116
+ tmp = SETTINGS.with_suffix(".tmp")
117
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
118
+ with os.fdopen(fd, "w") as f:
119
+ f.write(json.dumps(cur))
120
+ os.chmod(tmp, 0o600)
121
+ tmp.replace(SETTINGS)
122
+
123
+
124
+ def save(items: list[dict]) -> list[dict]:
125
+ cur = _settings()
126
+ cur["dashboards"] = clean(items, clean(cur.get("dashboards")))
127
+ write(cur)
128
+ return cur["dashboards"]
129
+
130
+
131
+ def _match(d: dict, key: str) -> bool:
132
+ k = key.strip().lower()
133
+ return k in (d["id"].lower(), d["name"].lower(), d["url"].lower().rstrip("/"), d["url"].lower())
134
+
135
+
136
+ def _changes(name=None, url=None, agent=None, note=None, token=None, token_param=None) -> dict:
137
+ ch = {k: v for k, v in dict(name=name, url=url, agent=agent, note=note, token=token, token_param=token_param).items()
138
+ if v is not None}
139
+ if "url" in ch and not valid_url(ch["url"]):
140
+ raise ValueError(f"not an http(s) URL: {ch['url']}")
141
+ if ch.get("token_param") and not PARAM.match(ch["token_param"]):
142
+ raise ValueError(f"bad token parameter name: {ch['token_param']}")
143
+ return ch
144
+
145
+
146
+ def add(name: str, url: str, agent: str = "", note: str = "", token: str | None = None,
147
+ token_param: str | None = None) -> dict:
148
+ ch = _changes(name=name, url=url, agent=agent or None, note=note or None, token=token, token_param=token_param)
149
+ items = load()
150
+ for i, d in enumerate(items):
151
+ if _match(d, name) or _match(d, url.rstrip("/")):
152
+ items[i] = {**d, **ch, "id": d["id"]}
153
+ break
154
+ else:
155
+ items.append(ch)
156
+ saved = save(items)
157
+ return next(d for d in saved if d["url"] == url or d["name"] == name)
158
+
159
+
160
+ def edit(key: str, **changes) -> dict | None:
161
+ """Change the given fields of the dashboard named key (name, id or URL); None if there is none."""
162
+ ch = _changes(**changes)
163
+ items = load()
164
+ for i, d in enumerate(items):
165
+ if _match(d, key):
166
+ items[i] = {**d, **ch}
167
+ return save(items)[i]
168
+ return None
169
+
170
+
171
+ def remove(key: str) -> bool:
172
+ items = load()
173
+ kept = [d for d in items if not _match(d, key)]
174
+ if len(kept) == len(items):
175
+ return False
176
+ save(kept)
177
+ return True
178
+
179
+
180
+ def default_token() -> str:
181
+ """Your default dashboard token: an EnvSave key (es_…) or a value, "" when none is set."""
182
+ return str(_settings().get("dashboard_token") or "").strip()
183
+
184
+
185
+ def set_default_token(token: str) -> None:
186
+ cur = _settings()
187
+ if token:
188
+ cur["dashboard_token"] = token.strip()[:4000]
189
+ else:
190
+ cur.pop("dashboard_token", None)
191
+ write(cur)
192
+
193
+
194
+ _resolved: dict[str, tuple[float, str]] = {}
195
+
196
+
197
+ def resolve(token: str) -> str:
198
+ """A literal token as is; an EnvSave opaque key read with `envsave get es_…` (cached for 10 minutes);
199
+ "default" is your default dashboard token."""
200
+ if token == DEFAULT:
201
+ token = default_token()
202
+ if not token or token == DEFAULT:
203
+ raise RuntimeError("no default dashboard token yet: `hivey agent-map dashboard token es_…`")
204
+ if not token.startswith("es_"):
205
+ return token
206
+ hit = _resolved.get(token)
207
+ if hit and time.time() - hit[0] < 600:
208
+ return hit[1]
209
+ exe = shutil.which("envsave") or next((p for p in ("/opt/homebrew/bin/envsave", "/usr/local/bin/envsave")
210
+ if os.path.isfile(p)), None)
211
+ if not exe:
212
+ raise RuntimeError("envsave is not installed, so the dashboard's es_ token cannot be read")
213
+ p = subprocess.run([exe, "get", token], capture_output=True, text=True, timeout=20, stdin=subprocess.DEVNULL)
214
+ value = p.stdout.strip()
215
+ if p.returncode or not value:
216
+ raise RuntimeError(f"envsave get {token[:10]}… failed: {(p.stderr or 'empty').strip()[:120]}")
217
+ _resolved[token] = (time.time(), value)
218
+ return value
219
+
220
+
221
+ def open_url(d: dict) -> str:
222
+ """The URL to open: with its token as a query parameter when it has one."""
223
+ if not d.get("token"):
224
+ return d["url"]
225
+ param = d.get("token_param") or "token"
226
+ extra = [(param, resolve(d["token"]))]
227
+ u = urllib.parse.urlsplit(d["url"])
228
+ q = [(k, v) for k, v in urllib.parse.parse_qsl(u.query, keep_blank_values=True) if k not in dict(extra)]
229
+ return urllib.parse.urlunsplit(u._replace(query=urllib.parse.urlencode(q + extra)))
230
+
231
+
232
+ def find(key: str) -> dict | None:
233
+ return next((d for d in load() if d["id"] == key), None)
234
+
235
+
236
+ def _frameable(headers) -> bool:
237
+ """Whether the page lets another site show it in a frame (X-Frame-Options, CSP frame-ancestors)."""
238
+ if (headers.get("X-Frame-Options") or "").strip().upper() in ("DENY", "SAMEORIGIN"):
239
+ return False
240
+ m = re.search(r"frame-ancestors([^;]*)", headers.get("Content-Security-Policy") or "", re.I)
241
+ if not m:
242
+ return True
243
+ srcs = m.group(1).split()
244
+ return "*" in srcs or any(s.rstrip("/") in ("http://127.0.0.1:*", "http://localhost:*", "http:") for s in srcs)
245
+
246
+
247
+ def _probe(d: dict) -> dict:
248
+ """Is the dashboard up, and can it show in the frame? Any answer below 500 counts as up."""
249
+ start = time.time()
250
+ try:
251
+ url = open_url(d)
252
+ except (RuntimeError, OSError, subprocess.SubprocessError) as e:
253
+ return {"ok": False, "error": str(e)[:160], "ms": 0}
254
+ req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 hivey-fleet-dashboards"})
255
+ try:
256
+ with urllib.request.urlopen(req, timeout=8) as r:
257
+ code, final, headers = r.status, r.geturl(), r.headers
258
+ except urllib.error.HTTPError as e:
259
+ code, final, headers = e.code, e.geturl() or url, e.headers
260
+ except (urllib.error.URLError, OSError, ValueError) as e:
261
+ return {"ok": False, "error": str(getattr(e, "reason", e))[:120], "ms": round((time.time() - start) * 1000)}
262
+ out = {"ok": code < 500, "code": code, "ms": round((time.time() - start) * 1000), "frame": _frameable(headers)}
263
+ if urllib.parse.urlsplit(final).netloc != urllib.parse.urlsplit(d["url"]).netloc:
264
+ out["elsewhere"] = urllib.parse.urlsplit(final).netloc # sent to another site, e.g. a hosting login wall
265
+ return out
266
+
267
+
268
+ def status() -> dict:
269
+ """{id: {ok, code | error, ms, frame, elsewhere?}} for every dashboard, checked in parallel."""
270
+ items = load()
271
+ if not items:
272
+ return {}
273
+ with concurrent.futures.ThreadPoolExecutor(max_workers=min(8, len(items))) as pool:
274
+ return {d["id"]: r for d, r in zip(items, pool.map(_probe, items))}
275
+
276
+
277
+ def main(argv: list[str] | None = None) -> int:
278
+ ap = argparse.ArgumentParser(prog="hivey agent-map dashboard", description=__doc__,
279
+ formatter_class=argparse.RawDescriptionHelpFormatter)
280
+ sub = ap.add_subparsers(dest="cmd", required=True)
281
+
282
+ def login_args(p) -> None:
283
+ p.add_argument("--token", help="login token: default (your default dashboard token), an EnvSave key es_… "
284
+ "or a value (\"\" removes it)")
285
+ p.add_argument("--token-param", help="the query parameter the dashboard reads it from (default token)")
286
+
287
+ a = sub.add_parser("add", help="add a dashboard (or update the one with this name or URL)")
288
+ a.add_argument("name")
289
+ a.add_argument("url")
290
+ a.add_argument("--agent", default="", help="the agent that keeps it")
291
+ a.add_argument("--note", default="", help="one line: what it shows")
292
+ login_args(a)
293
+ ls = sub.add_parser("list")
294
+ ls.add_argument("--json", action="store_true")
295
+ ed = sub.add_parser("edit", help="change a dashboard's name, URL, agent, note or token")
296
+ ed.add_argument("key", help="name, id or URL")
297
+ for f in ("name", "url", "agent", "note"):
298
+ ed.add_argument(f"--{f}")
299
+ login_args(ed)
300
+ rm = sub.add_parser("remove")
301
+ rm.add_argument("key", help="name, id or URL")
302
+ tk = sub.add_parser("token", help="show or set your default dashboard token (used by --token default)")
303
+ tk.add_argument("value", nargs="?", help="an EnvSave key es_… (best) or the token itself")
304
+ tk.add_argument("--clear", action="store_true")
305
+ args = ap.parse_args(argv)
306
+ if args.cmd == "token":
307
+ if args.clear or args.value:
308
+ set_default_token("" if args.clear else args.value)
309
+ cur = default_token()
310
+ print(f"default dashboard token: {cur[:8] + '…' if cur.startswith('es_') else ('set (a raw value)' if cur else 'none')}"
311
+ + ("" if cur else " (set it: hivey agent-map dashboard token es_…)"))
312
+ return 0
313
+ try:
314
+ if args.cmd == "add":
315
+ d = add(args.name, args.url, args.agent, args.note, args.token, args.token_param)
316
+ print(f"saved {d['name']} → {d['url']}{' (with login token)' if d['token'] else ''} (fleet page → 🖥 Dashboards)")
317
+ return 0
318
+ if args.cmd == "edit":
319
+ d = edit(args.key, name=args.name, url=args.url, agent=args.agent, note=args.note, token=args.token,
320
+ token_param=args.token_param)
321
+ if not d:
322
+ print(f"dashboards: no dashboard named {args.key}", file=sys.stderr)
323
+ return 1
324
+ print(f"saved {d['name']} → {d['url']}{' (with login token)' if d['token'] else ''}")
325
+ return 0
326
+ except ValueError as e:
327
+ print(f"dashboards: {e}", file=sys.stderr)
328
+ return 1
329
+ if args.cmd == "list":
330
+ items = public(load())
331
+ if args.json:
332
+ print(json.dumps(items, indent=1))
333
+ else:
334
+ for d in items:
335
+ print(f"{d['name']:<28} {d['url']}" + (f" [{d['agent']}]" if d["agent"] else "")
336
+ + (f" 🔑 {d['login']}" if d["login"] else ""))
337
+ if not items:
338
+ print("no dashboards yet (fleet page → 🖥 Dashboards → + Add, or `hivey agent-map dashboard add NAME URL`)")
339
+ return 0
340
+ if args.cmd == "remove":
341
+ if remove(args.key):
342
+ print(f"removed {args.key}")
343
+ return 0
344
+ print(f"dashboards: no dashboard named {args.key}", file=sys.stderr)
345
+ return 1
346
+ return 2
347
+
348
+
349
+ if __name__ == "__main__":
350
+ sys.exit(main())
@@ -179,6 +179,57 @@ body.v-jobs .search{visibility:hidden}
179
179
  #views .jbad.soft{background:var(--honey)}
180
180
  .ask.job{border-color:rgba(251,113,133,.5);cursor:pointer}
181
181
  #list{display:none;padding:12px 18px 40px}
182
+ /* ---------- dashboards: the list on the left, the one you pick in a frame on the right ---------- */
183
+ #dash{display:none;height:calc(100vh - 58px)}
184
+ #dash.on{display:flex}
185
+ body.v-dash .search{visibility:hidden}
186
+ body.v-dash #inbox{display:none}
187
+ /* the list folds away (☰ brings it back) and ⛶ gives the dashboard the whole window */
188
+ #dash.fold .dside{display:none}
189
+ #dash.max{position:fixed;inset:0;z-index:45;height:100vh!important}
190
+ #dash.max .dside{display:none}
191
+ #dash .dbar .ic{padding:4px 8px;font-size:13px;line-height:1}
192
+ #dash .dside{flex:none;width:290px;border-right:1px solid var(--line);display:flex;flex-direction:column;background:var(--panel)}
193
+ #dash .dside .hd{display:flex;align-items:center;gap:8px;padding:12px 12px 8px}
194
+ #dash .dside .hd h2{margin:0;font-size:15px;flex:1}
195
+ #dash .add{background:var(--honey);color:#1b1405;border:0;border-radius:9px;padding:6px 11px;font-weight:650;font-size:12.5px}
196
+ #dash .dlist{flex:1;overflow-y:auto;padding:4px 8px 10px;display:flex;flex-direction:column;gap:4px}
197
+ #dash .dfoot{padding:9px 12px;border-top:1px solid var(--line);color:var(--muted);font-size:11.5px;line-height:1.4}
198
+ #dash code{background:var(--panel2);padding:1px 5px;border-radius:5px;font-size:11px;word-break:break-all}
199
+ .ditem{display:flex;gap:9px;align-items:center;padding:8px 9px;border-radius:10px;cursor:pointer;border:1px solid transparent}
200
+ .ditem:hover{background:var(--panel2)}
201
+ .ditem.sel{background:var(--panel2);border-color:var(--honey)}
202
+ .ditem .fav{flex:none;width:28px;height:28px;border-radius:7px;background:var(--bg);display:grid;place-items:center;overflow:hidden;font-size:15px}
203
+ .ditem .fav img{width:18px;height:18px}
204
+ .ditem .tx{min-width:0;flex:1}
205
+ .ditem .nm{font-weight:600;font-size:13.5px;display:flex;align-items:center;gap:6px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
206
+ .ditem .host{color:var(--muted);font-size:11.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
207
+ .ditem .dot{width:8px;height:8px;border-radius:50%;background:var(--idle);flex:none}
208
+ .ditem .dot.up{background:var(--done)}.ditem .dot.down{background:var(--block)}.ditem .dot.warn{background:var(--honey)}
209
+ #dash .dmain{flex:1;min-width:0;display:flex;flex-direction:column;background:var(--bg)}
210
+ #dash .dbar{display:flex;align-items:center;gap:8px;padding:8px 12px;border-bottom:1px solid var(--line);min-height:44px}
211
+ #dash .dbar .t{font-weight:650}
212
+ #dash .dbar .m{color:var(--muted);font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1}
213
+ #dash .dbar button{background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:4px 10px;font-size:12px}
214
+ #dash .dbar button:hover{border-color:var(--honey)}
215
+ #dash .dbar button.arm{border-color:var(--block);color:var(--block)}
216
+ #dash .dview{flex:1;position:relative}
217
+ #dash iframe{position:absolute;inset:0;width:100%;height:100%;border:0;background:#fff}
218
+ #dash .dmsg{position:absolute;inset:0;display:grid;place-items:center;text-align:center;color:var(--muted);padding:30px;background:var(--bg)}
219
+ #dash .dmsg[hidden]{display:none!important}
220
+ #dash .dmsg b{color:var(--text)}
221
+ #dash .dmsg button{margin-top:10px;background:var(--honey);color:#1b1405;border:0;border-radius:9px;padding:7px 14px;font-weight:650}
222
+ .dform{display:grid;grid-template-columns:110px 1fr;gap:9px 12px;align-items:center;padding:18px;margin:18px;border-radius:var(--r);
223
+ background:var(--panel);border:1px solid var(--honey);max-width:660px}
224
+ .dform h3{grid-column:1/-1;margin:0 0 4px;font-size:15px}
225
+ .dform input[type=text],.dform input[type=url],.dform input[type=password]{background:var(--bg);border:1px solid var(--line);border-radius:8px;padding:7px 10px;color:var(--text);font:inherit;outline:none}
226
+ .dform input:focus{border-color:var(--honey)}
227
+ .dform label{color:var(--muted);font-size:12.5px}
228
+ .dform .chk{grid-column:2;display:flex;gap:7px;align-items:center;color:var(--muted);font-size:12.5px}
229
+ .dform .hint{grid-column:2;color:var(--muted);font-size:11.5px;line-height:1.45;margin-top:-4px}
230
+ .dform .btns{grid-column:2;display:flex;gap:8px;margin-top:4px}
231
+ .dform .btns button{border-radius:8px;padding:6px 14px;border:1px solid var(--line);background:var(--panel2)}
232
+ .dform .btns button.primary{background:var(--honey);color:#1b1405;border:0;font-weight:650}
182
233
  table{width:100%;border-collapse:collapse;font-size:12.5px}
183
234
  th{text-align:left;color:var(--muted);font-weight:600;padding:7px 8px;border-bottom:1px solid var(--line);cursor:pointer;white-space:nowrap;position:sticky;top:57px;background:var(--bg)}
184
235
  td{padding:6px 8px;border-bottom:1px solid #1a2130;vertical-align:top}
@@ -218,6 +269,7 @@ td.j{max-width:420px}
218
269
  <button data-v="board" title="Cards by what needs you (2)">▦ Board</button>
219
270
  <button data-v="list" title="One row per agent, for hundreds (3)">☰ List</button>
220
271
  <button data-v="jobs" title="Agent jobs: scheduled and background jobs, their map, spend, logs and sessions (4)">📊 Jobs</button>
272
+ <button data-v="dash" title="Dashboards your agents keep: one place to open them all (5)">🖥 Dashboards</button>
221
273
  </div>
222
274
  <button class="iconbtn" id="music" title="Background music on/off (m)">🔇</button>
223
275
  <button class="iconbtn" id="refresh" title="Read every terminal and session log again now (r)">⟳</button>
@@ -270,6 +322,7 @@ td.j{max-width:420px}
270
322
  </section>
271
323
  <section id="board"></section>
272
324
  <section id="list"></section>
325
+ <section id="dash"></section>
273
326
  <section id="jobs"><div id="jobhealth"></div><iframe id="jobsframe" title="Agent jobs"></iframe></section>
274
327
  </main>
275
328
  <aside id="drawer"></aside>
@@ -25,7 +25,7 @@ let data = null, agents = [], selected = null;
25
25
  // settings saved before the rename (the page was the agent office) carry over
26
26
  const ui = JSON.parse(localStorage.getItem('hv-fleet-ship') || localStorage.getItem('hv-' + 'off' + 'ice-ship') || '{}');
27
27
  ui.view ||= 'fleet';
28
- const VIEWS = ['fleet', 'board', 'list', 'jobs'];
28
+ const VIEWS = ['fleet', 'board', 'list', 'jobs', 'dash'];
29
29
  let health = null, healthAt = 0; // failing scheduled jobs (pollHealth)
30
30
  { const v = new URLSearchParams(location.search).get('view'); if (VIEWS.includes(v)) ui.view = v; if (v) history.replaceState(null, '', location.pathname); } // ?view=jobs from the menu or a jobs page
31
31
  ui.filter = null; // a status filter lasts until reload: a reload always shows every agent
@@ -946,6 +946,7 @@ function renderAll() {
946
946
  $('#board').style.display = ui.view === 'board' ? 'block' : 'none';
947
947
  $('#list').style.display = ui.view === 'list' ? 'block' : 'none';
948
948
  showJobs();
949
+ showDash();
949
950
  if (ui.view === 'fleet') { fleet.build(agents.filter(visible), data.sessions); fleet.resize(); }
950
951
  if (ui.view === 'board') renderBoard();
951
952
  if (ui.view === 'list') renderList();
@@ -966,6 +967,175 @@ function showJobs() {
966
967
  }
967
968
  fitJobs();
968
969
  }
970
+ // 🖥 Dashboards: the dashboards your agents keep, listed on the left; the one you pick shows in a frame on the
971
+ // right. One list on the fleet server (fleet-settings.json), so every browser sees it; agents add theirs from
972
+ // the shell with `hivey agent-map dashboard add NAME URL` (hivey-dashboards skill). A dashboard with a login
973
+ // token opens through /hv-dashboard-open, which adds the token: the page itself never sees tokens.
974
+ let dashes = null, dashStatus = {}, dashForm = null, dashArm = false, dashAt = 0, dashBuilt = false, dashDefault = false;
975
+ function showDash() {
976
+ const on = ui.view === 'dash';
977
+ document.body.classList.toggle('v-dash', on);
978
+ $('#dash').classList.toggle('on', on);
979
+ if (!on) { $('#dash').classList.remove('max'); return; }
980
+ renderDash();
981
+ if (Date.now() - dashAt > 20000) loadDash();
982
+ }
983
+ async function loadDash() { // the list may have changed from the terminal; then which ones answer
984
+ dashAt = Date.now();
985
+ try { const j = await post('/hv-fleet-settings', {}); if (Array.isArray(j.dashboards)) dashes = j.dashboards; dashDefault = !!j.default_token; } catch { }
986
+ renderDash();
987
+ try {
988
+ const r = await fetch('/hv-dashboard-status', { cache: 'no-store' });
989
+ if (r.ok) { dashStatus = (await r.json()).status || {}; renderDash(); }
990
+ } catch { }
991
+ }
992
+ async function saveDash(list, msg, select, deftoken) {
993
+ try {
994
+ const j = await post('/hv-fleet-settings', deftoken ? { dashboards: list, dashboard_token: deftoken } : { dashboards: list });
995
+ dashDefault = !!j.default_token;
996
+ if (!Array.isArray(j.dashboards)) throw new Error('old server');
997
+ dashes = j.dashboards; dashForm = null; dashArm = false;
998
+ if (select === 'last' && dashes.length) select = dashes[dashes.length - 1].id;
999
+ if (select !== undefined) { ui.dash = select; saveDashSel(); }
1000
+ if (msg) toast(msg);
1001
+ $('#dframe').dataset.src = ''; // the URL or token may have changed: load it again
1002
+ renderDash(); loadDash();
1003
+ } catch { toast('Could not save: the fleet server is not answering (or is too old: reload after hivey update)'); }
1004
+ }
1005
+ const saveDashSel = () => localStorage.setItem('hv-fleet-dash', ui.dash || '');
1006
+ ui.dash = localStorage.getItem('hv-fleet-dash') || '';
1007
+ function dashHost(u) { try { return new URL(u).host; } catch { return u; } }
1008
+ const dashOpenUrl = d => d.login ? '/hv-dashboard-open?id=' + encodeURIComponent(d.id) : d.url;
1009
+ function buildDash() {
1010
+ $('#dash').innerHTML = `<div class="dside"><div class="hd"><h2>🖥 Dashboards</h2><button class="add" id="dadd" title="Add a dashboard">+ Add</button></div>
1011
+ <div class="dlist" id="dlist"></div>
1012
+ <div class="dfoot">Agents add theirs: <code>hivey agent-map dashboard add NAME URL</code>, or ask any agent “add this dashboard to the agent fleet”.</div></div>
1013
+ <div class="dmain"><div class="dbar" id="dbar"></div><div class="dview"><iframe id="dframe" title="Dashboard" referrerpolicy="no-referrer"></iframe><div class="dmsg" id="dmsg" hidden></div></div></div>`;
1014
+ $('#dadd').onclick = () => { $('#dmsg').innerHTML = ''; dashForm = { name: '', url: '', agent: '', note: '', token: '' }; dashArm = false; renderDash(); $('#dmsg input')?.focus(); };
1015
+ $('#dlist').onclick = e => {
1016
+ const it = e.target.closest('.ditem');
1017
+ if (!it) return;
1018
+ ui.dash = it.dataset.id; saveDashSel(); dashForm = null; dashArm = false; renderDash();
1019
+ };
1020
+ dashBuilt = true;
1021
+ $('#dash').classList.toggle('fold', localStorage.getItem('hv-fleet-dash-fold') === '1');
1022
+ }
1023
+ // the frame fills the window below the header; the list can fold away; ⛶ covers the whole window (Esc leaves)
1024
+ function fitDash() {
1025
+ const box = $('#dash');
1026
+ if (ui.view !== 'dash' || !box || box.classList.contains('max')) return;
1027
+ box.style.height = Math.max(360, innerHeight - (box.getBoundingClientRect().top + scrollY)) + 'px';
1028
+ }
1029
+ addEventListener('resize', fitDash);
1030
+ function foldDash(on) { $('#dash').classList.toggle('fold', on); localStorage.setItem('hv-fleet-dash-fold', on ? '1' : '0'); renderDash(); }
1031
+ function maxDash(on) { $('#dash').classList.toggle('max', on); if (!on) fitDash(); renderDash(); }
1032
+ document.addEventListener('keydown', e => { if (e.key === 'Escape' && $('#dash')?.classList.contains('max')) maxDash(false); });
1033
+ function dashFormHtml(f) {
1034
+ // Login: none, your default dashboard token (one EnvSave key that opens all your dashboards), or a token for this one
1035
+ const mode = f.mode || (f.login === 'default' ? 'default' : f.login ? 'own' : f.id ? 'none' : (dashDefault ? 'default' : 'none'));
1036
+ const saved = f.id && f.login && f.login !== 'default';
1037
+ return `<form class="dform" id="dform"><h3>${f.id ? 'Edit ' + esc(f.name) : 'Add a dashboard'}</h3>
1038
+ <label>Name</label><input type="text" name="name" value="${esc(f.name)}" placeholder="Trading dashboard" required>
1039
+ <label>URL</label><input type="url" name="url" value="${esc(f.url)}" placeholder="https://…" required>
1040
+ <label>Agent</label><input type="text" name="agent" value="${esc(f.agent)}" placeholder="the agent that keeps it (optional)">
1041
+ <label>Note</label><input type="text" name="note" value="${esc(f.note)}" placeholder="what it shows (optional)">
1042
+ <label>Login</label><span class="chk" style="grid-column:auto;flex-wrap:wrap;gap:12px">
1043
+ <label class="chk" style="grid-column:auto"><input type="radio" name="mode" value="none" ${mode === 'none' ? 'checked' : ''}> none</label>
1044
+ <label class="chk" style="grid-column:auto"><input type="radio" name="mode" value="default" ${mode === 'default' ? 'checked' : ''}> my dashboard token</label>
1045
+ <label class="chk" style="grid-column:auto"><input type="radio" name="mode" value="own" ${mode === 'own' ? 'checked' : ''}> a token for this one</label></span>
1046
+ ${mode === 'default' && !dashDefault ? `<label>Your token</label><input type="password" name="deftoken" value="${esc(f.deftoken || '')}" autocomplete="off" placeholder="EnvSave key es_… (saved once, used by all your dashboards)" required>` : ''}
1047
+ ${mode === 'own' ? `<label>Token</label><input type="password" name="token" value="${esc(f.token || '')}" autocomplete="off"
1048
+ placeholder="${saved ? 'token saved: leave empty to keep it' : 'an EnvSave key es_… or the token'}" ${saved ? '' : 'required'}>
1049
+ <label>Parameter</label><input type="text" name="token_param" value="${esc(f.token_param || '')}" placeholder="token (the URL parameter the dashboard reads)">` : ''}
1050
+ <div class="hint">Opening the dashboard adds the token to its URL (<code>?token=…</code>), so a dashboard with token login logs you in by
1051
+ itself. ${dashDefault ? 'Your dashboard token is saved; ' : ''}tokens stay on this Mac and are never shown again. Agents build this login into
1052
+ the dashboards they make (hivey-dashboards skill).</div>
1053
+ <div class="btns"><button class="primary" type="submit">${f.id ? 'Save' : 'Add dashboard'}</button><button type="button" id="dcancel">Cancel</button></div></form>`;
1054
+ }
1055
+ function renderDash() {
1056
+ if (ui.view !== 'dash') return;
1057
+ if (!dashBuilt) buildDash();
1058
+ requestAnimationFrame(fitDash);
1059
+ const folded = $('#dash').classList.contains('fold'), maxed = $('#dash').classList.contains('max');
1060
+ const sideBtns = `<button class="ic" id="dfold" title="${folded || maxed ? 'Show the dashboard list' : 'Hide the list: the dashboard gets the full width'}">${folded || maxed ? '☰' : '⟨'}</button>`;
1061
+ const list = dashes || [];
1062
+ if (!list.find(d => d.id === ui.dash) && list.length) ui.dash = list[0].id;
1063
+ const cur = list.find(d => d.id === ui.dash);
1064
+ // the list on the left
1065
+ $('#dlist').innerHTML = dashes === null ? '<div class="meta" style="padding:8px">loading…</div>'
1066
+ : !list.length ? '<div class="meta" style="padding:8px">No dashboards yet. Press <b>+ Add</b>.</div>'
1067
+ : list.map(d => {
1068
+ const s = dashStatus[d.id], cls = !s ? '' : !s.ok ? 'down' : s.elsewhere || s.frame === false ? 'warn' : 'up';
1069
+ const tip = !s ? 'checking…' : !s.ok ? `not answering: ${s.error || s.code}` : s.elsewhere ? `sends you to ${s.elsewhere} (a login wall?)`
1070
+ : s.frame === false ? 'opens only in a new tab' : `up · ${s.code} · ${s.ms} ms`;
1071
+ let origin = ''; try { origin = new URL(d.url).origin; } catch { }
1072
+ return `<div class="ditem ${d.id === ui.dash && !(dashForm && !dashForm.id) ? 'sel' : ''}" data-id="${esc(d.id)}" title="${esc(d.note || d.url)}">
1073
+ <div class="fav">${origin ? `<img src="${esc(origin)}/favicon.ico" alt="" onerror="this.replaceWith('🖥')">` : '🖥'}</div>
1074
+ <div class="tx"><div class="nm"><span class="dot ${cls}" title="${esc(tip)}"></span>${esc(d.name)}${d.login ? ' <span title="opens with its login token">🔑</span>' : ''}</div>
1075
+ <div class="host">${esc(d.agent ? '🤖 ' + d.agent + ' · ' : '')}${esc(dashHost(d.url))}</div></div></div>`;
1076
+ }).join('');
1077
+ // the bar and the frame on the right
1078
+ const bar = $('#dbar'), frame = $('#dframe'), msg = $('#dmsg');
1079
+ if (dashForm) {
1080
+ bar.innerHTML = sideBtns + `<span class="t">${dashForm.id ? 'Edit dashboard' : 'New dashboard'}</span>`;
1081
+ wireDashBar(folded, maxed);
1082
+ if (!msg.querySelector('#dform')) { msg.innerHTML = dashFormHtml(dashForm); wireDashForm(list); }
1083
+ msg.hidden = false; msg.style.display = 'block'; msg.style.overflow = 'auto';
1084
+ return;
1085
+ }
1086
+ msg.style.display = ''; msg.style.overflow = '';
1087
+ if (msg.querySelector('#dform')) msg.innerHTML = '';
1088
+ if (!cur) { bar.innerHTML = sideBtns; wireDashBar(folded, maxed); msg.hidden = false; msg.innerHTML = dashes === null ? '' : '<div><b>No dashboards yet</b><br>Add the dashboards your agents keep, and open them all from here.<br><button id="dfirst">+ Add a dashboard</button></div>';
1089
+ $('#dfirst')?.addEventListener('click', () => $('#dadd').click()); frame.removeAttribute('src'); frame.dataset.src = ''; return; }
1090
+ const s = dashStatus[cur.id];
1091
+ bar.innerHTML = sideBtns + `<span class="t">${esc(cur.name)}</span><span class="m">${esc(cur.note || dashHost(cur.url))}</span>
1092
+ <button id="dreload" title="Load it again">⟳</button><button class="ic" id="dmax" title="${maxed ? 'Back to the fleet page (Esc)' : 'Full window: the dashboard covers the whole page (Esc to leave)'}">${maxed ? '✕' : '⛶'}</button><button id="dtab" title="Open in a new browser tab">Open in tab ↗</button>
1093
+ <button id="dedit">Edit</button><button id="ddel" class="${dashArm ? 'arm' : ''}">${dashArm ? 'Remove?' : 'Remove'}</button>`;
1094
+ wireDashBar(folded, maxed);
1095
+ $('#dmax').onclick = () => maxDash(!maxed);
1096
+ $('#dreload').onclick = () => { frame.dataset.src = ''; renderDash(); };
1097
+ $('#dtab').onclick = () => window.open(dashOpenUrl(cur), '_blank', 'noopener');
1098
+ $('#dedit').onclick = () => { dashForm = { ...cur }; renderDash(); };
1099
+ $('#ddel').onclick = () => { if (!dashArm) { dashArm = true; renderDash(); return; } saveDash(list.filter(x => x.id !== cur.id), `Removed ${cur.name}`); };
1100
+ const blocked = s && s.ok && s.frame === false;
1101
+ if (blocked) { // the site refuses to be shown inside another page (or Vercel's login does)
1102
+ msg.hidden = false;
1103
+ msg.innerHTML = `<div><b>${esc(cur.name)} can't be shown inside the fleet page</b><br>${s.elsewhere
1104
+ ? `It sends you to <b>${esc(s.elsewhere)}</b> first, a login page that refuses frames. Turn that hosting login off (for a Vercel project: Settings → Deployment Protection) and give the dashboard token login instead (hivey-dashboards skill).`
1105
+ : 'The site does not allow being shown inside other pages (X-Frame-Options or frame-ancestors).'}<br><button id="dtab2">Open in a new tab ↗</button></div>`;
1106
+ $('#dtab2').onclick = () => window.open(dashOpenUrl(cur), '_blank', 'noopener');
1107
+ frame.removeAttribute('src'); frame.dataset.src = '';
1108
+ return;
1109
+ }
1110
+ msg.hidden = true;
1111
+ const src = dashOpenUrl(cur);
1112
+ if (frame.dataset.src !== src + '#' + cur.id) { frame.dataset.src = src + '#' + cur.id; frame.src = src; }
1113
+ }
1114
+ function wireDashBar(folded, maxed) {
1115
+ $('#dfold').onclick = () => { if (maxed) { $('#dash').classList.remove('max'); foldDash(false); } else foldDash(!folded); };
1116
+ }
1117
+ function wireDashForm(list) {
1118
+ const f = $('#dform');
1119
+ $('#dcancel').onclick = () => { dashForm = null; $('#dmsg').innerHTML = ''; renderDash(); };
1120
+ f.oninput = () => Object.assign(dashForm, Object.fromEntries(new FormData(f)));
1121
+ f.querySelectorAll('input[name=mode]').forEach(r => r.onchange = () => { Object.assign(dashForm, Object.fromEntries(new FormData(f))); $('#dmsg').innerHTML = ''; renderDash(); });
1122
+ f.onsubmit = e => {
1123
+ e.preventDefault();
1124
+ const v = Object.fromEntries(new FormData(f));
1125
+ let url = v.url.trim();
1126
+ if (!/^https?:\/\//i.test(url)) url = 'https://' + url;
1127
+ try { new URL(url); } catch { toast('That URL does not look right'); return; }
1128
+ const entry = { name: v.name.trim(), url, agent: v.agent.trim(), note: v.note.trim(), token_param: (v.token_param || '').trim() };
1129
+ if (v.mode === 'none') entry.token = '';
1130
+ else if (v.mode === 'default') entry.token = 'default';
1131
+ else if ((v.token || '').trim()) entry.token = v.token.trim(); // no "token" key: the server keeps the saved one
1132
+ else if (dashForm.login === 'default' || !dashForm.login) { toast('Type the token for this dashboard'); return; }
1133
+ const id = dashForm.id;
1134
+ const next = id ? list.map(d => d.id === id ? { id, ...entry } : d) : [...list, entry];
1135
+ $('#dmsg').innerHTML = '';
1136
+ saveDash(next, id ? `Saved ${entry.name}` : `Added ${entry.name}`, id || 'last', (v.deftoken || '').trim());
1137
+ };
1138
+ }
969
1139
  // scheduled jobs that failed (non-zero exit) or need a check, live from the page server: a count on the
970
1140
  // Jobs tab, a chip in the top strip and a banner over the jobs pages (the nightly report is a day old)
971
1141
  async function pollHealth() {
@@ -1107,7 +1277,7 @@ addEventListener('keydown', e => {
1107
1277
  if (e.target.matches('input')) { if (e.key === 'Escape') { e.target.value = ''; e.target.blur(); renderAll(); } return; }
1108
1278
  if (e.key === '/') { e.preventDefault(); $('#q').focus(); }
1109
1279
  else if (e.key === 'Escape') closeDrawer();
1110
- else if (e.key >= '1' && e.key <= '4') { ui.view = VIEWS[+e.key - 1]; save(); renderAll(); }
1280
+ else if (e.key >= '1' && e.key <= '5') { ui.view = VIEWS[+e.key - 1]; save(); renderAll(); }
1111
1281
  else if (e.key === 'r') refreshNow();
1112
1282
  else if (e.key === 'f') fleet.fit();
1113
1283
  else if (e.key === 't') toggleStyle();
@@ -1133,6 +1303,7 @@ $('#space').onchange = e => {
1133
1303
  };
1134
1304
  post('/hv-fleet-refresh', { load: true }).then(j => {
1135
1305
  showEvery(j.every);
1306
+ if (Array.isArray(j.dashboards)) { dashes = j.dashboards; dashDefault = !!j.default_token; renderDash(); }
1136
1307
  if (j.space && j.space !== String(ui.space || 'random')) { // the server's choice wins (set in another browser)
1137
1308
  ui.space = j.space; save(); $('#space').value = j.space;
1138
1309
  if (j.space !== 'random') fleet.setSpace(j.space);
@@ -11,6 +11,12 @@ trigger them:
11
11
  GET /hv-job-health scheduled jobs whose latest run failed (non-zero exit) or needs a check (not
12
12
  loaded, missed its run, errors in its log), from a jobs-only scan (~0.1 s, no
13
13
  model), with each one's error lines and log tail: the Jobs tab's warnings
14
+ GET /hv-dashboard-status is each dashboard on the fleet page's 🖥 Dashboards tab up: {id: {ok, code | error,
15
+ ms, frame}}, checked in parallel from this Mac (dashboards.py; the list itself is in
16
+ fleet-settings.json, POST /hv-fleet-settings {"dashboards": [...]} replaces it; the
17
+ page never sees tokens, so an entry sent back without "token" keeps its saved one;
18
+ {"dashboard_token": "es_…"} sets the default token `"token": "default"` uses, write-only)
19
+ GET /hv-dashboard-open?id=<id> a redirect to that dashboard with its login token added (the frame's src)
14
20
  POST /hv-refresh `agent_map.py refresh` (free: no model)
15
21
  GET /fleet/ the agent fleet page (files in reports/fleet/; old /fleet/ links redirect here)
16
22
  POST /hv-fleet-refresh `fleet.py run` in the background (the agent fleet, /fleet/)
@@ -59,7 +65,7 @@ IDLE_SECONDS = 2 * 3600
59
65
  PING = "/hv-ping"
60
66
  LEGACY_PAGE = "/office" # the fleet page's address before it was renamed; redirected to /fleet/
61
67
  MARK = b"hivey-agent-map"
62
- VERSION = b"fleet-17" # bump when the server gains actions, so `ensure` replaces an older one
68
+ VERSION = b"fleet-19" # bump when the server gains actions, so `ensure` replaces an older one
63
69
  FLEET_EVERY = 300 # seconds between full fleet refreshes (every terminal re-summarized) while its page is open
64
70
  FLEET_LIVE = 60 # seconds between live passes (status, context, screen; only changed statuses summarized)
65
71
  FLEET_WATCHED = 600 # the page counts as open for this long after its last poll
@@ -82,6 +88,11 @@ def fleet_settings() -> dict:
82
88
  return {}
83
89
 
84
90
 
91
+ def dashboards_public() -> list:
92
+ import dashboards
93
+ return dashboards.public(dashboards.load())
94
+
95
+
85
96
  def clean_ships(ships: object) -> dict:
86
97
  """{session: {x, z}} where you dragged each ship on the fleet page (bad entries dropped)."""
87
98
  out = {}
@@ -439,6 +450,14 @@ def running(current_only: bool = True) -> int | None:
439
450
  return port if body == MARK + b" " + VERSION or not current_only else None
440
451
 
441
452
 
453
+ def server_hivey() -> str | None:
454
+ """The hivey binary the running server reads agents and sessions with."""
455
+ try:
456
+ return json.loads(INFO.read_text()).get("hivey")
457
+ except (OSError, ValueError, AttributeError):
458
+ return None
459
+
460
+
442
461
  def port_free(port: int) -> bool:
443
462
  import socket
444
463
  with socket.socket() as sock:
@@ -452,9 +471,11 @@ def port_free(port: int) -> bool:
452
471
  def ensure() -> int | None:
453
472
  """The running server's port, starting one in the background when there is none."""
454
473
  port = running()
455
- if port and (port == PREFERRED_PORT or not port_free(PREFERRED_PORT)):
474
+ if port and (port == PREFERRED_PORT or not port_free(PREFERRED_PORT)) and server_hivey() == hivey_bin():
456
475
  return port
457
- if port or running(current_only=False): # older version, or on another port while ours is free
476
+ # older version, on another port while ours is free, or reading another hivey (a dev build started
477
+ # it: that binary talks to the hivey-dev server, so the fleet would show its agents, not yours)
478
+ if port or running(current_only=False):
458
479
  try:
459
480
  os.kill(int(json.loads(INFO.read_text())["pid"]), 15)
460
481
  time.sleep(0.3)
@@ -513,6 +534,10 @@ class Handler(http.server.SimpleHTTPRequestHandler):
513
534
  return self.jobs()
514
535
  if path == "/hv-job-health":
515
536
  return self.job_health()
537
+ if path == "/hv-dashboard-status":
538
+ return self.dashboard_status()
539
+ if path == "/hv-dashboard-open":
540
+ return self.dashboard_open(query)
516
541
  return super().do_GET()
517
542
 
518
543
  def job_health(self) -> None:
@@ -539,6 +564,36 @@ class Handler(http.server.SimpleHTTPRequestHandler):
539
564
  "tail": (j.get("tail") or [])[-15:]})
540
565
  return self.answer(200, json.dumps(out).encode())
541
566
 
567
+ def dashboard_status(self) -> None:
568
+ """Which of the saved dashboards answer right now (the dots on the Dashboards tab)."""
569
+ port = self.server.server_address[1]
570
+ if self.headers.get("Host") not in (f"127.0.0.1:{port}", f"localhost:{port}"):
571
+ return self.answer(403, b'{"ok":false,"error":"local pages only"}')
572
+ import dashboards
573
+ return self.answer(200, json.dumps({"ok": True, "status": dashboards.status()}).encode())
574
+
575
+ def dashboard_open(self, query: str) -> None:
576
+ """The frame (or new tab) for one dashboard: a redirect to its URL with its token, for this page only."""
577
+ port = self.server.server_address[1]
578
+ if self.headers.get("Host") not in (f"127.0.0.1:{port}", f"localhost:{port}") or \
579
+ self.headers.get("Sec-Fetch-Site", "same-origin") not in ("same-origin", "none"):
580
+ return self.answer(403, b"only the fleet page can open its dashboards", "text/plain")
581
+ import dashboards
582
+ d = dashboards.find(urllib.parse.parse_qs(query).get("id", [""])[0])
583
+ if not d:
584
+ return self.answer(404, b"no such dashboard", "text/plain")
585
+ try:
586
+ url = dashboards.open_url(d)
587
+ except (RuntimeError, OSError, subprocess.SubprocessError) as e:
588
+ return self.answer(500, f"cannot read the login token: {e}".encode(), "text/plain; charset=utf-8")
589
+ self.send_response(302)
590
+ self.send_header("Location", url)
591
+ self.send_header("Cache-Control", "no-store")
592
+ self.send_header("Referrer-Policy", "no-referrer")
593
+ self.send_header("Content-Length", "0")
594
+ self.end_headers()
595
+ return None
596
+
542
597
  def jobs(self) -> None:
543
598
  """The fleet page's Jobs tab: the latest agent jobs page, or the first report being built."""
544
599
  import report
@@ -573,7 +628,7 @@ class Handler(http.server.SimpleHTTPRequestHandler):
573
628
  return self.answer(403, b'{"ok":false,"error":"only the agent map pages can do this"}')
574
629
  if self.path in ("/hv-fleet-refresh", "/hv-fleet-settings"):
575
630
  try:
576
- length = min(int(self.headers.get("Content-Length") or 0), 4096)
631
+ length = min(int(self.headers.get("Content-Length") or 0), 262144) # the dashboards list
577
632
  req = json.loads(self.rfile.read(length) or b"{}")
578
633
  req = req if isinstance(req, dict) else {}
579
634
  except ValueError:
@@ -594,9 +649,16 @@ class Handler(http.server.SimpleHTTPRequestHandler):
594
649
  cur["track"] = str(req["track"])
595
650
  if "ships" in req: # the ship positions you dragged on the fleet page
596
651
  cur["ships"] = clean_ships(req["ships"])
597
- FLEET_SETTINGS.write_text(json.dumps(cur))
652
+ import dashboards
653
+ if "dashboards" in req: # the Dashboards tab's list, replaced whole (bad entries dropped, tokens kept)
654
+ cur["dashboards"] = dashboards.clean(req["dashboards"], dashboards.clean(cur.get("dashboards")))
655
+ if isinstance(req.get("dashboard_token"), str) and req["dashboard_token"].strip(): # write-only
656
+ cur["dashboard_token"] = req["dashboard_token"].strip()[:4000]
657
+ dashboards.write(cur) # owner-only: it can hold dashboard tokens
598
658
  return self.answer(200, json.dumps({"ok": True, "every": fleet_every(), "space": cur.get("space"), "track": cur.get("track"),
599
- "ships": cur.get("ships", {})}).encode())
659
+ "ships": cur.get("ships", {}),
660
+ "dashboards": dashboards.public(dashboards.clean(cur.get("dashboards"))),
661
+ "default_token": bool(cur.get("dashboard_token"))}).encode())
600
662
  every = fleet_every()
601
663
  # a page load: a quick pass when updating every minute, a full one otherwise; ⟳: always full
602
664
  quick = bool(req.get("quick")) or (bool(req.get("load")) and every == "minute")
@@ -606,7 +668,9 @@ class Handler(http.server.SimpleHTTPRequestHandler):
606
668
  start_fleet_refresh(quick=quick)
607
669
  return self.answer(200, json.dumps({"ok": True, "started": True, "every": every,
608
670
  "space": fleet_settings().get("space"), "track": fleet_settings().get("track"),
609
- "ships": clean_ships(fleet_settings().get("ships"))}).encode())
671
+ "ships": clean_ships(fleet_settings().get("ships")),
672
+ "dashboards": dashboards_public(),
673
+ "default_token": bool(fleet_settings().get("dashboard_token"))}).encode())
610
674
  if self.path == "/hv-fleet-action":
611
675
  try:
612
676
  length = min(int(self.headers.get("Content-Length") or 0), 4096)
@@ -654,7 +718,7 @@ def serve() -> int:
654
718
  except OSError: # taken: any free port
655
719
  httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
656
720
  port = httpd.server_address[1]
657
- INFO.write_text(json.dumps({"port": port, "pid": os.getpid()}))
721
+ INFO.write_text(json.dumps({"port": port, "pid": os.getpid(), "hivey": hivey_bin()}))
658
722
 
659
723
  def watchdog() -> None:
660
724
  while True:
@@ -0,0 +1,82 @@
1
+ ---
2
+ name: hivey-dashboards
3
+ description: >
4
+ Create dashboards that open logged in from the hivey agent fleet, and manage the fleet page's
5
+ 🖥 Dashboards tab: add, list, edit and remove dashboards (Vercel sites, local servers, anything
6
+ with a URL) and their login tokens. Use whenever you build, deploy or change a dashboard, report
7
+ site or web view for the user or an agent (give it the token login in references/token-login.md,
8
+ then register it, without being asked); and whenever the user says "add this dashboard to the
9
+ agent fleet", "register my dashboard", "remove/rename that dashboard", "change its token",
10
+ "which dashboards do I have", or gives a dashboard URL to keep track of. Works from any agent
11
+ hivey runs (Claude Code, Codex, Grok, Antigravity).
12
+ allowed-tools:
13
+ - Bash
14
+ ---
15
+
16
+ > Local additions: if `EXTRA_SKILL.md` exists in this skill's folder, read it too and follow it.
17
+ > It holds this machine's own additions; hivey updates never touch it, so put local changes
18
+ > there, never here.
19
+
20
+ # hivey dashboards
21
+
22
+ The agent fleet page (hivey menu → agent fleet, or `hivey agent-map fleet`) has a **🖥 Dashboards** tab:
23
+ the user's dashboards listed on the left with a live up/down dot, and the one they pick loaded in a frame
24
+ on the right, logged in. The same list is edited from the page (**+ Add**, Edit, Remove) and from the
25
+ shell, so this skill and the page always agree.
26
+
27
+ ## How the login works
28
+
29
+ Each user has one **dashboard token** (EnvSave key `DASHBOARD_TOKEN_<USER>`, 32+ characters) that opens
30
+ all their dashboards. hivey saves it once as the *default dashboard token*; a dashboard registered with
31
+ `--token default` opens as `https://<site>/?token=<it>`, and the site trades the token for its own session
32
+ cookie. No hosting login (no Vercel Deployment Protection): it refuses frames, and the token login protects
33
+ the site instead. Tokens never reach the page; the local fleet server adds them when a dashboard opens.
34
+
35
+ ## Building a dashboard
36
+
37
+ When you create or change a dashboard (any web page that shows the user's data):
38
+
39
+ 1. **Give it the token login** exactly as in `references/token-login.md` (Next.js or a static page with
40
+ Vercel functions; the contract applies to any stack): `?token=` → `/api/auth/token` → signed
41
+ `SameSite=None; Partitioned` session cookie, token stripped from the URL, every data endpoint 401
42
+ without the cookie, no `X-Frame-Options`, the host's own login wall off.
43
+ 2. **The token on the server** comes from the user's `DASHBOARD_TOKEN_<USER>` EnvSave key
44
+ (`envsave.get("es_…")`). If you don't know the key, ask the user for it; never ask for the token
45
+ itself. Pushing it to Vercel (`envsave vercel …`) unlocks the vault: tell the user first and let them run it.
46
+ 3. **Check it** with the two `curl` lines at the end of the reference (a wrong token gets 401, nothing
47
+ forbids framing).
48
+ 4. **Register it** (below) with `--token default`, and tell the user it is on the 🖥 Dashboards tab.
49
+
50
+ ## Managing the list
51
+
52
+ ```bash
53
+ hivey agent-map dashboard list # name, URL, agent, 🔑 login (--json for the fields)
54
+ hivey agent-map dashboard add "Trading dashboard" https://trading.example.app \
55
+ --agent trading-strategies --note "paper accounts, trades and job status" --token default
56
+ hivey agent-map dashboard edit "Trading dashboard" --name "Paper trading" --url https://new.example.app
57
+ hivey agent-map dashboard edit "Trading dashboard" --token default # or es_… for its own token, "" for none
58
+ hivey agent-map dashboard remove "Paper trading" # by name, id or URL; removes the card only
59
+ hivey agent-map dashboard token # is a default dashboard token set?
60
+ hivey agent-map dashboard token es_… # set it (the user's DASHBOARD_TOKEN_<USER> key)
61
+ ```
62
+
63
+ - `add` with a name or URL already in the list updates that entry instead of adding a twin. Run
64
+ `list` first so you edit the existing card rather than adding a duplicate under a new name.
65
+ - URLs must be `http://` or `https://` (local servers like `http://localhost:3000` are fine). Prefer the
66
+ stable production URL (`vercel project ls` in the project folder, its README) over a preview URL.
67
+ - `--agent` is the agent that keeps the dashboard (its folder name); leave it out for the user's own.
68
+ `--note` is one short line on what it shows.
69
+ - `--token default` uses the default dashboard token, so changing that key later updates every dashboard.
70
+ A dashboard that needs a different token gets its own EnvSave key (`--token es_…`); a raw value works
71
+ but lands in the settings file and your shell history. `--token-param` changes the URL parameter
72
+ (default `token`). Never put a token in the name, note or URL.
73
+ - No default token yet: ask the user for their `DASHBOARD_TOKEN_<USER>` EnvSave key, or tell them to pick
74
+ "my dashboard token" in the page's form, which asks for it once.
75
+ - If `hivey` is not on PATH: `python3 -I ~/.claude/skills/hivey-agent-map/scripts/dashboards.py …` (same
76
+ arguments).
77
+
78
+ ## When a dashboard won't show in the frame
79
+
80
+ The page says why. "Sends you to another site": a hosting login wall (turn it off and use the token login);
81
+ "does not allow being shown inside other pages": remove `X-Frame-Options` / `frame-ancestors` from the
82
+ site. A red dot means the site did not answer, or its token could not be read.
@@ -0,0 +1,111 @@
1
+ # Token login for a dashboard (opens logged in from the agent fleet)
2
+
3
+ The fleet page opens a dashboard as `https://<site>/?token=<the user's dashboard token>` inside a frame.
4
+ The site trades the token for its own session cookie and drops the token from the address bar. One token
5
+ per user (EnvSave `DASHBOARD_TOKEN_<USER>`, 32+ characters) opens all of that user's dashboards.
6
+
7
+ ## The contract (any stack)
8
+
9
+ 1. **Any page with `?token=`**: redirect (303) to `/api/auth/token?token=<t>&next=<same path and query
10
+ without token>`, with `Referrer-Policy: no-referrer`. Do it in middleware, or first thing in the page's
11
+ script for a static site.
12
+ 2. **`GET /api/auth/token`**:
13
+ - reject tokens shorter than 32 characters, and any token when the expected one is missing;
14
+ - compare in constant time (hash both sides, then `timingSafeEqual`);
15
+ - wrong → `401 Invalid or expired dashboard token`;
16
+ - right → `303` to `next` (only a path starting with `/`, never `//` or `/\`) with
17
+ `Cache-Control: no-store`, `Referrer-Policy: no-referrer` and
18
+ `Set-Cookie: session=<exp>.<hmac(exp)>; Path=/; Max-Age=2592000; HttpOnly; Secure; SameSite=None; Partitioned`.
19
+ `SameSite=None; Partitioned` is what keeps the login working inside the fleet's frame. Locally
20
+ (http://localhost) use `SameSite=Lax` without `Secure`/`Partitioned`.
21
+ 3. **Sign the cookie** with HMAC-SHA256 keyed by the dashboard token plus another server secret (e.g. the
22
+ data token), so rotating either logs everyone out. Check the expiry and the signature on every request.
23
+ 4. **Every data endpoint** checks the cookie; with none, `401 {"error": "Not logged in: open this dashboard
24
+ from the hivey fleet page (token login)."}`. The page shows that message instead of empty charts.
25
+ 5. **Let it be framed:** no `X-Frame-Options`, and no `frame-ancestors` that excludes
26
+ `http://127.0.0.1:*`. Turn off the host's own login wall (a Vercel project: Settings → Deployment
27
+ Protection → off), which refuses frames; the token login protects the site instead.
28
+ 6. **The secret on the server:** in code read it with `envsave.get("es_…")` (the user's
29
+ `DASHBOARD_TOKEN_<USER>` key); on Vercel that falls back to an env var named after the key, so set it once
30
+ per project: `envsave vercel DASHBOARD_TOKEN_<USER>` in the linked project folder (it unlocks the vault:
31
+ tell the user which key and why, and let them run it). A plain `DASHBOARD_TOKEN` env var works too. Never write the token into the repo.
32
+
33
+ ## Next.js (App Router), as in x-post-viewer
34
+
35
+ `middleware.ts`:
36
+ ```ts
37
+ import { NextRequest, NextResponse } from "next/server";
38
+ export function middleware(req: NextRequest) {
39
+ const url = req.nextUrl, token = url.searchParams.get("token");
40
+ if (!token || url.pathname.startsWith("/api/")) return NextResponse.next();
41
+ const rest = new URLSearchParams(url.searchParams); rest.delete("token");
42
+ const target = new URL("/api/auth/token", url.origin);
43
+ target.searchParams.set("token", token);
44
+ target.searchParams.set("next", url.pathname + (rest.size ? `?${rest}` : ""));
45
+ const res = NextResponse.redirect(target, 303);
46
+ res.headers.set("Referrer-Policy", "no-referrer");
47
+ return res;
48
+ }
49
+ export const config = { matcher: ["/((?!_next/|api/|favicon|.*\\.(?:png|jpg|svg|ico)$).*)"] };
50
+ ```
51
+
52
+ `lib/auth.ts`:
53
+ ```ts
54
+ import crypto from "node:crypto";
55
+ import envsave from "@envsave/cli";
56
+ export const SESSION_COOKIE = "session", SESSION_MAX_AGE = 60 * 60 * 24 * 30;
57
+ const want = () => envsave.get("es_…") || ""; // DASHBOARD_TOKEN_<USER>
58
+ const key = () => `${want()}\0${process.env.OTHER_SERVER_SECRET || ""}`;
59
+ const sign = (p: string) => crypto.createHmac("sha256", key()).update(p).digest("base64url");
60
+ const same = (a: string, b: string) => crypto.timingSafeEqual(
61
+ crypto.createHash("sha256").update(a).digest(), crypto.createHash("sha256").update(b).digest());
62
+ export const tokenOk = (t: unknown) => typeof t === "string" && t.length >= 32 && want().length >= 32 && same(t, want());
63
+ export const sessionValue = () => { const exp = String(Math.floor(Date.now() / 1000) + SESSION_MAX_AGE); return `${exp}.${sign(exp)}`; };
64
+ export function loggedIn(cookie: string | undefined) {
65
+ const [exp, sig] = (cookie || "").split(".");
66
+ return !!exp && !!sig && Number(exp) * 1000 > Date.now() && want().length >= 32 && same(sig, sign(exp));
67
+ }
68
+ ```
69
+
70
+ `app/api/auth/token/route.ts`:
71
+ ```ts
72
+ import { NextRequest, NextResponse } from "next/server";
73
+ import { SESSION_COOKIE, SESSION_MAX_AGE, tokenOk, sessionValue } from "@/lib/auth";
74
+ export async function GET(req: NextRequest) {
75
+ const url = req.nextUrl, raw = url.searchParams.get("next") || "/";
76
+ const next = raw.startsWith("/") && !raw.startsWith("//") && !raw.startsWith("/\\") ? raw : "/";
77
+ if (!tokenOk(url.searchParams.get("token"))) return new NextResponse("Invalid or expired dashboard token", { status: 401 });
78
+ const res = NextResponse.redirect(new URL(next, url.origin), 303);
79
+ const prod = process.env.NODE_ENV === "production";
80
+ res.cookies.set(SESSION_COOKIE, sessionValue(), { httpOnly: true, sameSite: prod ? "none" : "lax", secure: prod,
81
+ partitioned: prod, path: "/", maxAge: SESSION_MAX_AGE });
82
+ res.headers.set("Referrer-Policy", "no-referrer"); res.headers.set("Cache-Control", "no-store");
83
+ return res;
84
+ }
85
+ ```
86
+ Data routes: `if (!loggedIn(req.cookies.get(SESSION_COOKIE)?.value)) return 401`.
87
+ A multi-user app keeps one dashboard token per user and signs the user name into the cookie.
88
+
89
+ ## Static page + Vercel functions, as in trading-dashboard
90
+
91
+ - `lib/auth.js`: the same `tokenOk`, `sessionCookie()` (returns the whole `Set-Cookie` string above) and
92
+ `loggedIn(req)` (reads `req.headers.get("cookie")`).
93
+ - `api/auth/token.js`: `export async function GET(req)`: the checks above, then
94
+ `new Response(null, { status: 303, headers: { Location, "Set-Cookie": sessionCookie(), … } })`.
95
+ - First lines of the page script:
96
+ ```js
97
+ { const q = new URLSearchParams(location.search);
98
+ if (q.has("token")) { const t = q.get("token"); q.delete("token");
99
+ location.replace(`/api/auth/token?token=${encodeURIComponent(t)}&next=${encodeURIComponent(location.pathname + (q.size ? `?${q}` : ""))}`);
100
+ throw new Error("redirecting to token login"); } }
101
+ ```
102
+ - `api/data.js` returns 401 without `loggedIn(req)`.
103
+
104
+ ## Check it before registering
105
+
106
+ ```bash
107
+ curl -s -o /dev/null -w "%{http_code}\n" "https://<site>/api/auth/token?token=$(printf x%.0s {1..32})" # 401
108
+ curl -sI "https://<site>/" | grep -iE "x-frame-options|frame-ancestors" # nothing
109
+ ```
110
+ Then register it with `--token default` and open it on the fleet page's 🖥 Dashboards tab: it should show
111
+ the dashboard logged in, inside the frame. Never print the real token while testing.