@hivey/cli 0.9.60 → 0.9.62

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.
Files changed (60) hide show
  1. package/native/darwin-arm64/hivey +0 -0
  2. package/package.json +1 -1
  3. package/repo/skills/hivey/scripts/new_wiki.py +12 -0
  4. package/repo/skills/hivey-agent-map/SKILL.md +36 -3
  5. package/repo/skills/hivey-agent-map/scripts/agent_map.py +16 -6
  6. package/repo/skills/hivey-agent-map/scripts/office/OutlineEffect.js +539 -0
  7. package/repo/skills/hivey-agent-map/scripts/office/RoomEnvironment.js +148 -0
  8. package/repo/skills/hivey-agent-map/scripts/office/loaders/GLTFLoader.js +4663 -0
  9. package/repo/skills/hivey-agent-map/scripts/office/models/LICENSE-kenney-space-kit.txt +23 -0
  10. package/repo/skills/hivey-agent-map/scripts/office/models/LICENSE-kenney-space-station-kit.txt +28 -0
  11. package/repo/skills/hivey-agent-map/scripts/office/models/LICENSE-robot.txt +2 -0
  12. package/repo/skills/hivey-agent-map/scripts/office/models/astronautA.glb.b64 +1 -0
  13. package/repo/skills/hivey-agent-map/scripts/office/models/astronautB.glb.b64 +1 -0
  14. package/repo/skills/hivey-agent-map/scripts/office/models/barrels.glb.b64 +1 -0
  15. package/repo/skills/hivey-agent-map/scripts/office/models/barrels_rail.glb.b64 +1 -0
  16. package/repo/skills/hivey-agent-map/scripts/office/models/craft_cargoA.glb.b64 +1 -0
  17. package/repo/skills/hivey-agent-map/scripts/office/models/craft_racer.glb.b64 +1 -0
  18. package/repo/skills/hivey-agent-map/scripts/office/models/craft_speederA.glb.b64 +1 -0
  19. package/repo/skills/hivey-agent-map/scripts/office/models/desk_chairArms.glb.b64 +1 -0
  20. package/repo/skills/hivey-agent-map/scripts/office/models/desk_computer.glb.b64 +1 -0
  21. package/repo/skills/hivey-agent-map/scripts/office/models/machine_generator.glb.b64 +1 -0
  22. package/repo/skills/hivey-agent-map/scripts/office/models/machine_generatorLarge.glb.b64 +1 -0
  23. package/repo/skills/hivey-agent-map/scripts/office/models/machine_wireless.glb.b64 +1 -0
  24. package/repo/skills/hivey-agent-map/scripts/office/models/robot.glb.b64 +1 -0
  25. package/repo/skills/hivey-agent-map/scripts/office/models/satelliteDish_detailed.glb.b64 +1 -0
  26. package/repo/skills/hivey-agent-map/scripts/office/models/satelliteDish_large.glb.b64 +1 -0
  27. package/repo/skills/hivey-agent-map/scripts/office/models/station/Textures/colormap.png.b64 +1 -0
  28. package/repo/skills/hivey-agent-map/scripts/office/models/station/chair-cushion-headrest.glb.b64 +1 -0
  29. package/repo/skills/hivey-agent-map/scripts/office/models/station/computer-system.glb.b64 +1 -0
  30. package/repo/skills/hivey-agent-map/scripts/office/models/station/computer-wide.glb.b64 +1 -0
  31. package/repo/skills/hivey-agent-map/scripts/office/models/station/container-flat.glb.b64 +1 -0
  32. package/repo/skills/hivey-agent-map/scripts/office/models/station/container-tall.glb.b64 +1 -0
  33. package/repo/skills/hivey-agent-map/scripts/office/models/station/container-wide.glb.b64 +1 -0
  34. package/repo/skills/hivey-agent-map/scripts/office/models/station/display-wall-wide.glb.b64 +1 -0
  35. package/repo/skills/hivey-agent-map/scripts/office/models/station/pipe-ring-colored.glb.b64 +1 -0
  36. package/repo/skills/hivey-agent-map/scripts/office/music/README.txt +2 -0
  37. package/repo/skills/hivey-agent-map/scripts/office/music/space.mp3.b64 +1 -0
  38. package/repo/skills/hivey-agent-map/scripts/office/office.html +179 -0
  39. package/repo/skills/hivey-agent-map/scripts/office/office.js +754 -0
  40. package/repo/skills/hivey-agent-map/scripts/office/postprocessing/EffectComposer.js +231 -0
  41. package/repo/skills/hivey-agent-map/scripts/office/postprocessing/MaskPass.js +104 -0
  42. package/repo/skills/hivey-agent-map/scripts/office/postprocessing/OutputPass.js +95 -0
  43. package/repo/skills/hivey-agent-map/scripts/office/postprocessing/Pass.js +95 -0
  44. package/repo/skills/hivey-agent-map/scripts/office/postprocessing/RenderPass.js +99 -0
  45. package/repo/skills/hivey-agent-map/scripts/office/postprocessing/ShaderPass.js +77 -0
  46. package/repo/skills/hivey-agent-map/scripts/office/postprocessing/UnrealBloomPass.js +415 -0
  47. package/repo/skills/hivey-agent-map/scripts/office/shaders/CopyShader.js +45 -0
  48. package/repo/skills/hivey-agent-map/scripts/office/shaders/LuminosityHighPassShader.js +66 -0
  49. package/repo/skills/hivey-agent-map/scripts/office/shaders/OutputShader.js +81 -0
  50. package/repo/skills/hivey-agent-map/scripts/office/ship.js +578 -0
  51. package/repo/skills/hivey-agent-map/scripts/office/three.module.min.js +6 -0
  52. package/repo/skills/hivey-agent-map/scripts/office/utils/BufferGeometryUtils.js +1375 -0
  53. package/repo/skills/hivey-agent-map/scripts/office/utils/SkeletonUtils.js +413 -0
  54. package/repo/skills/hivey-agent-map/scripts/office.py +522 -0
  55. package/repo/skills/hivey-agent-map/scripts/report.py +105 -2
  56. package/repo/skills/hivey-agent-map/scripts/serve.py +190 -9
  57. package/repo/skills/hivey-create-wiki/SKILL.md +27 -2
  58. package/repo/skills/hivey-swarm-creator/SKILL.md +4 -0
  59. package/repo/skills/hivey-swarm-creator/references/wiki-memory.md +3 -0
  60. package/repo/skills/hivey-wiki-lint/SKILL.md +7 -2
@@ -0,0 +1,522 @@
1
+ """The agent office: what every live agent is doing now, drawn as a 3D office of desks.
2
+
3
+ One desk per agent you talk to in hivey: solo agents, extra sessions in a space, and each swarm's
4
+ coordinator (a swarm's workers and critics are folded into their coordinator's desk as its team).
5
+ For each desk it reads two things:
6
+
7
+ terminal `hivey pane read <pane>`: the bottom of its screen (what it is doing right now,
8
+ a permission prompt, a question for you), for any CLI (Claude Code, Codex, Grok, agy)
9
+ session log the Claude Code transcript of its session (~/.claude/projects/*/<session>.jsonl):
10
+ context size (input + cache tokens of the last reply), model, your last prompt, the
11
+ session's recap (away_summary) and its last replies
12
+
13
+ Sonnet (`claude -p --model sonnet`, no tools, no session saved) turns them into a short summary per
14
+ desk: the current job, a speech-bubble line, what it achieved, what it waits for and whether to keep,
15
+ /compact or /clear the conversation. Only desks whose terminal or log changed since the last run are
16
+ sent again, in batches, so 100 agents cost a few calls per refresh. Without a model (--no-llm, or the
17
+ call fails) the summary comes from the recap and the last prompt.
18
+
19
+ Output: ~/.hivey/agent-map/reports/office/office.json, read by office.html (Three.js, vendored), served
20
+ by serve.py, which reruns this every 5 minutes while the page is open. Python standard library only.
21
+
22
+ office.py run [--no-llm] [--model sonnet] one refresh
23
+ office.py open start the server, refresh if stale, open the page
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import base64
29
+ import concurrent.futures as cf
30
+ import datetime as dt
31
+ import glob
32
+ import hashlib
33
+ import json
34
+ import os
35
+ import re
36
+ import shutil
37
+ import subprocess
38
+ import sys
39
+ import time
40
+ from pathlib import Path
41
+
42
+ SCRIPTS = Path(__file__).resolve().parent
43
+ sys.path.insert(0, str(SCRIPTS))
44
+ import context_window # noqa: E402
45
+
46
+ HOME = Path.home()
47
+ STATE = HOME / ".hivey" / "agent-map"
48
+ OUT = STATE / "reports" / "office"
49
+ CACHE = STATE / "office-cache.json"
50
+ LOCK = STATE / "office.lock"
51
+ RUN_DIR = STATE / "office-run" # neutral cwd for the sonnet calls (no CLAUDE.md, no project)
52
+
53
+ STANDARD_WINDOW = 200_000
54
+ LARGE_WINDOW = 1_000_000
55
+ SCREEN_LINES = 70
56
+ SCREEN_CHARS = 3500
57
+ BATCH = 10
58
+ STALE_SECONDS = 240 # `open` refreshes first when the data is older than this
59
+ ANSI = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07]*(\x07|\x1b\\)")
60
+ BOX = re.compile(r"[─━│┃┌┐└┘├┤┬┴┼╭╮╯╰═║╔╗╚╝╠╣╦╩╬╌╍┄┅]+")
61
+ CLIS = {"claude": "Claude Code", "codex": "Codex", "grok": "Grok", "agy": "Antigravity", "gemini": "Antigravity"}
62
+
63
+
64
+ def hivey_bin() -> str | None:
65
+ exe = os.environ.get("HIVEY_BIN")
66
+ return exe if exe and os.path.isfile(exe) else shutil.which("hivey")
67
+
68
+
69
+ def sh(cmd: list[str], timeout: int = 15) -> str:
70
+ try:
71
+ return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout
72
+ except (OSError, subprocess.SubprocessError):
73
+ return ""
74
+
75
+
76
+ def short(path: str | None) -> str:
77
+ return (path or "").replace(str(HOME), "~", 1)
78
+
79
+
80
+ def now_iso() -> str:
81
+ return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
82
+
83
+
84
+ # ---------------------------------------------------------------- who is in the office
85
+
86
+ def spaces(hv: str) -> dict:
87
+ """workspace id → {label, emoji, name, about}."""
88
+ out = {}
89
+ try:
90
+ data = json.loads(sh([hv, "workspace", "list"]) or "{}")
91
+ except ValueError:
92
+ return out
93
+ for w in data.get("result", {}).get("workspaces", []):
94
+ label = w.get("label") or w.get("workspace_id", "")
95
+ m = re.match(r"^(\W+?)\s+(.+)$", label)
96
+ tok = w.get("tokens") or {}
97
+ about = " ".join(v.split(" ", 1)[-1].strip() for k, v in sorted(tok.items())
98
+ if k.startswith("info") and v and (v.startswith("about") or v[:1].islower() and "about" not in v
99
+ and not re.match(r"^(★|channel|running|folder|addons)\b", v)))
100
+ out[w.get("workspace_id")] = {"label": label, "emoji": m.group(1).strip() if m else "🐝",
101
+ "name": m.group(2) if m else label, "about": about.strip()[:200]}
102
+ return out
103
+
104
+
105
+ def desks(hv: str) -> list[dict]:
106
+ """One entry per agent you talk to; swarm workers/critics/scripts fold into their coordinator."""
107
+ try:
108
+ data = json.loads(sh([hv, "agent", "list"]) or "{}")
109
+ except ValueError:
110
+ return []
111
+ agents = data.get("result", {}).get("agents", [])
112
+ rooms = spaces(hv)
113
+ team: dict[str, list] = {}
114
+ for a in agents:
115
+ tok = a.get("tokens") or {}
116
+ if tok.get("swarm") and tok.get("role") not in (None, "master"):
117
+ team.setdefault(tok["swarm"], []).append({"name": a.get("name") or tok.get("role"),
118
+ "role": tok.get("role"), "status": a.get("agent_status")})
119
+ out, per_space = [], {}
120
+ for a in agents:
121
+ tok = a.get("tokens") or {}
122
+ if tok.get("swarm") and tok.get("role") not in (None, "master"):
123
+ continue
124
+ ws = a.get("workspace_id", "")
125
+ room = rooms.get(ws, {"label": ws, "emoji": "🐝", "name": ws, "about": ""})
126
+ per_space[ws] = per_space.get(ws, 0) + 1
127
+ master = tok.get("role") == "master"
128
+ name = a.get("name") or tok.get("swarm") or room["name"]
129
+ if not master:
130
+ name = f"{room['name']} · session {per_space[ws]}"
131
+ members = team.get(tok.get("swarm"), []) if master else []
132
+ sess = a.get("agent_session") or {}
133
+ title = re.sub(r"^\W+\s*", "", a.get("title") or "")
134
+ out.append({
135
+ "id": a.get("pane_id"), "pane": a.get("pane_id"), "workspace": ws, "space": room["name"],
136
+ "space_label": room["label"], "emoji": room["emoji"], "about": room["about"] if master else "",
137
+ "name": name, "role": "coordinator" if members else ("agent" if master else "session"),
138
+ "cli": CLIS.get(a.get("agent"), a.get("agent") or "?"), "cli_id": a.get("agent"),
139
+ "status": a.get("agent_status") or "unknown", "cwd": short(a.get("foreground_cwd") or a.get("cwd")),
140
+ "folder": a.get("foreground_cwd") or a.get("cwd"), "session": sess.get("value"),
141
+ "model_hint": title.rsplit("·", 1)[-1].strip() if "·" in title else "",
142
+ "team": members, "team_working": sum(1 for m in members if m["status"] == "working"),
143
+ "focused": bool(a.get("focused")), "queued": bool(tok.get("queued")),
144
+ })
145
+ for d in out: # the only desk in a space is just the space
146
+ if d["role"] == "session" and per_space.get(d["workspace"]) == 1:
147
+ d["name"] = d["space"]
148
+ return out
149
+
150
+
151
+ # ---------------------------------------------------------------- what each one shows
152
+
153
+ def screen(hv: str, pane: str) -> str:
154
+ """The bottom of the pane's terminal, cleaned for reading (no colors, no box lines, no blank runs)."""
155
+ raw = sh([hv, "pane", "read", pane, "--source", "recent", "--lines", str(SCREEN_LINES)], timeout=10)
156
+ lines = []
157
+ for line in ANSI.sub("", raw).splitlines():
158
+ line = BOX.sub(" ", line).rstrip()
159
+ line = re.sub(r"\s{3,}", " ", line)
160
+ if line.strip() or (lines and lines[-1]):
161
+ lines.append(line)
162
+ text = "\n".join(lines).strip()
163
+ return text[-SCREEN_CHARS:]
164
+
165
+
166
+ def transcript_of(session: str | None, cli: str | None) -> Path | None:
167
+ if not session or cli != "claude" or not re.fullmatch(r"[\w-]{8,80}", session):
168
+ return None
169
+ hits = glob.glob(str(HOME / ".claude/projects" / "*" / f"{session}.jsonl"))
170
+ return Path(max(hits, key=os.path.getmtime)) if hits else None
171
+
172
+
173
+ def text_of(content) -> str:
174
+ if isinstance(content, str):
175
+ return content
176
+ if isinstance(content, list):
177
+ return "\n".join(c.get("text", "") for c in content if isinstance(c, dict) and c.get("type") == "text")
178
+ return ""
179
+
180
+
181
+ def tool_line(c: dict) -> str:
182
+ inp = c.get("input") or {}
183
+ arg = inp.get("description") or inp.get("command") or inp.get("file_path") or inp.get("pattern") \
184
+ or inp.get("prompt") or inp.get("url") or ""
185
+ return f"{c.get('name')}: {str(arg)[:110]}"
186
+
187
+
188
+ def session_log(path: Path | None) -> dict:
189
+ """Context size, model, last prompt, recap, last replies and tools from the tail of a transcript."""
190
+ if not path:
191
+ return {}
192
+ try:
193
+ size = path.stat().st_size
194
+ with open(path, "rb") as fh:
195
+ fh.seek(max(0, size - 1_500_000))
196
+ tail = fh.read().decode("utf-8", "replace").splitlines()[1:]
197
+ except OSError:
198
+ return {}
199
+ info = {"log": short(str(path)), "context": 0, "model": "", "last_prompt": "", "recap": "", "replies": [],
200
+ "tools": [], "prompts": [], "last_activity": None, "started": None, "uuid": ""}
201
+ for line in tail:
202
+ try:
203
+ d = json.loads(line)
204
+ except ValueError:
205
+ continue
206
+ kind = d.get("type")
207
+ ts = d.get("timestamp")
208
+ if kind == "last-prompt":
209
+ info["last_prompt"] = (d.get("lastPrompt") or "")[:400]
210
+ continue
211
+ if kind == "system" and d.get("subtype") == "away_summary":
212
+ info["recap"] = re.sub(r"\n+DONE:.*$", "", d.get("content") or "", flags=re.S).strip()[:600]
213
+ continue
214
+ msg = d.get("message") or {}
215
+ if kind == "assistant":
216
+ u = msg.get("usage") or {}
217
+ if u and msg.get("model") != "<synthetic>":
218
+ info["context"] = (u.get("input_tokens", 0) or 0) + (u.get("cache_read_input_tokens", 0) or 0) \
219
+ + (u.get("cache_creation_input_tokens", 0) or 0)
220
+ info["model"] = msg.get("model", "") or info["model"]
221
+ for c in msg.get("content") or []:
222
+ if not isinstance(c, dict):
223
+ continue
224
+ if c.get("type") == "text" and c.get("text", "").strip():
225
+ info["replies"].append(c["text"].strip()[:700])
226
+ elif c.get("type") == "tool_use":
227
+ info["tools"].append(tool_line(c))
228
+ elif kind == "user" and not d.get("isMeta"):
229
+ t = text_of(msg.get("content")).strip()
230
+ if t and not t.startswith("<") and "tool_result" not in t:
231
+ info["prompts"].append(t[:300])
232
+ if kind in ("assistant", "user") and ts:
233
+ info["last_activity"] = ts
234
+ info["started"] = info["started"] or ts
235
+ info["uuid"] = d.get("uuid", "")
236
+ info["replies"] = info["replies"][-4:]
237
+ info["tools"] = info["tools"][-8:]
238
+ info["prompts"] = info["prompts"][-3:]
239
+ return info
240
+
241
+
242
+ def window_for(desk: dict, ctx: int) -> int:
243
+ folder = Path(desk["folder"]) if desk.get("folder") and os.path.isdir(desk["folder"]) else None
244
+ w = LARGE_WINDOW if context_window.window(folder) == context_window.LARGE else STANDARD_WINDOW
245
+ model = (desk.get("model") or "").lower()
246
+ if "sonnet" in model or "haiku" in model:
247
+ w = STANDARD_WINDOW if ctx <= STANDARD_WINDOW else LARGE_WINDOW
248
+ return LARGE_WINDOW if ctx > w else w
249
+
250
+
251
+ # ---------------------------------------------------------------- the summaries
252
+
253
+ PROMPT = """You are the receptionist of an office of AI coding agents. For each agent below you get its
254
+ status, its terminal screen (bottom of the screen = now) and, for Claude Code agents, facts from its session
255
+ log. Write what a busy manager needs at a glance. Plain words, no jargon, no markdown.
256
+
257
+ Return ONLY a JSON array, one object per agent, same ids, with these keys:
258
+ "id": the agent id as given
259
+ "job": its current job in 3-9 words (what it is working on now, or the last thing if idle)
260
+ "bubble": one sentence it would say, first person, max 90 characters, may start with one fitting emoji
261
+ "done": up to 3 short things it achieved in this session (max 60 characters each), newest first
262
+ "next": what happens next or what it waits for, max 80 characters ("" if nothing)
263
+ "needs_you": if it waits for the human (a permission prompt, a question, a choice): what to answer, max 80
264
+ characters; otherwise ""
265
+ "advice": "keep", "compact" or "clear" for its conversation. compact = the context is large (over ~60%)
266
+ and the work continues; clear = the task is finished and the next task is unrelated or the
267
+ context is large and stale; keep otherwise. Never clear while it is working or waiting for you.
268
+ "advice_why": max 70 characters
269
+
270
+ Agents:
271
+ """
272
+
273
+
274
+ def fingerprint(desk: dict) -> str:
275
+ key = json.dumps([desk["status"], desk.get("screen", "")[-1500:], desk.get("log_uuid", "")])
276
+ return hashlib.sha1(key.encode()).hexdigest()[:16]
277
+
278
+
279
+ def brief(desk: dict) -> str:
280
+ parts = [f"### id={desk['id']} name={desk['name']} cli={desk['cli']} status={desk['status']}"
281
+ f" context={desk['context_pct']}% of {desk['window'] // 1000}k"]
282
+ if desk.get("about"):
283
+ parts.append(f"about: {desk['about']}")
284
+ if desk["team"]:
285
+ parts.append("swarm team: " + ", ".join(f"{m['name']} ({m['status']})" for m in desk["team"]))
286
+ log = desk.get("_log") or {}
287
+ if log.get("recap"):
288
+ parts.append(f"session recap: {log['recap']}")
289
+ if log.get("last_prompt"):
290
+ parts.append(f"human's last prompt: {log['last_prompt']}")
291
+ for r in log.get("replies", [])[-2:]:
292
+ parts.append(f"agent said: {r[:400]}")
293
+ if log.get("tools"):
294
+ parts.append("recent tools: " + " | ".join(log["tools"][-5:]))
295
+ parts.append("terminal (bottom = now):\n" + (desk.get("screen") or "(empty)")[-2200:])
296
+ return "\n".join(parts)
297
+
298
+
299
+ def claude_token() -> str | None:
300
+ try:
301
+ import report # the nightly's long-lived login, when one is set
302
+ RUN_DIR.mkdir(parents=True, exist_ok=True)
303
+ return report.claude_token(RUN_DIR)
304
+ except Exception: # noqa: BLE001 - the normal login is fine
305
+ return None
306
+
307
+
308
+ def ask_sonnet(batch: list[dict], model: str, token: str | None) -> list[dict]:
309
+ claude = shutil.which("claude") or str(HOME / ".local/bin/claude")
310
+ prompt = PROMPT + "\n\n".join(brief(d) for d in batch)
311
+ env = dict(os.environ)
312
+ for k in list(env):
313
+ if k.startswith(("HERDR_", "CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT")):
314
+ env.pop(k)
315
+ if token:
316
+ env["CLAUDE_CODE_OAUTH_TOKEN"] = token
317
+ RUN_DIR.mkdir(parents=True, exist_ok=True)
318
+ p = subprocess.run([claude, "-p", "--model", model, "--tools", "", "--setting-sources", "",
319
+ "--strict-mcp-config", "--no-session-persistence", "--output-format", "text"],
320
+ input=prompt, cwd=RUN_DIR, capture_output=True, text=True, timeout=240, env=env)
321
+ m = re.search(r"\[.*\]", p.stdout, re.S)
322
+ if p.returncode != 0 or not m:
323
+ raise RuntimeError((p.stderr or p.stdout).strip()[-300:] or f"exit {p.returncode}")
324
+ return [x for x in json.loads(m.group(0)) if isinstance(x, dict) and x.get("id")]
325
+
326
+
327
+ def first_sentence(text: str, limit: int) -> str:
328
+ text = re.sub(r"\s+", " ", text or "").strip()
329
+ m = re.match(r"(.+?[.!?])(\s|$)", text)
330
+ s = m.group(1) if m else text
331
+ return s if len(s) <= limit else s[: limit - 1].rstrip() + "…"
332
+
333
+
334
+ def fallback(desk: dict) -> dict:
335
+ """A summary without a model: the recap, the last prompt and the last reply."""
336
+ log = desk.get("_log") or {}
337
+ scr = desk.get("screen", "")
338
+ needs = ""
339
+ if desk["status"] == "blocked":
340
+ q = re.findall(r"(Do you want[^\n]*|[^\n]*\?\s*$)", scr, re.M)
341
+ needs = first_sentence(q[-1], 80) if q else "it is waiting for you in its terminal"
342
+ reply = log.get("replies", [""])[-1] if log.get("replies") else ""
343
+ lines = [ln.strip() for ln in scr.splitlines() if len(ln.strip()) > 20]
344
+ return {
345
+ "job": first_sentence(log.get("last_prompt") or (lines[-1] if lines else desk["name"]), 60),
346
+ "bubble": first_sentence(log.get("recap") or reply or (lines[-1] if lines else "…"), 90),
347
+ "done": [], "next": "", "needs_you": needs,
348
+ "advice": "compact" if desk["context_pct"] >= 70 and desk["status"] not in ("working", "blocked") else "keep",
349
+ "advice_why": f"context at {desk['context_pct']}%" if desk["context_pct"] >= 70 else "",
350
+ "by": "fallback",
351
+ }
352
+
353
+
354
+ def clean_summary(s: dict) -> dict:
355
+ out = {k: str(s.get(k) or "")[:limit] for k, limit in
356
+ (("job", 80), ("bubble", 110), ("next", 100), ("needs_you", 100), ("advice_why", 90))}
357
+ out["done"] = [str(x)[:80] for x in (s.get("done") or []) if x][:3]
358
+ out["advice"] = s.get("advice") if s.get("advice") in ("keep", "compact", "clear") else "keep"
359
+ return out
360
+
361
+
362
+ # ---------------------------------------------------------------- one refresh
363
+
364
+ def collect(hv: str) -> list[dict]:
365
+ people = desks(hv)
366
+ with cf.ThreadPoolExecutor(max_workers=8) as pool:
367
+ screens = list(pool.map(lambda d: screen(hv, d["pane"]), people))
368
+ for d, scr in zip(people, screens):
369
+ d["screen"] = scr
370
+ log = session_log(transcript_of(d["session"], d["cli_id"]))
371
+ d["_log"] = log
372
+ d["log_uuid"] = log.get("uuid", "")
373
+ d["model"] = log.get("model") or d["model_hint"]
374
+ d["context"] = log.get("context", 0)
375
+ d["window"] = window_for(d, d["context"])
376
+ d["context_pct"] = round(100 * d["context"] / d["window"]) if d["context"] else 0
377
+ d["last_activity"] = log.get("last_activity")
378
+ d["session_started"] = log.get("started")
379
+ d["log"] = log.get("log", "")
380
+ d["last_prompt"] = log.get("last_prompt", "")
381
+ d["recap"] = log.get("recap", "")
382
+ return people
383
+
384
+
385
+ def run(model: str = "sonnet", use_llm: bool = True) -> int:
386
+ hv = hivey_bin()
387
+ if not hv:
388
+ print("office: hivey not found", file=sys.stderr)
389
+ return 1
390
+ STATE.mkdir(parents=True, exist_ok=True)
391
+ try:
392
+ fd = os.open(LOCK, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
393
+ os.write(fd, str(os.getpid()).encode())
394
+ os.close(fd)
395
+ except FileExistsError:
396
+ if time.time() - LOCK.stat().st_mtime < 600:
397
+ print("office: a refresh is already running")
398
+ return 0
399
+ LOCK.unlink(missing_ok=True)
400
+ return run(model, use_llm)
401
+ try:
402
+ return _run(hv, model, use_llm)
403
+ finally:
404
+ LOCK.unlink(missing_ok=True)
405
+
406
+
407
+ def _run(hv: str, model: str, use_llm: bool) -> int:
408
+ start = time.time()
409
+ people = collect(hv)
410
+ try:
411
+ cache = json.loads(CACHE.read_text())
412
+ except (OSError, ValueError):
413
+ cache = {}
414
+ todo, error = [], ""
415
+ for d in people:
416
+ d["fp"] = fingerprint(d)
417
+ hit = cache.get(d["id"])
418
+ if hit and hit.get("fp") == d["fp"] and (hit.get("by") != "fallback" or not use_llm):
419
+ d["summary"] = hit["summary"]
420
+ d["summarized_at"] = hit.get("at")
421
+ else:
422
+ todo.append(d)
423
+ if todo and use_llm:
424
+ token = claude_token()
425
+ batches = [todo[i:i + BATCH] for i in range(0, len(todo), BATCH)]
426
+ with cf.ThreadPoolExecutor(max_workers=4) as pool:
427
+ futures = {pool.submit(ask_sonnet, b, model, token): b for b in batches}
428
+ for fut in cf.as_completed(futures):
429
+ try:
430
+ got = {s["id"]: s for s in fut.result()}
431
+ except Exception as e: # noqa: BLE001 - keep the page alive with the fallback
432
+ error, got = str(e)[:300], {}
433
+ for d in futures[fut]:
434
+ if d["id"] in got:
435
+ d["summary"] = {**clean_summary(got[d["id"]]), "by": model}
436
+ d["summarized_at"] = now_iso()
437
+ for d in people:
438
+ if "summary" not in d:
439
+ d["summary"] = fallback(d)
440
+ d["summarized_at"] = now_iso()
441
+ s = d["summary"]
442
+ if d["context_pct"] >= 85 and s.get("advice") == "keep": # a model can be too gentle
443
+ s["advice"], s["advice_why"] = "compact", f"context at {d['context_pct']}%"
444
+ if d["status"] in ("working", "blocked") and s.get("advice") == "clear":
445
+ s["advice"] = "keep"
446
+ CACHE.write_text(json.dumps({d["id"]: {"fp": d["fp"], "summary": d["summary"], "at": d["summarized_at"],
447
+ "by": d["summary"].get("by")} for d in people}))
448
+ for d in people:
449
+ log = d.pop("_log", {})
450
+ d["tools"] = log.get("tools", [])[-5:]
451
+ d["screen"] = "\n".join(d["screen"].splitlines()[-30:])
452
+ for k in ("folder", "model_hint", "log_uuid", "fp"):
453
+ d.pop(k, None)
454
+ order = {"blocked": 0, "working": 1, "done": 2, "idle": 3}
455
+ people.sort(key=lambda d: (order.get(d["status"], 4), -d["context_pct"], d["name"]))
456
+ counts = {k: sum(1 for d in people if d["status"] == k) for k in ("working", "blocked", "done", "idle")}
457
+ data = {"generated": now_iso(), "seconds": round(time.time() - start, 1), "model": model if use_llm else None,
458
+ "summarized": len(todo) if use_llm else 0, "error": error, "refresh_every": 300,
459
+ "counts": counts, "agents": people,
460
+ "advice": {k: sum(1 for d in people if d["summary"].get("advice") == k) for k in ("compact", "clear")}}
461
+ write(data)
462
+ print(f"office: {len(people)} desks, {len(todo) if use_llm else 0} summarized"
463
+ f"{' (' + error + ')' if error else ''} in {data['seconds']}s → {OUT / 'index.html'}")
464
+ return 0
465
+
466
+
467
+ def write(data: dict) -> None:
468
+ OUT.mkdir(parents=True, exist_ok=True)
469
+ assets = SCRIPTS / "office" # the page and its modules (Three.js, post-processing, the ship)
470
+ for src in assets.rglob("*"):
471
+ if not src.is_file() or src.name.startswith("."):
472
+ continue
473
+ rel = src.relative_to(assets)
474
+ blob = src.read_bytes()
475
+ if rel.suffix == ".b64": # binary models travel base64 (skills install text files)
476
+ rel, blob = rel.with_suffix(""), base64.b64decode(blob)
477
+ dst = OUT / ("index.html" if rel.as_posix() == "office.html" else rel)
478
+ if not dst.is_file() or dst.read_bytes() != blob:
479
+ dst.parent.mkdir(parents=True, exist_ok=True)
480
+ dst.write_bytes(blob)
481
+ tmp = OUT / "office.json.tmp"
482
+ tmp.write_text(json.dumps(data, ensure_ascii=False))
483
+ os.replace(tmp, OUT / "office.json")
484
+
485
+
486
+ def open_page(model: str) -> int:
487
+ import serve
488
+ data = OUT / "office.json"
489
+ fresh = data.is_file() and time.time() - data.stat().st_mtime < STALE_SECONDS
490
+ if not fresh:
491
+ run(model, use_llm=False) # seconds: desks and terminal lines now, summaries follow
492
+ port = serve.ensure()
493
+ if not port:
494
+ print("office: the local page server did not start (see ~/.hivey/agent-map/server.log)", file=sys.stderr)
495
+ return 1
496
+ if not fresh:
497
+ serve.request_office_refresh(port)
498
+ url = f"http://127.0.0.1:{port}/office/"
499
+ subprocess.run(["open", url], capture_output=True)
500
+ print(f"agent office: {url}")
501
+ return 0
502
+
503
+
504
+ def main(argv: list[str] | None = None) -> int:
505
+ ap = argparse.ArgumentParser(prog="office.py", description=__doc__.split("\n\n")[0])
506
+ sub = ap.add_subparsers(dest="cmd")
507
+ r = sub.add_parser("run")
508
+ r.add_argument("--no-llm", action="store_true")
509
+ r.add_argument("--model", default="sonnet")
510
+ o = sub.add_parser("open")
511
+ o.add_argument("--model", default="sonnet")
512
+ a = ap.parse_args(argv)
513
+ if a.cmd == "run":
514
+ return run(a.model, not a.no_llm)
515
+ if a.cmd == "open":
516
+ return open_page(a.model)
517
+ ap.print_help()
518
+ return 0
519
+
520
+
521
+ if __name__ == "__main__":
522
+ sys.exit(main())
@@ -418,7 +418,8 @@ already built: do not touch stats.archify.md or agent-stats.html.
418
418
  nodes[].llm_api.models in snapshot.json). People chatting with agents (interactive sessions) are on
419
419
  another page: never show their spend; drop an agent that has no automated runs and no data links,
420
420
  and keep a consumer agent (one a job feeds) without its interactive cost. Each node's sublabel holds
421
- its schedule or role, its models and its automated cost when it has one ("cron 04:15 · Grok + Sonnet ·
421
+ its schedule with its start time (a box folding several jobs shows the earliest: "cron from 00:30")
422
+ or its role, its models and its automated cost when it has one ("cron 04:15 · Grok + Sonnet ·
422
423
  $0.40"); spend is usage.agents (automated only). Keep at most 25 nodes on 5 stages x rows 0-4;
423
424
  refresh the numbers in the cards (automated spend, models in use, needs attention).
424
425
  3. Descriptions: every node in snapshot.json has a "description" (what it does). snapshot.json
@@ -565,6 +566,96 @@ def day_spec(spec: dict) -> dict:
565
566
  return {**spec, "meta": meta, "nodes": nodes, "cards": cards}
566
567
 
567
568
 
569
+ DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
570
+
571
+
572
+ def job_start(schedule: str) -> tuple[str, str] | None:
573
+ """(HH:MM, the schedule's words for one job) from a cron line or a launchd description, or None
574
+ when the job has no fixed start time (hourly, every N s, always on, at login, on demand)."""
575
+ s = (schedule or "").strip()
576
+ f = s.split()
577
+ if len(f) == 5: # cron: minute hour day-of-month month day-of-week
578
+ mm, hh = (re.split(r"[,-]", x)[0] for x in f[:2])
579
+ if not (mm.isdigit() and hh.isdigit()):
580
+ return None
581
+ t = f"{int(hh):02d}:{int(mm):02d}"
582
+ if f[4].isdigit():
583
+ return t, f"{DAYS[int(f[4]) % 7]} {t}"
584
+ if f[2].isdigit():
585
+ return t, f"day {f[2]} {t}"
586
+ return t, t
587
+ m = re.search(r"(\d\d):(\d\d)", s)
588
+ if not m:
589
+ return None
590
+ return m.group(0), re.sub(r"^daily\s+", "", s)
591
+
592
+
593
+ def start_time_labels(spec: dict, meta: dict, snap: dict) -> dict[str, list[str]]:
594
+ """Every scheduled box on the map shows when it starts. The model writes the sublabels and leaves
595
+ the time out of folded boxes ("11 trading jobs") and of agents run by jobs; the scan knows each
596
+ job's schedule, so a box without a time gets its job's time, or "from <earliest>" when it stands
597
+ for several jobs. Data stores get none. Returns {box id: sublabels to try, longest first}: when a
598
+ box is too narrow, the model names go before the cost and the errors."""
599
+ jobs = {j["id"]: j for j in snap.get("jobs") or [] if j.get("id")}
600
+ owned: dict[str, list[str]] = {}
601
+ for b in (snap.get("links_candidates") or {}).get("belongs_to") or []:
602
+ owned.setdefault(b.get("agent", ""), []).append(b.get("job", ""))
603
+ out = {}
604
+ for n in spec.get("nodes") or []:
605
+ sub = str(n.get("sublabel", ""))
606
+ if n.get("type") == "database" or re.search(r"\b\d\d:\d\d\b", sub):
607
+ continue
608
+ refs = ((meta.get("nodes") or {}).get(n.get("id")) or {}).get("refs") or []
609
+ ids = [r for r in refs if r in jobs] or [j for r in refs for j in owned.get(r, []) if j in jobs]
610
+ starts = [s for s in (job_start(jobs[j].get("schedule", "")) for j in dict.fromkeys(ids)) if s]
611
+ if not starts:
612
+ continue
613
+ when = starts[0][1] if len(starts) == 1 else "from " + min(t for t, _ in starts)
614
+ m = re.match(r"(cron|launchd|nightly|daily|weekly|\d+ jobs)\b", sub)
615
+ first = (sub[:m.end()] + " " + when + sub[m.end():]) if m else " · ".join(x for x in (when, sub) if x)
616
+ parts = [x.strip() for x in first.split("·")]
617
+ tries = [first]
618
+ while len(parts) > 1:
619
+ keep = lambda x: re.search(r"\$|error|exit|fail", x, re.I)
620
+ drop = next((i for i in range(len(parts) - 1, 0, -1) if not keep(parts[i])), len(parts) - 1)
621
+ parts.pop(drop)
622
+ tries.append(" · ".join(parts))
623
+ out[str(n.get("id"))] = tries
624
+ return out
625
+
626
+
627
+ def place_start_times(folder: Path) -> None:
628
+ """Put the start times on the map (start_time_labels) and redraw it. A box the drawing rejects as
629
+ too narrow tries its next, shorter sublabel; when nothing fits, the night's map stays as it was."""
630
+ spec_path, meta_path, snap_path = folder / "map.json", folder / "map-meta.json", folder / "snapshot.json"
631
+ try:
632
+ original = spec_path.read_text()
633
+ spec, meta, snap = json.loads(original), json.loads(meta_path.read_text()), json.loads(snap_path.read_text())
634
+ except (OSError, ValueError):
635
+ return
636
+ tries = start_time_labels(spec, meta, snap)
637
+ if not tries:
638
+ return
639
+ step = dict.fromkeys(tries, 0)
640
+ for _ in range(8):
641
+ for n in spec.get("nodes") or []:
642
+ if n.get("id") in step:
643
+ n["sublabel"] = tries[n["id"]][step[n["id"]]]
644
+ spec_path.write_text(json.dumps(spec, indent=1))
645
+ good, why = finalize(folder, "dataflow", "map.json", "agent-map.html")
646
+ if good:
647
+ log(folder, f"map start times: {len(step)} boxes")
648
+ return
649
+ bad = [i for i in re.findall(r'node "([^"]+)"', why) if i in step]
650
+ if not bad or any(step[i] + 1 >= len(tries[i]) for i in bad):
651
+ break
652
+ for i in bad:
653
+ step[i] += 1
654
+ log(folder, f"map start times did not fit ({why}); map unchanged")
655
+ spec_path.write_text(original)
656
+ finalize(folder, "dataflow", "map.json", "agent-map.html")
657
+
658
+
568
659
  def day_view(scan, folder: Path) -> None:
569
660
  try:
570
661
  ok, msg = write_day_view(scan, folder)
@@ -605,6 +696,8 @@ def nightly(scan, days: int, model: str, use_llm: bool) -> int:
605
696
  log(folder, f"map: {'ok' if good else 'FAILED ' + why}")
606
697
  else:
607
698
  log(folder, "map: ok" if (folder / "agent-map.html").is_file() else "map: none yet")
699
+ if (folder / "agent-map.html").is_file():
700
+ place_start_times(folder)
608
701
 
609
702
  try:
610
703
  import enhance
@@ -640,6 +733,7 @@ def refresh(scan, days: int, model: str) -> int:
640
733
  import sessions_page
641
734
  sessions_page.write_sessions_page(snap, folder)
642
735
  ok, msg = finalize(folder, "explainer", "stats.archify.md", "agent-stats.html")
736
+ place_start_times(folder)
643
737
  try:
644
738
  import enhance
645
739
  enhance.enhance_folder(folder, json.loads((folder / "snapshot.json").read_text()), job_state)
@@ -733,6 +827,15 @@ OFFER = STATE / "offer.json"
733
827
  def offer(hour: int, minute: int, model: str) -> int:
734
828
  """Asked once, by install.sh and `hivey update`: set up the nightly run? The answer is kept in
735
829
  offer.json so it is never asked again; with no terminal nothing is asked (asked next time)."""
830
+ if sys.platform == "darwin" and PLIST.is_file(): # nights set up with Haiku move to Sonnet, same time:
831
+ try: # Haiku did not follow the map rules well
832
+ with open(PLIST, "rb") as fh:
833
+ d = plistlib.load(fh)
834
+ if d.get("ProgramArguments", [])[-2:] == ["--model", "haiku"]:
835
+ cal = d.get("StartCalendarInterval", {})
836
+ return schedule("install", cal.get("Hour", hour), cal.get("Minute", minute), "sonnet")
837
+ except (OSError, ValueError, plistlib.InvalidFileException):
838
+ pass
736
839
  if sys.platform != "darwin" or PLIST.is_file() or OFFER.is_file() or not sys.stdin.isatty():
737
840
  return 0 # not a person at a terminal (remote or scripted update): asked next time
738
841
  try:
@@ -744,7 +847,7 @@ def offer(hour: int, minute: int, model: str) -> int:
744
847
  "\nhivey can watch this computer every night: scheduled jobs (cron, launchd), agents and\n"
745
848
  "swarms, token use and estimated cost per agent and provider, failing jobs, and how\n"
746
849
  "agents feed each other. The report opens from the hivey menu → agent map.\n"
747
- f"It runs at {hour:02}:{minute:02} with Claude {model} (a few cents a night).\n"
850
+ f"It runs at {hour:02}:{minute:02} with Claude {model} (well under a dollar a night).\n"
748
851
  "Set up the nightly agent monitoring? [Y/n] ")
749
852
  tty.flush()
750
853
  answer = tty.readline().strip().lower()