@hivey/cli 0.0.0-stage → 0.9.36
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.
- package/README.md +235 -2
- package/bin/hivey.js +98 -0
- package/native/darwin-arm64/hivey +0 -0
- package/package.json +36 -4
- package/platforms.json +3 -0
- package/repo/LICENSE +201 -0
- package/repo/NOTICE +18 -0
- package/repo/README.md +148 -0
- package/repo/install.sh +365 -0
- package/repo/pets/README.md +25 -0
- package/repo/pets/hivey-dot/CLAUDE.md +55 -0
- package/repo/pets/hivey-dot/build.sh +34 -0
- package/repo/pets/hivey-dot/main.swift +750 -0
- package/repo/pets/hivey-h/CLAUDE.md +75 -0
- package/repo/pets/hivey-h/build.sh +34 -0
- package/repo/pets/hivey-h/main.swift +739 -0
- package/repo/pets/hivey-prompt/CLAUDE.md +59 -0
- package/repo/pets/hivey-prompt/build.sh +34 -0
- package/repo/pets/hivey-prompt/main.swift +691 -0
- package/repo/pets/pet.py +288 -0
- package/repo/pets/shared/HiveyWatch.swift +437 -0
- package/repo/pets/test_pet.py +122 -0
- package/repo/plugins/README.md +108 -0
- package/repo/plugins/agent-creator/herdr-plugin.toml +17 -0
- package/repo/plugins/dashboard/dashboard.py +507 -0
- package/repo/plugins/dashboard/herdr-plugin.toml +14 -0
- package/repo/plugins/dashboard/test_dashboard.py +134 -0
- package/repo/plugins/github/github.py +261 -0
- package/repo/plugins/github/herdr-plugin.toml +14 -0
- package/repo/plugins/github/test_github.py +49 -0
- package/repo/plugins/skills/herdr-plugin.toml +11 -0
- package/repo/plugins/skills/skills.md +41 -0
- package/repo/plugins/slack-relay/connect.py +198 -0
- package/repo/plugins/slack-relay/create_channel.py +134 -0
- package/repo/plugins/slack-relay/herdr-plugin.toml +15 -0
- package/repo/plugins/slack-relay/relay.py +401 -0
- package/repo/plugins/slack-relay/slack-app-manifest.json +30 -0
- package/repo/plugins/slack-relay/test_connect.py +66 -0
- package/repo/plugins/slack-relay/test_create_channel.py +61 -0
- package/repo/plugins/slack-relay/test_relay.py +254 -0
- package/repo/plugins/swarm-creator/herdr-plugin.toml +17 -0
- package/repo/plugins/swarm-watcher/dashboard.py +333 -0
- package/repo/plugins/swarm-watcher/herdr-plugin.toml +16 -0
- package/repo/plugins/swarm-watcher/usage.py +129 -0
- package/repo/plugins/swarm-watcher/watcher.py +191 -0
- package/repo/plugins/team-template/herdr-plugin.toml +15 -0
- package/repo/plugins/team-template/setup.py +211 -0
- package/repo/plugins/team-template/test_setup.py +73 -0
- package/repo/plugins/tts/herdr-plugin.toml +15 -0
- package/repo/skills/herdr/SKILL.md +214 -0
- package/repo/skills/hivey/SKILL.md +322 -0
- package/repo/skills/hivey/scripts/handoff.py +27 -0
- package/repo/skills/hivey/scripts/new_wiki.py +143 -0
- package/repo/skills/hivey-agent-creator/SKILL.md +303 -0
- package/repo/skills/hivey-agent-creator/references/agent-claude-md.md +256 -0
- package/repo/skills/hivey-agent-creator/references/global-guidelines.md +67 -0
- package/repo/skills/hivey-agent-creator/references/reviewer-agent.md +35 -0
- package/repo/skills/hivey-agent-creator/scripts/agent_context.py +76 -0
- package/repo/skills/hivey-agent-creator/scripts/agent_gate.py +78 -0
- package/repo/skills/hivey-agent-creator/scripts/setup_agent.py +288 -0
- package/repo/skills/hivey-agy/SKILL.md +123 -0
- package/repo/skills/hivey-agy/references/gemini-prompting.md +134 -0
- package/repo/skills/hivey-agy/scripts/agy_run.py +146 -0
- package/repo/skills/hivey-codex/SKILL.md +66 -0
- package/repo/skills/hivey-context7/SKILL.md +56 -0
- package/repo/skills/hivey-create-wiki/SKILL.md +329 -0
- package/repo/skills/hivey-grok/SKILL.md +101 -0
- package/repo/skills/hivey-grok/scripts/grok_run.py +139 -0
- package/repo/skills/hivey-swarm-creator/SKILL.md +384 -0
- package/repo/skills/hivey-swarm-creator/references/agent-claude-md.md +313 -0
- package/repo/skills/hivey-swarm-creator/references/archify-report.md +24 -0
- package/repo/skills/hivey-swarm-creator/references/dashboard.md +46 -0
- package/repo/skills/hivey-swarm-creator/references/retrospective.md +23 -0
- package/repo/skills/hivey-swarm-creator/references/shared-rules.md +39 -0
- package/repo/skills/hivey-swarm-creator/references/wiki-memory.md +30 -0
- package/repo/skills/hivey-swarm-creator/scripts/setup_agent.py +76 -0
- package/repo/skills/hivey-swarm-creator/scripts/shared_rules.py +50 -0
- package/repo/skills/hivey-swarm-creator/scripts/swarm_tasks.py +171 -0
- package/repo/skills/hivey-wiki-ingest/SKILL.md +45 -0
- package/repo/skills/hivey-wiki-lint/SKILL.md +38 -0
- package/repo/skills/hivey-wiki-list/SKILL.md +46 -0
- package/repo/skills/hivey-wiki-log/SKILL.md +45 -0
- package/repo/skills/hivey-wiki-query/SKILL.md +44 -0
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Live, animated Gantt dashboard for a swarm → a self-contained HTML page.
|
|
3
|
+
|
|
4
|
+
Animated with CSS + a small inline script (works from file://, no deps): running bars
|
|
5
|
+
and the "now" line grow in real time between reloads, active tasks show moving stripes,
|
|
6
|
+
working agents pulse, blocked items glow, and the intro sweep plays only on first open
|
|
7
|
+
(the 60 s reload keeps scroll position and doesn't replay it).
|
|
8
|
+
|
|
9
|
+
Built from .swarm/agents.json (roster, launch time, budget), .swarm/tasks.json (task board)
|
|
10
|
+
and .swarm/events.jsonl (claims, status changes, agent states, alerts). No LLM, no deps —
|
|
11
|
+
the hivey.swarm-watcher addon rebuilds it every minute. Output: <launch_dir>/diagrams/dashboard-swarm-<slug>.html
|
|
12
|
+
(launch_dir from the manifest, else the root), or --out PATH.
|
|
13
|
+
|
|
14
|
+
Usage: dashboard.py <swarm_root> [--out PATH] [--open]
|
|
15
|
+
"""
|
|
16
|
+
import argparse
|
|
17
|
+
import html
|
|
18
|
+
import json
|
|
19
|
+
import subprocess
|
|
20
|
+
import time
|
|
21
|
+
from datetime import datetime
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
TASK_COLORS = {"open": "#6b7280", "in-progress": "#3b82f6", "review": "#f59e0b",
|
|
25
|
+
"blocked": "#ef4444", "approved": "#22c55e"}
|
|
26
|
+
STATE_COLORS = {"working": "#3b82f6", "idle": "#4b5563", "done": "#4b5563",
|
|
27
|
+
"blocked": "#ef4444", "gone": "#1f2937", "unknown": "#374151"}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def ts(s):
|
|
31
|
+
return datetime.strptime(s, "%Y-%m-%dT%H:%M:%S").timestamp()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def load(root):
|
|
35
|
+
sw = Path(root) / ".swarm"
|
|
36
|
+
m = json.loads((sw / "agents.json").read_text())
|
|
37
|
+
tasks = json.loads((sw / "tasks.json").read_text())["tasks"] if (sw / "tasks.json").exists() else []
|
|
38
|
+
events = []
|
|
39
|
+
if (sw / "events.jsonl").exists():
|
|
40
|
+
for line in (sw / "events.jsonl").read_text().splitlines():
|
|
41
|
+
try:
|
|
42
|
+
events.append(json.loads(line))
|
|
43
|
+
except json.JSONDecodeError:
|
|
44
|
+
pass
|
|
45
|
+
return m, tasks, events
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def segments(changes, start, now):
|
|
49
|
+
"""[(t, value)] sorted → [(t0, t1, value, live)]; the last one runs to now (live=True)."""
|
|
50
|
+
out = []
|
|
51
|
+
for i, (t, v) in enumerate(changes):
|
|
52
|
+
live = i + 1 == len(changes)
|
|
53
|
+
end = now if live else changes[i + 1][0]
|
|
54
|
+
if end > t and t >= start - 1:
|
|
55
|
+
out.append((t, end, v, live))
|
|
56
|
+
return out
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def dur(sec):
|
|
60
|
+
mins = round(sec / 60)
|
|
61
|
+
return f"{mins // 60}h {mins % 60:02d}m" if mins >= 60 else f"{mins}m"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def build(root, out=None):
|
|
65
|
+
m, tasks, events = load(root)
|
|
66
|
+
now = time.time()
|
|
67
|
+
start = m.get("launched_at") or (ts(events[0]["ts"]) if events else now - 60)
|
|
68
|
+
budget = m.get("budget_minutes")
|
|
69
|
+
end = max(now, start + budget * 60 if budget else now) + 60
|
|
70
|
+
span = max(end - start, 60)
|
|
71
|
+
|
|
72
|
+
# task status timelines + agent state timelines from the event log
|
|
73
|
+
task_changes, agent_changes = {}, {}
|
|
74
|
+
for e in events:
|
|
75
|
+
t = ts(e["ts"])
|
|
76
|
+
if e["type"] == "task_claimed":
|
|
77
|
+
task_changes.setdefault(e["task"], []).append((t, "in-progress"))
|
|
78
|
+
elif e["type"] == "task_status":
|
|
79
|
+
task_changes.setdefault(e["task"], []).append((t, e["status"]))
|
|
80
|
+
elif e["type"] == "agent_state":
|
|
81
|
+
agent_changes.setdefault(e["agent"], []).append((t, e["status"]))
|
|
82
|
+
|
|
83
|
+
# finished = every task approved; the swarm's run time ends at the last approval
|
|
84
|
+
approvals = [ts(e["ts"]) for e in events if e["type"] == "task_status" and e.get("status") == "approved"]
|
|
85
|
+
finished_at = max(approvals) if approvals and tasks and all(t["status"] == "approved" for t in tasks) else None
|
|
86
|
+
first = m.get("first_launched_at") or start
|
|
87
|
+
until = finished_at or now
|
|
88
|
+
# agent time = time each agent spent `working` (all launches, not just the latest)
|
|
89
|
+
work = {a: sum(t1 - t0 for t0, t1, st, _ in segments(sorted(agent_changes.get(a, [])), 0, until)
|
|
90
|
+
if st == "working") for a in m["agents"]}
|
|
91
|
+
total_work = sum(work.values())
|
|
92
|
+
|
|
93
|
+
last_act = {}
|
|
94
|
+
for e in events:
|
|
95
|
+
if e["type"] == "delivered":
|
|
96
|
+
continue
|
|
97
|
+
for who in {e.get("actor"), e.get("agent")} & set(m["agents"]):
|
|
98
|
+
last_act[who] = max(last_act.get(who, 0), ts(e["ts"]))
|
|
99
|
+
up = Path(root) / ".swarm" / "usage.json"
|
|
100
|
+
usage = json.loads(up.read_text()) if up.exists() else {}
|
|
101
|
+
per_tok = usage.get("per_agent", {})
|
|
102
|
+
hum = lambda n: f"{n / 1e6:.1f}M" if n >= 1e6 else f"{n / 1e3:.0f}k" if n >= 1e3 else str(n)
|
|
103
|
+
tok = lambda a: hum(per_tok[a]["total"]) + " tok" if a in per_tok else "— tok"
|
|
104
|
+
ago = lambda a: (f'<tspan class="ago" data-t="{last_act[a]:.0f}">active '
|
|
105
|
+
f'{int((now - last_act[a]) // 60)} m ago</tspan>' if a in last_act else "no activity yet")
|
|
106
|
+
|
|
107
|
+
W, LABEL, ROW, BAR = 1100, 190, 26, 16
|
|
108
|
+
x = lambda t: LABEL + (t - start) / span * (W - LABEL - 20)
|
|
109
|
+
rows, y, n = [], 40, 0
|
|
110
|
+
|
|
111
|
+
def delay(): # stagger the intro sweep
|
|
112
|
+
nonlocal n
|
|
113
|
+
n += 1
|
|
114
|
+
return f' style="--d:{n * 45}ms"'
|
|
115
|
+
|
|
116
|
+
for agent in m["agents"]:
|
|
117
|
+
info = m["agents"][agent]
|
|
118
|
+
rows.append(f'<text x="{LABEL - 8}" y="{y + 17}" class="tok" text-anchor="end">{tok(agent)}'
|
|
119
|
+
f'<title>{agent}: {per_tok.get(agent, {}).get("output", 0):,} output tokens</title></text>')
|
|
120
|
+
rows.append(f'<text x="8" y="{y + 17}" class="agent">{html.escape(agent)}</text>'
|
|
121
|
+
f'<text x="8" y="{y + 30}" class="sub">{html.escape(str(info.get("model") or ""))} · '
|
|
122
|
+
f'⏱ {dur(work[agent])} · {ago(agent)}</text>')
|
|
123
|
+
for t0, t1, st, live in segments(sorted(agent_changes.get(agent, [])), start, now):
|
|
124
|
+
lv = f' data-live="1" data-x0="{x(t0):.1f}"' if live else ""
|
|
125
|
+
rows.append(f'<rect class="strip st-{st}"{lv}{delay()} x="{x(t0):.1f}" y="{y + 4}" '
|
|
126
|
+
f'width="{max(x(t1) - x(t0), 1):.1f}" height="8" rx="2" '
|
|
127
|
+
f'fill="{STATE_COLORS.get(st, "#374151")}"><title>{agent}: {st}</title></rect>')
|
|
128
|
+
y += ROW + 10
|
|
129
|
+
for task in [t for t in tasks if t.get("owner") == agent]:
|
|
130
|
+
segs = segments(sorted(task_changes.get(task["id"], [])), start, now)
|
|
131
|
+
rows.append(f'<text x="24" y="{y + 13}" class="task">{html.escape(task["id"])} · '
|
|
132
|
+
f'{html.escape(task["title"][:22])}</text>')
|
|
133
|
+
for t0, t1, st, live in segs:
|
|
134
|
+
if st == "approved":
|
|
135
|
+
rows.append(f'<path class="diamond" d="M{x(t0):.1f},{y + 1} l7,7 l-7,7 l-7,-7z" '
|
|
136
|
+
f'fill="{TASK_COLORS["approved"]}"><title>{task["id"]} approved</title></path>')
|
|
137
|
+
break
|
|
138
|
+
lv = f' data-live="1" data-x0="{x(t0):.1f}"' if live else ""
|
|
139
|
+
geo = f'x="{x(t0):.1f}" y="{y}" width="{max(x(t1) - x(t0), 2):.1f}" height="{BAR}" rx="3"'
|
|
140
|
+
rows.append(f'<rect class="bar st-{st}"{lv}{delay()} {geo} fill="{TASK_COLORS.get(st, "#6b7280")}">'
|
|
141
|
+
f'<title>{task["id"]}: {st}</title></rect>')
|
|
142
|
+
if live and st in ("in-progress", "review"): # moving stripes on active work
|
|
143
|
+
rows.append(f'<rect class="bar"{lv}{delay()} {geo} fill="url(#stripes)" pointer-events="none"/>')
|
|
144
|
+
if not segs:
|
|
145
|
+
rows.append(f'<text x="{LABEL}" y="{y + 13}" class="sub">not started'
|
|
146
|
+
f'{" · waits on " + ",".join(task["deps"]) if task["deps"] else ""}</text>')
|
|
147
|
+
y += ROW
|
|
148
|
+
y += 8
|
|
149
|
+
unowned = [t for t in tasks if not t.get("owner") or t["owner"] not in m["agents"]]
|
|
150
|
+
for task in unowned:
|
|
151
|
+
rows.append(f'<text x="24" y="{y + 13}" class="task">{html.escape(task["id"])} · unassigned · '
|
|
152
|
+
f'{html.escape(task["title"][:40])}</text>')
|
|
153
|
+
y += ROW
|
|
154
|
+
|
|
155
|
+
# axis: ticks every 10/30/60 min depending on span
|
|
156
|
+
step = 600 if span <= 3 * 3600 else 1800 if span <= 8 * 3600 else 3600
|
|
157
|
+
ticks = "".join(f'<line x1="{x(t):.1f}" y1="28" x2="{x(t):.1f}" y2="{y}" class="grid"/>'
|
|
158
|
+
f'<text x="{x(t):.1f}" y="22" class="tick">{time.strftime("%H:%M", time.localtime(t))}</text>'
|
|
159
|
+
for t in range(int(start // step + 1) * step, int(end), step))
|
|
160
|
+
marks = f'<line id="nowline" x1="{x(now):.1f}" y1="28" x2="{x(now):.1f}" y2="{y}" class="now"/>' \
|
|
161
|
+
f'<text id="nowtext" x="{x(now) + 4:.1f}" y="36" class="nowt">now</text>'
|
|
162
|
+
if budget:
|
|
163
|
+
bx = x(start + budget * 60)
|
|
164
|
+
marks += f'<line x1="{bx:.1f}" y1="28" x2="{bx:.1f}" y2="{y}" class="budget"/>' \
|
|
165
|
+
f'<text x="{bx - 4:.1f}" y="48" class="budt" text-anchor="end">budget</text>'
|
|
166
|
+
defs = ('<defs><pattern id="stripes" width="12" height="12" patternUnits="userSpaceOnUse" '
|
|
167
|
+
'patternTransform="rotate(45)"><rect width="6" height="12" fill="rgba(255,255,255,.18)"/>'
|
|
168
|
+
'<animateTransform attributeName="patternTransform" type="translate" from="0 0" to="12 0" '
|
|
169
|
+
'additive="sum" dur="0.8s" repeatCount="indefinite"/></pattern></defs>')
|
|
170
|
+
svg = f'<svg viewBox="0 0 {W} {y + 10}" width="100%">{defs}{ticks}{marks}{"".join(rows)}</svg>'
|
|
171
|
+
|
|
172
|
+
# header stats, agent cards, recent events
|
|
173
|
+
counts = {s: sum(t["status"] == s for t in tasks) for s in TASK_COLORS}
|
|
174
|
+
used = (until - start) / 60
|
|
175
|
+
fmt = lambda t: time.strftime("%b %d %H:%M", time.localtime(t))
|
|
176
|
+
done_banner = (f'<div class="done">✅ Swarm finished in <b>{dur(finished_at - first)}</b> '
|
|
177
|
+
f'({fmt(first)} → last approval {fmt(finished_at)}) · agents worked '
|
|
178
|
+
f'<b>{dur(total_work)}</b> in total</div>' if finished_at else "")
|
|
179
|
+
last_state = {a: (sorted(c)[-1][1] if c else "unknown") for a, c in agent_changes.items()}
|
|
180
|
+
cards = "".join(
|
|
181
|
+
f'<div class="card"><b>{html.escape(a)}</b><span class="pill st-{last_state.get(a, "unknown")}" style="background:'
|
|
182
|
+
f'{STATE_COLORS.get(last_state.get(a, "unknown"), "#374151")}">{last_state.get(a, "unknown")}</span>'
|
|
183
|
+
f'<div class="sub">{html.escape(str(v.get("model") or ""))} · '
|
|
184
|
+
f'{sum(t.get("owner") == a and t["status"] == "approved" for t in tasks)}/'
|
|
185
|
+
f'{sum(t.get("owner") == a for t in tasks)} tasks approved · '
|
|
186
|
+
f'<b class="tokc">{tok(a)}</b> (out {hum(per_tok.get(a, {}).get("output", 0))}) · '
|
|
187
|
+
f'⏱ <b>{dur(work[a])}</b> working · '
|
|
188
|
+
f'{ago(a).replace("tspan", "span")}</div>'
|
|
189
|
+
f'<div class="sub">now: {html.escape(next((t["id"] + " " + t["title"][:30] for t in tasks if t.get("owner") == a and t["status"] in ("in-progress", "blocked", "review")), "—"))}</div></div>'
|
|
190
|
+
for a, v in m["agents"].items())
|
|
191
|
+
def describe(e):
|
|
192
|
+
k = e["type"]
|
|
193
|
+
if k == "task_status":
|
|
194
|
+
return f'{e["task"]} → {e["status"]}' + (f' ({e["note"]})' if e.get("note") else "")
|
|
195
|
+
if k == "task_claimed":
|
|
196
|
+
return f'claimed {e["task"]}'
|
|
197
|
+
if k == "agent_state":
|
|
198
|
+
return f'is {e["status"]}'
|
|
199
|
+
if k == "slack":
|
|
200
|
+
return f'Slack {e.get("kind", "")}: {e.get("text", "")}'
|
|
201
|
+
if k in ("check_pass", "check_fail"):
|
|
202
|
+
return f'{k.replace("_", " ")} {e["task"]}'
|
|
203
|
+
return f'{k} {e.get("why") or e.get("task") or ""}'
|
|
204
|
+
feed = "".join(
|
|
205
|
+
f'<li style="--i:{i}"><span class="sub">{e["ts"][11:16]}</span> <b>{html.escape(str(e.get("actor", "")))}</b> '
|
|
206
|
+
f'{html.escape(describe(e)[:110])}</li>'
|
|
207
|
+
for i, e in enumerate(reversed([e for e in events if e["type"] != "delivered"][-18:])))
|
|
208
|
+
parts = [("output", "#f472b6"), ("input", "#a78bfa"), ("cache_write", "#60a5fa"), ("cache_read", "#334155")]
|
|
209
|
+
who_list = sorted(per_tok, key=lambda w: -per_tok[w]["total"])
|
|
210
|
+
top = max([per_tok[w]["total"] for w in who_list] or [1]) or 1
|
|
211
|
+
bars = []
|
|
212
|
+
for i, w in enumerate(who_list):
|
|
213
|
+
u, xx, yy = per_tok[w], 150.0, 8 + i * 28
|
|
214
|
+
bars.append(f'<text x="8" y="{yy + 13}" class="agent">{html.escape(w)}</text>')
|
|
215
|
+
for k, c in parts:
|
|
216
|
+
wdt = u.get(k, 0) / top * 760
|
|
217
|
+
if wdt >= 0.5:
|
|
218
|
+
bars.append(f'<rect class="bar" style="--d:{i * 80}ms" x="{xx:.1f}" y="{yy}" width="{wdt:.1f}" '
|
|
219
|
+
f'height="16" rx="2" fill="{c}"><title>{w} {k}: {u.get(k, 0):,}</title></rect>')
|
|
220
|
+
xx += wdt
|
|
221
|
+
bars.append(f'<text x="{xx + 8:.1f}" y="{yy + 13}" class="task">{hum(u["total"])} · out {hum(u["output"])}'
|
|
222
|
+
f' · {html.escape(", ".join(x.replace("claude-", "") for x in u.get("models", [])))}</text>')
|
|
223
|
+
tok_legend = "".join(f'<span class="pill" style="background:{c}">{k.replace("_", " ")}</span>' for k, c in parts)
|
|
224
|
+
swarm_tot = usage.get("swarm_total", {})
|
|
225
|
+
tok_panel = (f'<div class="panel"><div class="sub" style="margin-bottom:6px">🔥 Tokens by agent · swarm total '
|
|
226
|
+
f'<b>{hum(swarm_tot.get("total", 0))}</b> (output {hum(swarm_tot.get("output", 0))}) · '
|
|
227
|
+
f'updated with the dashboard · {tok_legend}</div>'
|
|
228
|
+
f'<svg viewBox="0 0 1100 {len(who_list) * 28 + 12}" width="100%">{"".join(bars)}</svg></div>'
|
|
229
|
+
if who_list else "")
|
|
230
|
+
diagrams = sorted((Path(m.get("launch_dir") or root) / "diagrams").glob(f"*swarm-{m['slug']}*/*.html"),
|
|
231
|
+
key=lambda p: p.stat().st_mtime)
|
|
232
|
+
latest = f'<a href="file://{diagrams[-1]}">latest Archify diagram ↗</a>' if diagrams else "no Archify diagram yet"
|
|
233
|
+
legend = "".join(f'<span class="pill" style="background:{c}">{s}</span>' for s, c in TASK_COLORS.items())
|
|
234
|
+
|
|
235
|
+
page = f"""<!doctype html><html><head><meta charset="utf-8">
|
|
236
|
+
<title>swarm-{html.escape(m['slug'])} · dashboard</title><style>
|
|
237
|
+
body{{background:#0b1020;color:#e5e7eb;font:14px -apple-system,system-ui,sans-serif;margin:24px}}
|
|
238
|
+
h1{{font-size:20px;margin:0 0 4px}} .sub{{color:#9ca3af;font-size:12px}} .stats span{{margin-right:14px}}
|
|
239
|
+
.cards{{display:flex;flex-wrap:wrap;gap:10px;margin:14px 0}} .card{{background:#111827;border:1px solid #1f2937;border-radius:10px;padding:10px 12px;min-width:210px}}
|
|
240
|
+
.pill{{display:inline-block;border-radius:9px;padding:1px 8px;margin-left:6px;font-size:11px;color:#fff}}
|
|
241
|
+
.panel{{background:#111827;border:1px solid #1f2937;border-radius:10px;padding:12px;margin-top:12px}}
|
|
242
|
+
svg text{{fill:#e5e7eb}} .agent{{font-weight:700;font-size:13px}} .task{{font-size:11px;fill:#cbd5e1}} svg .sub{{fill:#9ca3af;font-size:10px}}
|
|
243
|
+
.tick{{font-size:10px;fill:#9ca3af;text-anchor:middle}} .grid{{stroke:#1f2937}} .now{{stroke:#f472b6;stroke-width:2}}
|
|
244
|
+
.nowt{{fill:#f472b6;font-size:10px}} .budget{{stroke:#fbbf24;stroke-dasharray:4 3}} .budt{{fill:#fbbf24;font-size:10px}}
|
|
245
|
+
ul{{list-style:none;padding:0;margin:0}}
|
|
246
|
+
.done{{margin-top:10px;padding:8px 12px;border-radius:10px;background:rgba(34,197,94,.12);border:1px solid #22c55e;color:#bbf7d0}}
|
|
247
|
+
.tok{{font-size:11px;fill:#f9a8d4;font-weight:700}} .tokc{{color:#f9a8d4}}
|
|
248
|
+
.fresh{{border-radius:9px;padding:1px 8px;color:#fff;background:#15803d}} .fresh.warn{{background:#b45309}} .fresh.stale{{background:#b91c1c;animation:pulse .8s infinite}}
|
|
249
|
+
.ago.warn{{fill:#fbbf24;color:#fbbf24}} .ago.stale{{fill:#f87171;color:#f87171;font-weight:700}}
|
|
250
|
+
/* animation */
|
|
251
|
+
.bar,.strip{{transform-box:fill-box;transform-origin:left center}}
|
|
252
|
+
.intro .bar,.intro .strip{{animation:grow .9s cubic-bezier(.2,.8,.2,1) both;animation-delay:var(--d,0ms)}}
|
|
253
|
+
.diamond{{transform-box:fill-box;transform-origin:center}} .intro .diamond{{animation:pop .5s 1s both}}
|
|
254
|
+
@keyframes grow{{from{{transform:scaleX(0)}}}}
|
|
255
|
+
@keyframes pop{{0%{{transform:scale(0)}}70%{{transform:scale(1.5)}}100%{{transform:scale(1)}}}}
|
|
256
|
+
.st-blocked{{animation:glow 1.4s ease-in-out infinite}}
|
|
257
|
+
.intro .st-blocked{{animation:grow .9s cubic-bezier(.2,.8,.2,1) both,glow 1.4s ease-in-out 1s infinite}}
|
|
258
|
+
@keyframes glow{{50%{{filter:drop-shadow(0 0 6px #ef4444);opacity:.75}}}}
|
|
259
|
+
.pill.st-working{{animation:pulse 1.6s ease-in-out infinite}} .pill.st-blocked{{animation:pulse 0.8s ease-in-out infinite}}
|
|
260
|
+
@keyframes pulse{{50%{{box-shadow:0 0 0 5px rgba(59,130,246,0);opacity:.6}}}}
|
|
261
|
+
.now{{animation:nowp 2s ease-in-out infinite}} @keyframes nowp{{50%{{opacity:.45}}}}
|
|
262
|
+
.intro li{{animation:slide .45s ease-out both;animation-delay:calc(var(--i) * 45ms + 300ms)}}
|
|
263
|
+
@keyframes slide{{from{{opacity:0;transform:translateX(-12px)}}}}
|
|
264
|
+
@media (prefers-reduced-motion:reduce){{*{{animation:none!important}}}} li{{padding:2px 0;font-size:12px}} a{{color:#93c5fd}}
|
|
265
|
+
</style></head><body>
|
|
266
|
+
<h1>🐝 swarm-{html.escape(m['slug'])}</h1>
|
|
267
|
+
<div class="sub"><span id="fresh" class="fresh" data-built="{now:.0f}">updated {time.strftime("%H:%M:%S")}</span>
|
|
268
|
+
· data rebuilt every 60 s by the relay · {latest}</div>
|
|
269
|
+
{done_banner}
|
|
270
|
+
<div class="stats" style="margin-top:10px"><span>⏱ <b id="elapsed">{round(used)}</b> min{f" / {budget} min budget ({int(used / budget * 100)}%)" if budget else ""}</span>
|
|
271
|
+
<span>🤖 agent time: <b>{dur(total_work)}</b></span>
|
|
272
|
+
{"".join(f"<span>{s}: <b>{n}</b></span>" for s, n in counts.items())}
|
|
273
|
+
<span>🔥 tokens: <b>{hum(usage.get("swarm_total", {}).get("total", 0))}</b>{f" (master {hum(per_tok['coordinator']['total'])})" if "coordinator" in per_tok else ""}</span></div>
|
|
274
|
+
<div class="cards">{cards}</div>
|
|
275
|
+
<div class="panel"><div class="sub" style="margin-bottom:6px">Gantt · top strip per agent = agent state (working / idle / blocked) · bars = tasks by status · ◆ approved {legend}</div>{svg}</div>
|
|
276
|
+
{tok_panel}
|
|
277
|
+
<div class="panel"><div class="sub" style="margin-bottom:6px">Recent events</div><ul>{feed}</ul></div>
|
|
278
|
+
<script>
|
|
279
|
+
(function(){{
|
|
280
|
+
const START={start}, SPAN={span}, W={W}, LABEL={LABEL}, FINISHED={"true" if finished_at else "false"};
|
|
281
|
+
const X=t=>LABEL+(t-START)/SPAN*(W-LABEL-20);
|
|
282
|
+
const KEY="swarm-{html.escape(m['slug'])}";
|
|
283
|
+
const headless=/HeadlessChrome/.test(navigator.userAgent); // screenshots: always the final state
|
|
284
|
+
if(!headless && location.hash!=="#nointro" && !sessionStorage.getItem(KEY+":seen")){{
|
|
285
|
+
document.body.classList.add("intro"); sessionStorage.setItem(KEY+":seen","1");
|
|
286
|
+
setTimeout(()=>document.body.classList.remove("intro"),2500); // never leave bars mid-animation
|
|
287
|
+
}}
|
|
288
|
+
const y=sessionStorage.getItem(KEY+":scroll"); if(y) window.scrollTo(0,+y);
|
|
289
|
+
addEventListener("beforeunload",()=>sessionStorage.setItem(KEY+":scroll",scrollY));
|
|
290
|
+
function tick(){{ // grow running bars + move "now" in real time between rebuilds
|
|
291
|
+
const now=Date.now()/1000, xn=X(now);
|
|
292
|
+
document.querySelectorAll("[data-live]").forEach(r=>r.setAttribute("width",Math.max(xn-parseFloat(r.dataset.x0),2).toFixed(1)));
|
|
293
|
+
const l=document.getElementById("nowline"); if(l){{l.setAttribute("x1",xn);l.setAttribute("x2",xn);}}
|
|
294
|
+
const tx=document.getElementById("nowtext"); if(tx) tx.setAttribute("x",xn+4);
|
|
295
|
+
const el=document.getElementById("elapsed"); if(el && !FINISHED) el.textContent=Math.floor((now-START)/60);
|
|
296
|
+
const f=document.getElementById("fresh"); // how old is this data?
|
|
297
|
+
if(f){{const s=Math.max(0,Math.round(now-f.dataset.built));
|
|
298
|
+
f.textContent=s<90?`updated ${{s}} s ago`:`updated ${{Math.floor(s/60)}} m ago`+(s>=300?" — stale, is the relay running?":"");
|
|
299
|
+
f.className="fresh"+(s>=300?" stale":s>=120?" warn":"");}}
|
|
300
|
+
document.querySelectorAll(".ago[data-t]").forEach(a=>{{const mnt=Math.floor((now-a.dataset.t)/60);
|
|
301
|
+
a.textContent=`active ${{mnt<1?"<1":mnt}} m ago`; a.classList.toggle("warn",mnt>=10&&mnt<30); a.classList.toggle("stale",mnt>=30);}});
|
|
302
|
+
}}
|
|
303
|
+
setInterval(tick,1000); tick();
|
|
304
|
+
setTimeout(()=>location.reload(),60000); // pick up the relay's rebuild
|
|
305
|
+
}})();
|
|
306
|
+
</script>
|
|
307
|
+
</body></html>"""
|
|
308
|
+
out = Path(out) if out else Path(m.get("launch_dir") or root) / "diagrams" / f"dashboard-swarm-{m['slug']}.html"
|
|
309
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
310
|
+
out.write_text(page)
|
|
311
|
+
return out
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def main():
|
|
315
|
+
p = argparse.ArgumentParser()
|
|
316
|
+
p.add_argument("root")
|
|
317
|
+
p.add_argument("--out")
|
|
318
|
+
p.add_argument("--open", action="store_true", help="open in Google Chrome")
|
|
319
|
+
args = p.parse_args()
|
|
320
|
+
out = build(Path(args.root).expanduser().resolve(), args.out)
|
|
321
|
+
print(out)
|
|
322
|
+
if args.open:
|
|
323
|
+
import shutil
|
|
324
|
+
if shutil.which("open"): # macOS: Chrome when installed, else the default browser
|
|
325
|
+
r = subprocess.run(["open", "-a", "Google Chrome", str(out)])
|
|
326
|
+
else:
|
|
327
|
+
r = subprocess.run(["xdg-open", str(out)])
|
|
328
|
+
if r.returncode and shutil.which("open"):
|
|
329
|
+
subprocess.run(["open", str(out)])
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
if __name__ == "__main__":
|
|
333
|
+
main()
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
id = "hivey.swarm-watcher"
|
|
2
|
+
name = "Swarm watcher"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
min_herdr_version = "0.9.0"
|
|
5
|
+
description = "Watches a swarm's workers and tells the master when one is blocked, stopped, stalled or gone, and when the time budget runs out; keeps a Gantt dashboard of the swarm"
|
|
6
|
+
platforms = ["linux", "macos"]
|
|
7
|
+
|
|
8
|
+
# Opened in a swarm's space by `hivey swarm launch … --addon hivey.swarm-watcher` (or
|
|
9
|
+
# `hivey swarm addon <swarm> hivey.swarm-watcher`) with HIVEY_SWARM_ROOT set. Alerts go to the
|
|
10
|
+
# master with `hivey msg send` (delivered when it is idle); the dashboard is
|
|
11
|
+
# <launch dir>/diagrams/dashboard-swarm-<slug>.html, opened once in the browser.
|
|
12
|
+
[[panes]]
|
|
13
|
+
id = "watcher"
|
|
14
|
+
title = "swarm watcher"
|
|
15
|
+
placement = "split"
|
|
16
|
+
command = ["sh", "-c", "exec python3 \"$HERDR_PLUGIN_ROOT/watcher.py\" \"$HIVEY_SWARM_ROOT\" --open"]
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Token usage per swarm agent, the coordinator, and the swarm total.
|
|
3
|
+
|
|
4
|
+
Herdr reports which Claude session each pane runs; every session an agent has had
|
|
5
|
+
(restarts create new ones) is remembered in <root>/.swarm/usage.json. Tokens are summed
|
|
6
|
+
from the session transcripts in ~/.claude/projects/*/<session>.jsonl (plus any sub-agent
|
|
7
|
+
transcripts in <session>/subagents/), deduplicated by message id — Claude Code logs one
|
|
8
|
+
line per streamed content block, all carrying the same usage. Reads are incremental
|
|
9
|
+
(per-file offsets), so the relay can call this every minute.
|
|
10
|
+
|
|
11
|
+
Tokens only, no $: price tables go stale; the numbers here are exact.
|
|
12
|
+
|
|
13
|
+
Usage: usage.py <swarm_root> # update usage.json and print the summary
|
|
14
|
+
"""
|
|
15
|
+
import glob
|
|
16
|
+
import json
|
|
17
|
+
import subprocess
|
|
18
|
+
import os
|
|
19
|
+
import sys
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def write_atomic(path, text):
|
|
24
|
+
"""Write text to path via a temp file, so readers never see half a file."""
|
|
25
|
+
path = Path(path)
|
|
26
|
+
tmp = path.with_name(path.name + ".tmp")
|
|
27
|
+
tmp.write_text(text)
|
|
28
|
+
os.replace(tmp, path)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
FIELDS = {"input_tokens": "input", "output_tokens": "output",
|
|
32
|
+
"cache_creation_input_tokens": "cache_write", "cache_read_input_tokens": "cache_read"}
|
|
33
|
+
PROJECTS = Path.home() / ".claude" / "projects"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def live_sessions():
|
|
37
|
+
r = subprocess.run(["hivey", "agent", "list"], capture_output=True, text=True)
|
|
38
|
+
try:
|
|
39
|
+
agents = json.loads(r.stdout)["result"]["agents"]
|
|
40
|
+
except (json.JSONDecodeError, KeyError):
|
|
41
|
+
return {}
|
|
42
|
+
return {a.get("name"): (a.get("agent_session") or {}).get("value") for a in agents if a.get("name")}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def transcripts(session_id):
|
|
46
|
+
files = glob.glob(str(PROJECTS / "*" / f"{session_id}.jsonl"))
|
|
47
|
+
files += glob.glob(str(PROJECTS / "*" / session_id / "subagents" / "*.jsonl"))
|
|
48
|
+
return files
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def scan(path, state):
|
|
52
|
+
"""Add new usage lines from `path` to `state` ({offset, last_id, totals, model})."""
|
|
53
|
+
try:
|
|
54
|
+
with open(path) as f:
|
|
55
|
+
f.seek(state.get("offset", 0))
|
|
56
|
+
while True:
|
|
57
|
+
line = f.readline()
|
|
58
|
+
if not line.endswith("\n"): # EOF, or a partial line still being written
|
|
59
|
+
break
|
|
60
|
+
state["offset"] = f.tell()
|
|
61
|
+
if '"usage"' not in line:
|
|
62
|
+
continue
|
|
63
|
+
try:
|
|
64
|
+
msg = json.loads(line).get("message") or {}
|
|
65
|
+
except json.JSONDecodeError:
|
|
66
|
+
continue
|
|
67
|
+
if not isinstance(msg, dict) or not msg.get("usage") or msg.get("id") == state.get("last_id"):
|
|
68
|
+
continue
|
|
69
|
+
state["last_id"] = msg.get("id")
|
|
70
|
+
state["model"] = msg.get("model") or state.get("model")
|
|
71
|
+
tot = state.setdefault("totals", {v: 0 for v in FIELDS.values()})
|
|
72
|
+
for k, v in FIELDS.items():
|
|
73
|
+
tot[v] += int(msg["usage"].get(k) or 0)
|
|
74
|
+
except FileNotFoundError:
|
|
75
|
+
pass
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def collect(root):
|
|
79
|
+
root = Path(root)
|
|
80
|
+
m = json.loads((root / ".swarm" / "agents.json").read_text())
|
|
81
|
+
path = root / ".swarm" / "usage.json"
|
|
82
|
+
data = json.loads(path.read_text()) if path.exists() else {"sessions": {}, "files": {}}
|
|
83
|
+
herdr_names = {info["herdr_name"]: a for a, info in m["agents"].items()}
|
|
84
|
+
herdr_names[m["coordinator"]] = "coordinator"
|
|
85
|
+
for hname, sid in live_sessions().items():
|
|
86
|
+
who = herdr_names.get(hname)
|
|
87
|
+
if who and sid and sid not in data["sessions"].setdefault(who, []):
|
|
88
|
+
data["sessions"][who].append(sid)
|
|
89
|
+
|
|
90
|
+
per = {}
|
|
91
|
+
for who, sids in data["sessions"].items():
|
|
92
|
+
tot = {v: 0 for v in FIELDS.values()}
|
|
93
|
+
models = set()
|
|
94
|
+
for sid in sids:
|
|
95
|
+
for f in transcripts(sid):
|
|
96
|
+
st = data["files"].setdefault(f, {})
|
|
97
|
+
scan(f, st)
|
|
98
|
+
for k in tot:
|
|
99
|
+
tot[k] += st.get("totals", {}).get(k, 0)
|
|
100
|
+
if st.get("model"):
|
|
101
|
+
models.add(st["model"])
|
|
102
|
+
tot["total"] = sum(tot.values())
|
|
103
|
+
tot["models"] = sorted(models)
|
|
104
|
+
tot["sessions"] = len(sids)
|
|
105
|
+
per[who] = tot
|
|
106
|
+
data["per_agent"] = per
|
|
107
|
+
swarm = {k: sum(p[k] for p in per.values()) for k in list(FIELDS.values()) + ["total"]}
|
|
108
|
+
data["swarm_total"] = swarm
|
|
109
|
+
write_atomic(path, json.dumps(data, indent=1) + "\n")
|
|
110
|
+
return data
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def human(n):
|
|
114
|
+
return f"{n / 1e6:.1f}M" if n >= 1e6 else f"{n / 1e3:.0f}k" if n >= 1e3 else str(n)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def main():
|
|
118
|
+
data = collect(Path(sys.argv[1]).expanduser().resolve())
|
|
119
|
+
for who, t in sorted(data["per_agent"].items(), key=lambda kv: -kv[1]["total"]):
|
|
120
|
+
print(f"{who:14} total {human(t['total']):>7} in {human(t['input']):>6} out {human(t['output']):>6} "
|
|
121
|
+
f"cache-w {human(t['cache_write']):>6} cache-r {human(t['cache_read']):>7} "
|
|
122
|
+
f"({', '.join(t['models']) or '?'}, {t['sessions']} session(s))")
|
|
123
|
+
s = data["swarm_total"]
|
|
124
|
+
print(f"{'SWARM TOTAL':14} total {human(s['total']):>7} in {human(s['input']):>6} out {human(s['output']):>6} "
|
|
125
|
+
f"cache-w {human(s['cache_write']):>6} cache-r {human(s['cache_read']):>7}")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
if __name__ == "__main__":
|
|
129
|
+
main()
|