@hivey/cli 0.9.64 → 0.9.66
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/native/darwin-arm64/hivey +0 -0
- package/package.json +1 -1
- package/repo/skills/hivey-agent-map/SKILL.md +3 -3
- package/repo/skills/hivey-agent-map/scripts/office/music/README.txt +14 -2
- package/repo/skills/hivey-agent-map/scripts/office/music/space_02.mp3.b64 +1 -0
- package/repo/skills/hivey-agent-map/scripts/office/music/track_01.mp3.b64 +1 -0
- package/repo/skills/hivey-agent-map/scripts/office/music/track_02.mp3.b64 +1 -0
- package/repo/skills/hivey-agent-map/scripts/office/music/track_03.mp3.b64 +1 -0
- package/repo/skills/hivey-agent-map/scripts/office/music/track_04.mp3.b64 +1 -0
- package/repo/skills/hivey-agent-map/scripts/office/music/track_05.mp3.b64 +1 -0
- package/repo/skills/hivey-agent-map/scripts/office/music/track_06.mp3.b64 +1 -0
- package/repo/skills/hivey-agent-map/scripts/office/music/track_07.mp3.b64 +1 -0
- package/repo/skills/hivey-agent-map/scripts/office/music/track_08.mp3.b64 +1 -0
- package/repo/skills/hivey-agent-map/scripts/office/office.html +67 -12
- package/repo/skills/hivey-agent-map/scripts/office/office.js +245 -36
- package/repo/skills/hivey-agent-map/scripts/office/ship.js +289 -68
- package/repo/skills/hivey-agent-map/scripts/office.py +112 -18
- package/repo/skills/hivey-agent-map/scripts/serve.py +224 -43
|
@@ -66,9 +66,22 @@ def hivey_bin() -> str | None:
|
|
|
66
66
|
return exe if exe and os.path.isfile(exe) else shutil.which("hivey")
|
|
67
67
|
|
|
68
68
|
|
|
69
|
-
|
|
69
|
+
INHERITED = ("HERDR_SOCKET_PATH", "HERDR_CLIENT_SOCKET_PATH", "HERDR_SESSION", "HERDR_PANE_ID", "HERDR_TAB_ID",
|
|
70
|
+
"HERDR_WORKSPACE_ID", "HERDR_PANE_RUNTIME_ID")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def hv_env(sock: str | None) -> dict | None:
|
|
74
|
+
"""The environment that points a hivey command at one session's server (None: inherit ours)."""
|
|
75
|
+
if not sock:
|
|
76
|
+
return None
|
|
77
|
+
env = {k: v for k, v in os.environ.items() if k not in INHERITED}
|
|
78
|
+
env["HERDR_SOCKET_PATH"] = sock
|
|
79
|
+
return env
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def sh(cmd: list[str], timeout: int = 15, sock: str | None = None) -> str:
|
|
70
83
|
try:
|
|
71
|
-
return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout
|
|
84
|
+
return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, env=hv_env(sock)).stdout
|
|
72
85
|
except (OSError, subprocess.SubprocessError):
|
|
73
86
|
return ""
|
|
74
87
|
|
|
@@ -83,11 +96,25 @@ def now_iso() -> str:
|
|
|
83
96
|
|
|
84
97
|
# ---------------------------------------------------------------- who is in the office
|
|
85
98
|
|
|
86
|
-
def
|
|
99
|
+
def hv_sessions(hv: str) -> list[dict]:
|
|
100
|
+
"""Every named hivey session: [{name, running, default, socket}] (the default one first)."""
|
|
101
|
+
try:
|
|
102
|
+
got = json.loads(sh([hv, "session", "list", "--json"]) or "{}").get("sessions") or []
|
|
103
|
+
except (ValueError, AttributeError):
|
|
104
|
+
got = []
|
|
105
|
+
out = [{"name": s.get("name") or "default", "running": bool(s.get("running")), "default": bool(s.get("default")),
|
|
106
|
+
"socket": s.get("socket_path"), "dir": s.get("session_dir")} for s in got if isinstance(s, dict)]
|
|
107
|
+
if not out: # an older hivey without sessions: the server we are attached to
|
|
108
|
+
out = [{"name": "default", "running": True, "default": True, "socket": None}]
|
|
109
|
+
out.sort(key=lambda s: (not s["default"], not s["running"], s["name"]))
|
|
110
|
+
return out
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def spaces(hv: str, sock: str | None = None) -> dict:
|
|
87
114
|
"""workspace id → {label, emoji, name, about}."""
|
|
88
115
|
out = {}
|
|
89
116
|
try:
|
|
90
|
-
data = json.loads(sh([hv, "workspace", "list"]) or "{}")
|
|
117
|
+
data = json.loads(sh([hv, "workspace", "list"], sock=sock) or "{}")
|
|
91
118
|
except ValueError:
|
|
92
119
|
return out
|
|
93
120
|
for w in data.get("result", {}).get("workspaces", []):
|
|
@@ -102,14 +129,17 @@ def spaces(hv: str) -> dict:
|
|
|
102
129
|
return out
|
|
103
130
|
|
|
104
131
|
|
|
105
|
-
def desks(hv: str) -> list[dict]:
|
|
106
|
-
"""One entry per agent you talk to; swarm workers/critics/scripts fold into their coordinator.
|
|
132
|
+
def desks(hv: str, hs: dict | None = None) -> list[dict]:
|
|
133
|
+
"""One entry per agent you talk to; swarm workers/critics/scripts fold into their coordinator.
|
|
134
|
+
hs: the hivey session to read (default: the one we are attached to)."""
|
|
135
|
+
hs = hs or {"name": "default", "default": True, "socket": None}
|
|
136
|
+
sock = hs.get("socket")
|
|
107
137
|
try:
|
|
108
|
-
data = json.loads(sh([hv, "agent", "list"]) or "{}")
|
|
138
|
+
data = json.loads(sh([hv, "agent", "list"], sock=sock) or "{}")
|
|
109
139
|
except ValueError:
|
|
110
140
|
return []
|
|
111
141
|
agents = data.get("result", {}).get("agents", [])
|
|
112
|
-
rooms = spaces(hv)
|
|
142
|
+
rooms = spaces(hv, sock)
|
|
113
143
|
team: dict[str, list] = {}
|
|
114
144
|
for a in agents:
|
|
115
145
|
tok = a.get("tokens") or {}
|
|
@@ -132,7 +162,8 @@ def desks(hv: str) -> list[dict]:
|
|
|
132
162
|
sess = a.get("agent_session") or {}
|
|
133
163
|
title = re.sub(r"^\W+\s*", "", a.get("title") or "")
|
|
134
164
|
out.append({
|
|
135
|
-
"id": a.get("pane_id")
|
|
165
|
+
"id": a.get("pane_id") if hs.get("default") else f"{hs['name']}/{a.get('pane_id')}",
|
|
166
|
+
"pane": a.get("pane_id"), "hv_session": hs["name"], "sock": sock, "workspace": ws, "space": room["name"],
|
|
136
167
|
"space_label": room["label"], "emoji": room["emoji"], "about": room["about"] if master else "",
|
|
137
168
|
"name": name, "role": "coordinator" if members else ("agent" if master else "session"),
|
|
138
169
|
"cli": CLIS.get(a.get("agent"), a.get("agent") or "?"), "cli_id": a.get("agent"),
|
|
@@ -148,11 +179,48 @@ def desks(hv: str) -> list[dict]:
|
|
|
148
179
|
return out
|
|
149
180
|
|
|
150
181
|
|
|
182
|
+
def asleep_desks(hs: dict) -> list[dict]:
|
|
183
|
+
"""The agents of a stopped hivey session, from the layout it saved (session.json): they sit powered down
|
|
184
|
+
at their desks; their context and last work still come from their session logs."""
|
|
185
|
+
try:
|
|
186
|
+
path = Path(hs.get("dir") or "") / "session.json"
|
|
187
|
+
saved = json.loads(path.read_text())
|
|
188
|
+
stopped_at = dt.datetime.fromtimestamp(path.stat().st_mtime, dt.timezone.utc).isoformat(timespec="seconds")
|
|
189
|
+
except (OSError, ValueError, TypeError):
|
|
190
|
+
return []
|
|
191
|
+
out = []
|
|
192
|
+
for w in saved.get("workspaces") or []:
|
|
193
|
+
if not isinstance(w, dict):
|
|
194
|
+
continue
|
|
195
|
+
ws, label = w.get("id", ""), w.get("custom_name") or w.get("id", "")
|
|
196
|
+
m = re.match(r"^(\W+?)\s+(.+)$", label)
|
|
197
|
+
emoji, space = (m.group(1).strip(), m.group(2)) if m else ("🐝", label)
|
|
198
|
+
panes = [(pid, p) for t in w.get("tabs") or [] for pid, p in (t.get("panes") or {}).items()
|
|
199
|
+
if isinstance(p, dict) and (p.get("agent_session") or {}).get("value")]
|
|
200
|
+
leads = [x for x in panes if not x[1].get("managed_agent_kind")] or panes[:1]
|
|
201
|
+
crew = [x for x in panes if x not in leads]
|
|
202
|
+
for n, (pid, p) in enumerate(leads, 1):
|
|
203
|
+
sess = p["agent_session"]
|
|
204
|
+
members = [{"name": c.get("agent_name") or f"pane {cid}", "role": (c.get("agent_name") or "").rsplit("-", 1)[-1] or "worker",
|
|
205
|
+
"status": "idle"} for cid, c in crew] if n == 1 else []
|
|
206
|
+
name = p.get("agent_name") or (space if len(leads) == 1 else f"{space} · session {n}")
|
|
207
|
+
pane = f"{ws}:p{pid}"
|
|
208
|
+
out.append({
|
|
209
|
+
"id": f"{hs['name']}/{pane}", "pane": pane, "hv_session": hs["name"], "sock": None, "asleep": True,
|
|
210
|
+
"stopped_at": stopped_at, "workspace": f"{hs['name']}/{ws}", "space": space, "space_label": label, "emoji": emoji, "about": "",
|
|
211
|
+
"name": name, "role": "coordinator" if members else "agent",
|
|
212
|
+
"cli": CLIS.get(sess.get("agent"), sess.get("agent") or "?"), "cli_id": sess.get("agent"),
|
|
213
|
+
"status": "idle", "cwd": short(p.get("cwd")), "folder": p.get("cwd"), "session": sess.get("value"),
|
|
214
|
+
"model_hint": "", "team": members, "team_working": 0, "focused": False, "queued": False,
|
|
215
|
+
})
|
|
216
|
+
return out
|
|
217
|
+
|
|
218
|
+
|
|
151
219
|
# ---------------------------------------------------------------- what each one shows
|
|
152
220
|
|
|
153
|
-
def screen(hv: str, pane: str) -> str:
|
|
221
|
+
def screen(hv: str, pane: str, sock: str | None = None) -> str:
|
|
154
222
|
"""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)
|
|
223
|
+
raw = sh([hv, "pane", "read", pane, "--source", "recent", "--lines", str(SCREEN_LINES)], timeout=10, sock=sock)
|
|
156
224
|
lines = []
|
|
157
225
|
for line in ANSI.sub("", raw).splitlines():
|
|
158
226
|
line = BOX.sub(" ", line).rstrip()
|
|
@@ -208,6 +276,13 @@ def session_log(path: Path | None) -> dict:
|
|
|
208
276
|
if kind == "last-prompt":
|
|
209
277
|
info["last_prompt"] = (d.get("lastPrompt") or "")[:400]
|
|
210
278
|
continue
|
|
279
|
+
if kind == "system" and d.get("subtype") == "compact_boundary":
|
|
280
|
+
# /compact (or auto-compact) shrank the context; until the next reply this is its size
|
|
281
|
+
meta = d.get("compactMetadata") if isinstance(d.get("compactMetadata"), dict) else {}
|
|
282
|
+
if meta.get("postTokens"):
|
|
283
|
+
info["context"] = int(meta["postTokens"])
|
|
284
|
+
info["compacted_at"] = d.get("timestamp")
|
|
285
|
+
continue
|
|
211
286
|
if kind == "system" and d.get("subtype") == "away_summary":
|
|
212
287
|
info["recap"] = re.sub(r"\n+DONE:.*$", "", d.get("content") or "", flags=re.S).strip()[:600]
|
|
213
288
|
continue
|
|
@@ -361,10 +436,12 @@ def clean_summary(s: dict) -> dict:
|
|
|
361
436
|
|
|
362
437
|
# ---------------------------------------------------------------- one refresh
|
|
363
438
|
|
|
364
|
-
def collect(hv: str) -> list[dict]:
|
|
365
|
-
|
|
439
|
+
def collect(hv: str, sessions: list[dict] | None = None) -> list[dict]:
|
|
440
|
+
"""Every agent of every running hivey session (one spaceship per session on the page)."""
|
|
441
|
+
people = [d for hs in (sessions or hv_sessions(hv))
|
|
442
|
+
for d in (desks(hv, hs) if hs["running"] else asleep_desks(hs))]
|
|
366
443
|
with cf.ThreadPoolExecutor(max_workers=8) as pool:
|
|
367
|
-
screens = list(pool.map(lambda d: screen(hv, d["pane"]), people))
|
|
444
|
+
screens = list(pool.map(lambda d: "" if d.get("asleep") else screen(hv, d["pane"], d.get("sock")), people))
|
|
368
445
|
for d, scr in zip(people, screens):
|
|
369
446
|
d["screen"] = scr
|
|
370
447
|
log = session_log(transcript_of(d["session"], d["cli_id"]))
|
|
@@ -379,6 +456,7 @@ def collect(hv: str) -> list[dict]:
|
|
|
379
456
|
d["log"] = log.get("log", "")
|
|
380
457
|
d["last_prompt"] = log.get("last_prompt", "")
|
|
381
458
|
d["recap"] = log.get("recap", "")
|
|
459
|
+
d["compacted_at"] = log.get("compacted_at")
|
|
382
460
|
return people
|
|
383
461
|
|
|
384
462
|
|
|
@@ -409,7 +487,8 @@ def _run(hv: str, model: str, use_llm: bool, quick: bool = False) -> int:
|
|
|
409
487
|
but whose status did not keeps its last summary (re-summarized at the next full pass), and only
|
|
410
488
|
desks whose status changed (blocked -> working, working -> done...) are sent to the model now."""
|
|
411
489
|
start = time.time()
|
|
412
|
-
|
|
490
|
+
sessions = hv_sessions(hv)
|
|
491
|
+
people = collect(hv, sessions)
|
|
413
492
|
try:
|
|
414
493
|
cache = json.loads(CACHE.read_text())
|
|
415
494
|
except (OSError, ValueError):
|
|
@@ -418,7 +497,14 @@ def _run(hv: str, model: str, use_llm: bool, quick: bool = False) -> int:
|
|
|
418
497
|
for d in people:
|
|
419
498
|
d["fp"] = fingerprint(d)
|
|
420
499
|
hit = cache.get(d["id"])
|
|
421
|
-
if
|
|
500
|
+
if d.get("asleep") and not d["log_uuid"]: # stopped, and its session log is gone: nothing to summarize
|
|
501
|
+
day = dt.datetime.fromisoformat(d["stopped_at"]).astimezone().strftime("%b %-d")
|
|
502
|
+
crew = f" with {len(d['team'])} teammates" if d["team"] else ""
|
|
503
|
+
d["summary"] = {"job": f"Session {d['hv_session']} stopped", "bubble": f"💤 Asleep since {day}{crew}. Click to start session {d['hv_session']}.",
|
|
504
|
+
"next": f"Start session {d['hv_session']} to wake it", "needs_you": "", "done": [],
|
|
505
|
+
"advice": "keep", "advice_why": "its session is stopped", "by": "stopped"}
|
|
506
|
+
d["summarized_at"] = d["stopped_at"]
|
|
507
|
+
elif hit and hit.get("fp") == d["fp"] and (hit.get("by") != "fallback" or not use_llm):
|
|
422
508
|
d["summary"] = hit["summary"]
|
|
423
509
|
d["summarized_at"] = hit.get("at")
|
|
424
510
|
elif quick and hit and hit.get("status", d["status"]) == d["status"] and hit.get("by") != "fallback":
|
|
@@ -448,6 +534,9 @@ def _run(hv: str, model: str, use_llm: bool, quick: bool = False) -> int:
|
|
|
448
534
|
s = d["summary"]
|
|
449
535
|
if d["context_pct"] >= 85 and s.get("advice") == "keep": # a model can be too gentle
|
|
450
536
|
s["advice"], s["advice_why"] = "compact", f"context at {d['context_pct']}%"
|
|
537
|
+
if d["context_pct"] < 40 and s.get("advice") == "compact": # already compacted since that summary
|
|
538
|
+
s["advice"], s["advice_why"] = "keep", f"context at {d['context_pct']}% after compacting" \
|
|
539
|
+
if d.get("compacted_at") else f"context at {d['context_pct']}%"
|
|
451
540
|
if d["status"] in ("working", "blocked") and s.get("advice") == "clear":
|
|
452
541
|
s["advice"] = "keep"
|
|
453
542
|
CACHE.write_text(json.dumps({d["id"]: stale.get(d["id"]) or {
|
|
@@ -461,7 +550,9 @@ def _run(hv: str, model: str, use_llm: bool, quick: bool = False) -> int:
|
|
|
461
550
|
d.pop(k, None)
|
|
462
551
|
order = {"blocked": 0, "working": 1, "done": 2, "idle": 3}
|
|
463
552
|
people.sort(key=lambda d: (order.get(d["status"], 4), -d["context_pct"], d["name"]))
|
|
464
|
-
counts = {k: sum(1 for d in people if d["status"] == k
|
|
553
|
+
counts = {k: sum(1 for d in people if d["status"] == k and not d.get("asleep"))
|
|
554
|
+
for k in ("working", "blocked", "done", "idle")}
|
|
555
|
+
counts["asleep"] = sum(1 for d in people if d.get("asleep"))
|
|
465
556
|
full_at = now_iso()
|
|
466
557
|
if quick: # a live pass: the last full summary pass stays the one already on the page
|
|
467
558
|
try:
|
|
@@ -471,7 +562,10 @@ def _run(hv: str, model: str, use_llm: bool, quick: bool = False) -> int:
|
|
|
471
562
|
data = {"generated": now_iso(), "kind": "quick" if quick else "full", "full_at": full_at, "seconds": round(time.time() - start, 1), "model": model if use_llm else None,
|
|
472
563
|
"summarized": len(todo) if use_llm else 0, "error": error, "refresh_every": 60,
|
|
473
564
|
"counts": counts, "agents": people,
|
|
474
|
-
"
|
|
565
|
+
"sessions": [{"name": hs["name"], "running": hs["running"], "default": hs["default"],
|
|
566
|
+
"agents": sum(1 for d in people if d["hv_session"] == hs["name"])} for hs in sessions],
|
|
567
|
+
"advice": {k: sum(1 for d in people if d["summary"].get("advice") == k and not d.get("asleep"))
|
|
568
|
+
for k in ("compact", "clear")}}
|
|
475
569
|
write(data)
|
|
476
570
|
print(f"office: {len(people)} desks, {len(todo) if use_llm else 0} summarized"
|
|
477
571
|
f"{' (' + error + ')' if error else ''} in {data['seconds']}s → {OUT / 'index.html'}")
|
|
@@ -7,7 +7,11 @@ trigger them:
|
|
|
7
7
|
|
|
8
8
|
POST /hv-refresh `agent_map.py refresh` (free: no model)
|
|
9
9
|
POST /hv-office-refresh `office.py run` in the background (the agent office, /office/)
|
|
10
|
-
POST /hv-office-action {"
|
|
10
|
+
POST /hv-office-action {"action": "session", "session": "<name>"} shows a hivey session in a terminal (a
|
|
11
|
+
new one if none shows it; `hivey session attach` starts a stopped session),
|
|
12
|
+
{"action": "stop-session", "session": "<name>"} stops a non-default session (all
|
|
13
|
+
its agents) and closes its terminal windows, or
|
|
14
|
+
{"id": "wN:p1" | "<session>/wN:p1", "action": "focus" | "compact" | "clear"} for a desk on the
|
|
11
15
|
office page: focus opens the agent's terminal in hivey (and brings the
|
|
12
16
|
terminal app forward); compact/clear type /compact or /clear into an agent
|
|
13
17
|
that is not working
|
|
@@ -26,6 +30,7 @@ import http.server
|
|
|
26
30
|
import json
|
|
27
31
|
import os
|
|
28
32
|
import re
|
|
33
|
+
import shlex
|
|
29
34
|
import shutil
|
|
30
35
|
import subprocess
|
|
31
36
|
import sys
|
|
@@ -35,7 +40,7 @@ import urllib.request
|
|
|
35
40
|
from pathlib import Path
|
|
36
41
|
|
|
37
42
|
STATE = Path.home() / ".hivey" / "agent-map"
|
|
38
|
-
OFFICE_SETTINGS = STATE / "office-settings.json" # {"every": "minute" | "
|
|
43
|
+
OFFICE_SETTINGS = STATE / "office-settings.json" # {"every": "minute" | ..., "ships": {"<session>": {"x", "z"}}}
|
|
39
44
|
EVERY_MODES = ("minute", "5min", "15min", "1h", "reload")
|
|
40
45
|
FULL_EVERY = {"minute": 300, "5min": 300, "15min": 900, "1h": 3600} # seconds between full passes per mode
|
|
41
46
|
REPORTS = STATE / "reports"
|
|
@@ -45,7 +50,7 @@ PREFERRED_PORT = 42817 # unregistered and below macOS's temporary-port range, s
|
|
|
45
50
|
IDLE_SECONDS = 2 * 3600
|
|
46
51
|
PING = "/hv-ping"
|
|
47
52
|
MARK = b"hivey-agent-map"
|
|
48
|
-
VERSION = b"office-
|
|
53
|
+
VERSION = b"office-12" # bump when the server gains actions, so `ensure` replaces an older one
|
|
49
54
|
OFFICE_EVERY = 300 # seconds between full office refreshes (every terminal re-summarized) while its page is open
|
|
50
55
|
OFFICE_LIVE = 60 # seconds between live passes (status, context, screen; only changed statuses summarized)
|
|
51
56
|
OFFICE_WATCHED = 600 # the page counts as open for this long after its last poll
|
|
@@ -60,10 +65,31 @@ def hivey_bin() -> str | None:
|
|
|
60
65
|
return exe if exe and os.path.isfile(exe) else shutil.which("hivey")
|
|
61
66
|
|
|
62
67
|
|
|
68
|
+
def office_settings() -> dict:
|
|
69
|
+
try:
|
|
70
|
+
got = json.loads(OFFICE_SETTINGS.read_text())
|
|
71
|
+
return got if isinstance(got, dict) else {}
|
|
72
|
+
except (OSError, ValueError):
|
|
73
|
+
return {}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def clean_ships(ships: object) -> dict:
|
|
77
|
+
"""{session: {x, z}} where you dragged each ship on the office page (bad entries dropped)."""
|
|
78
|
+
out = {}
|
|
79
|
+
for name, p in (ships.items() if isinstance(ships, dict) else []):
|
|
80
|
+
try:
|
|
81
|
+
x, z = float(p["x"]), float(p["z"])
|
|
82
|
+
except (TypeError, KeyError, ValueError):
|
|
83
|
+
continue
|
|
84
|
+
if SESSION_NAME.match(str(name)) and abs(x) < 1e5 and abs(z) < 1e5:
|
|
85
|
+
out[str(name)] = {"x": round(x, 2), "z": round(z, 2)}
|
|
86
|
+
return out
|
|
87
|
+
|
|
88
|
+
|
|
63
89
|
def office_every() -> str:
|
|
64
90
|
"""The office page's refresh setting (every minute by default)."""
|
|
65
91
|
try:
|
|
66
|
-
mode =
|
|
92
|
+
mode = office_settings().get("every")
|
|
67
93
|
except (OSError, ValueError, AttributeError):
|
|
68
94
|
mode = None
|
|
69
95
|
return mode if mode in EVERY_MODES else "minute"
|
|
@@ -86,8 +112,9 @@ def request_office_refresh(port: int) -> None:
|
|
|
86
112
|
pass
|
|
87
113
|
|
|
88
114
|
|
|
89
|
-
def client_ttys() -> list[str]:
|
|
90
|
-
"""ttys of running hivey clients (the TUI), newest first
|
|
115
|
+
def client_ttys(session: str | None = None, only: bool = False) -> list[str]:
|
|
116
|
+
"""ttys of running hivey clients (the TUI), newest first; those attached to `session` first
|
|
117
|
+
(only: just those)."""
|
|
91
118
|
out = subprocess.run(["ps", "-axo", "pid=,tty=,command="], capture_output=True, text=True, timeout=5).stdout
|
|
92
119
|
found = []
|
|
93
120
|
for line in out.splitlines():
|
|
@@ -95,9 +122,14 @@ def client_ttys() -> list[str]:
|
|
|
95
122
|
if len(f) < 3 or f[1] in ("??", "-"):
|
|
96
123
|
continue
|
|
97
124
|
args = f[2].split()
|
|
98
|
-
if os.path.basename(args[0]) == "hivey" and (len(args) == 1 or args[1] in ("attach", "--session", "-s")
|
|
99
|
-
|
|
100
|
-
|
|
125
|
+
if os.path.basename(args[0]) == "hivey" and (len(args) == 1 or args[1] in ("attach", "--session", "-s")
|
|
126
|
+
or args[1:3] == ["session", "attach"]):
|
|
127
|
+
named = (args[3] if args[1:3] == ["session", "attach"] and len(args) > 3 else None) \
|
|
128
|
+
or next((args[i + 1] for i in range(len(args) - 1) if args[i] in ("--session", "-s")), None) \
|
|
129
|
+
or next((a.split("=", 1)[1] for a in args if a.startswith("--session=")), None)
|
|
130
|
+
mine = (named or "default") == (session or "default")
|
|
131
|
+
found.append((mine, int(f[0]), "/dev/" + f[1]))
|
|
132
|
+
return [tty for mine, _, tty in sorted(found, reverse=True) if mine or not only]
|
|
101
133
|
|
|
102
134
|
|
|
103
135
|
RAISE_TERMINAL = """
|
|
@@ -141,42 +173,130 @@ end run
|
|
|
141
173
|
"""
|
|
142
174
|
|
|
143
175
|
|
|
144
|
-
|
|
145
|
-
|
|
176
|
+
OPEN_TERMINAL = """
|
|
177
|
+
on run argv
|
|
178
|
+
tell application "Terminal"
|
|
179
|
+
activate
|
|
180
|
+
do script (item 1 of argv)
|
|
181
|
+
end tell
|
|
182
|
+
end run
|
|
183
|
+
"""
|
|
184
|
+
OPEN_ITERM = """
|
|
185
|
+
on run argv
|
|
186
|
+
tell application "iTerm"
|
|
187
|
+
activate
|
|
188
|
+
create window with default profile command (item 1 of argv)
|
|
189
|
+
end tell
|
|
190
|
+
end run
|
|
191
|
+
"""
|
|
192
|
+
CLOSE_TERMINAL = """
|
|
193
|
+
on run argv
|
|
194
|
+
set wanted to item 1 of argv
|
|
195
|
+
tell application "Terminal"
|
|
196
|
+
repeat with w in windows
|
|
197
|
+
repeat with t in tabs of w
|
|
198
|
+
if tty of t is wanted then
|
|
199
|
+
if (count of tabs of w) is 1 then close w
|
|
200
|
+
return "ok"
|
|
201
|
+
end if
|
|
202
|
+
end repeat
|
|
203
|
+
end repeat
|
|
204
|
+
end tell
|
|
205
|
+
return "none"
|
|
206
|
+
end run
|
|
207
|
+
"""
|
|
208
|
+
CLOSE_ITERM = """
|
|
209
|
+
on run argv
|
|
210
|
+
set wanted to item 1 of argv
|
|
211
|
+
tell application "iTerm"
|
|
212
|
+
repeat with w in windows
|
|
213
|
+
repeat with t in tabs of w
|
|
214
|
+
repeat with s in sessions of t
|
|
215
|
+
if tty of s is wanted then
|
|
216
|
+
close s
|
|
217
|
+
return "ok"
|
|
218
|
+
end if
|
|
219
|
+
end repeat
|
|
220
|
+
end repeat
|
|
221
|
+
end repeat
|
|
222
|
+
end tell
|
|
223
|
+
return "none"
|
|
224
|
+
end run
|
|
225
|
+
"""
|
|
226
|
+
SESSION_NAME = re.compile(r"^[\w.-]{1,64}$")
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def open_session_terminal(session: str | None) -> bool:
|
|
230
|
+
"""A new terminal window running hivey on this session (`hivey session attach` also starts a stopped one)."""
|
|
231
|
+
exe = hivey_bin()
|
|
232
|
+
if not exe or (session and not SESSION_NAME.match(session)):
|
|
233
|
+
return False
|
|
234
|
+
cmd = shlex.quote(exe) if not session or session == "default" else \
|
|
235
|
+
f"{shlex.quote(exe)} session attach {shlex.quote(session)}"
|
|
236
|
+
cmd = f"exec {cmd}" # the window ends with hivey (when the session is stopped or you quit)
|
|
146
237
|
app = TERMINAL_APPS.get(os.environ.get("TERM_PROGRAM", ""), "Terminal")
|
|
238
|
+
script = OPEN_ITERM if app == "iTerm" else OPEN_TERMINAL
|
|
239
|
+
try:
|
|
240
|
+
p = subprocess.run(["osascript", "-e", script, cmd], capture_output=True, text=True, timeout=15)
|
|
241
|
+
except (OSError, subprocess.SubprocessError):
|
|
242
|
+
return False
|
|
243
|
+
return p.returncode == 0
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def raise_terminal(session: str | None = None) -> str:
|
|
247
|
+
"""Bring the terminal window (and tab) showing this hivey session to the front; when no terminal shows
|
|
248
|
+
it, open a new one on it. Returns "raised", "opened" or "" (nothing worked)."""
|
|
249
|
+
app = TERMINAL_APPS.get(os.environ.get("TERM_PROGRAM", ""), "Terminal")
|
|
250
|
+
mine = client_ttys(session, only=True)
|
|
251
|
+
if not mine:
|
|
252
|
+
return "opened" if open_session_terminal(session) else ""
|
|
147
253
|
script = {"Terminal": RAISE_TERMINAL, "iTerm": RAISE_ITERM}.get(app)
|
|
148
254
|
if script:
|
|
149
|
-
for tty in
|
|
255
|
+
for tty in mine:
|
|
150
256
|
try:
|
|
151
257
|
p = subprocess.run(["osascript", "-e", script, tty], capture_output=True, text=True, timeout=10)
|
|
152
258
|
except (OSError, subprocess.SubprocessError):
|
|
153
259
|
break
|
|
154
260
|
if p.stdout.strip() == "ok":
|
|
155
|
-
return
|
|
261
|
+
return "raised"
|
|
156
262
|
subprocess.run(["open", "-a", app], capture_output=True, timeout=10)
|
|
263
|
+
return "raised"
|
|
157
264
|
|
|
158
265
|
|
|
159
|
-
def office_desk(
|
|
266
|
+
def office_desk(desk_id: str) -> dict | None:
|
|
267
|
+
"""The desk on the office page with this id (pane id, or "<session>/<pane>" outside the default session)."""
|
|
160
268
|
try:
|
|
161
269
|
agents = json.loads(OFFICE_JSON.read_text()).get("agents", [])
|
|
162
270
|
except (OSError, ValueError):
|
|
163
271
|
return None
|
|
164
|
-
return next((a for a in agents if a.get("
|
|
272
|
+
return next((a for a in agents if a.get("id") == desk_id), None) \
|
|
273
|
+
or next((a for a in agents if a.get("pane") == desk_id and not a.get("sock")), None)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
INHERITED = ("HERDR_SOCKET_PATH", "HERDR_CLIENT_SOCKET_PATH", "HERDR_SESSION", "HERDR_PANE_ID", "HERDR_TAB_ID",
|
|
277
|
+
"HERDR_WORKSPACE_ID", "HERDR_PANE_RUNTIME_ID")
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def hv(exe: str, sock: str | None, *args: str, timeout: int = 10) -> subprocess.CompletedProcess:
|
|
281
|
+
"""Run a hivey command against one session's server (sock None: the one we inherited)."""
|
|
282
|
+
env = None
|
|
283
|
+
if sock:
|
|
284
|
+
env = {k: v for k, v in os.environ.items() if k not in INHERITED}
|
|
285
|
+
env["HERDR_SOCKET_PATH"] = sock
|
|
286
|
+
return subprocess.run([exe, *args], capture_output=True, text=True, timeout=timeout, env=env)
|
|
165
287
|
|
|
166
288
|
|
|
167
|
-
def live_status(
|
|
289
|
+
def live_status(exe: str, sock: str | None, pane: str) -> str | None:
|
|
168
290
|
try:
|
|
169
|
-
|
|
170
|
-
return json.loads(out)["result"]["pane"].get("agent_status")
|
|
291
|
+
return json.loads(hv(exe, sock, "pane", "get", pane, timeout=5).stdout)["result"]["pane"].get("agent_status")
|
|
171
292
|
except (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError):
|
|
172
293
|
return None
|
|
173
294
|
|
|
174
295
|
|
|
175
|
-
def waiting_in_prompt(
|
|
296
|
+
def waiting_in_prompt(exe: str, sock: str | None, pane: str, command: str) -> bool:
|
|
176
297
|
"""True while the command still sits typed in the agent's input box (its Enter not taken yet)."""
|
|
177
298
|
try:
|
|
178
|
-
out =
|
|
179
|
-
capture_output=True, text=True, timeout=5).stdout
|
|
299
|
+
out = hv(exe, sock, "pane", "read", pane, "--source", "recent", "--lines", "15", timeout=5).stdout
|
|
180
300
|
except (OSError, subprocess.SubprocessError):
|
|
181
301
|
return False
|
|
182
302
|
try: # the CLI answers JSON or plain text depending on the version
|
|
@@ -187,45 +307,89 @@ def waiting_in_prompt(hv: str, pane: str, command: str) -> bool:
|
|
|
187
307
|
for line in str(out).splitlines()[-10:])
|
|
188
308
|
|
|
189
309
|
|
|
190
|
-
def send_command(
|
|
310
|
+
def send_command(exe: str, sock: str | None, pane: str, command: str) -> tuple[bool, str]:
|
|
191
311
|
"""Type a slash command into an agent and press Enter as its own key press, so the CLI does not take
|
|
192
312
|
text and Enter as one paste (or let its slash-command menu swallow the Enter); press Enter again
|
|
193
313
|
while the command is still waiting in the input box."""
|
|
194
|
-
|
|
195
|
-
return subprocess.run([hv, "pane", *args], capture_output=True, text=True, timeout=10)
|
|
196
|
-
p = call("send-text", pane, command)
|
|
314
|
+
p = hv(exe, sock, "pane", "send-text", pane, command)
|
|
197
315
|
if p.returncode != 0:
|
|
198
316
|
return False, (p.stderr or p.stdout).strip()[-200:] or f"{command} failed"
|
|
199
317
|
for wait in (0.5, 1.2, 1.5):
|
|
200
318
|
time.sleep(wait)
|
|
201
|
-
if wait > 0.5 and not waiting_in_prompt(
|
|
319
|
+
if wait > 0.5 and not waiting_in_prompt(exe, sock, pane, command):
|
|
202
320
|
return True, f"sent {command} and Enter"
|
|
203
|
-
p =
|
|
321
|
+
p = hv(exe, sock, "pane", "send-keys", pane, "Enter")
|
|
204
322
|
if p.returncode != 0:
|
|
205
323
|
return False, (p.stderr or p.stdout).strip()[-200:] or "Enter failed"
|
|
206
324
|
time.sleep(1.5)
|
|
207
|
-
if waiting_in_prompt(
|
|
325
|
+
if waiting_in_prompt(exe, sock, pane, command):
|
|
208
326
|
return False, f"{command} is typed but the agent has not taken it; press Enter in its terminal"
|
|
209
327
|
return True, f"sent {command} and Enter"
|
|
210
328
|
|
|
211
329
|
|
|
212
|
-
def
|
|
213
|
-
|
|
214
|
-
|
|
330
|
+
def stop_session(session: str) -> tuple[bool, str]:
|
|
331
|
+
"""Stop a (non-default) hivey session: its server and every agent in it, then close its terminal windows."""
|
|
332
|
+
exe = hivey_bin()
|
|
333
|
+
if not exe or not SESSION_NAME.match(session or ""):
|
|
334
|
+
return False, "unknown session"
|
|
335
|
+
if session == "default":
|
|
336
|
+
return False, "the default session is not stopped from here (it runs this office); quit it in hivey"
|
|
337
|
+
ttys = client_ttys(session, only=True)
|
|
338
|
+
p = subprocess.run([exe, "session", "stop", session], capture_output=True, text=True, timeout=60)
|
|
339
|
+
if p.returncode != 0:
|
|
340
|
+
return False, (p.stderr or p.stdout).strip()[-200:] or "stop failed"
|
|
341
|
+
time.sleep(1.5) # let its hivey clients exit
|
|
342
|
+
app = TERMINAL_APPS.get(os.environ.get("TERM_PROGRAM", ""), "Terminal")
|
|
343
|
+
script = {"Terminal": CLOSE_TERMINAL, "iTerm": CLOSE_ITERM}.get(app)
|
|
344
|
+
closed = 0
|
|
345
|
+
for tty in ttys if script else []:
|
|
346
|
+
try:
|
|
347
|
+
r = subprocess.run(["osascript", "-e", script, tty], capture_output=True, text=True, timeout=10)
|
|
348
|
+
closed += r.stdout.strip() == "ok"
|
|
349
|
+
except (OSError, subprocess.SubprocessError):
|
|
350
|
+
pass
|
|
351
|
+
return True, f"session {session} stopped" + (f", {closed} terminal closed" if closed else "")
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def session_action(session: str) -> tuple[bool, str]:
|
|
355
|
+
"""Click on a ship: show that hivey session in a terminal (a new one if none shows it; starts it if stopped)."""
|
|
356
|
+
if not SESSION_NAME.match(session or ""):
|
|
357
|
+
return False, "unknown session"
|
|
358
|
+
how = raise_terminal(session)
|
|
359
|
+
return (True, {"opened": f"opened session {session} in a new terminal", "raised": f"session {session} is in front"}[how]) \
|
|
360
|
+
if how else (False, f"could not open a terminal; run: hivey session attach {session}")
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def office_action(desk_id: str, action: str, session: str = "") -> tuple[bool, str]:
|
|
364
|
+
if action == "session":
|
|
365
|
+
return session_action(session)
|
|
366
|
+
if action == "stop-session":
|
|
367
|
+
return stop_session(session)
|
|
368
|
+
exe = hivey_bin()
|
|
369
|
+
if not exe:
|
|
215
370
|
return False, "hivey not found"
|
|
216
|
-
|
|
371
|
+
desk = office_desk(desk_id)
|
|
372
|
+
pane = (desk or {}).get("pane") or ""
|
|
373
|
+
if not desk or not PANE.match(pane):
|
|
217
374
|
return False, "unknown agent"
|
|
375
|
+
sock = desk.get("sock") or None
|
|
376
|
+
if desk.get("asleep"): # an agent of a stopped session: start the session (compact/clear wait until then)
|
|
377
|
+
if action == "focus":
|
|
378
|
+
return session_action(desk.get("hv_session") or "")
|
|
379
|
+
return False, f"session {desk.get('hv_session')} is stopped; open it first"
|
|
218
380
|
if action == "focus":
|
|
219
|
-
p =
|
|
381
|
+
p = hv(exe, sock, "agent", "focus", pane)
|
|
220
382
|
if p.returncode != 0:
|
|
221
383
|
return False, (p.stderr or p.stdout).strip()[-200:] or "focus failed"
|
|
222
|
-
raise_terminal()
|
|
223
|
-
|
|
384
|
+
how = raise_terminal(desk.get("hv_session"))
|
|
385
|
+
where = desk.get("hv_session") or "default"
|
|
386
|
+
return True, {"opened": f"opened in a new terminal on session {where}",
|
|
387
|
+
"raised": "opened in hivey"}.get(how, "focused in hivey (bring its terminal forward yourself)")
|
|
224
388
|
if action in ("compact", "clear"):
|
|
225
|
-
status = live_status(
|
|
389
|
+
status = live_status(exe, sock, pane)
|
|
226
390
|
if status in ("working", "blocked"):
|
|
227
391
|
return False, f"it is {status} now; try when it is idle"
|
|
228
|
-
return send_command(
|
|
392
|
+
return send_command(exe, sock, pane, f"/{action}")
|
|
229
393
|
return False, "unknown action"
|
|
230
394
|
|
|
231
395
|
|
|
@@ -325,10 +489,24 @@ class Handler(http.server.SimpleHTTPRequestHandler):
|
|
|
325
489
|
except ValueError:
|
|
326
490
|
req = {}
|
|
327
491
|
if self.path == "/hv-office-settings":
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
492
|
+
cur = office_settings()
|
|
493
|
+
if "every" in req:
|
|
494
|
+
if req.get("every") not in EVERY_MODES:
|
|
495
|
+
return self.answer(400, b'{"ok":false,"error":"every: minute, 5min, 15min, 1h or reload"}')
|
|
496
|
+
cur["every"] = req["every"]
|
|
497
|
+
if "space" in req: # the background: "random" (new each load) or a scene "1".."6"
|
|
498
|
+
if str(req["space"]) not in ("random", "1", "2", "3", "4", "5", "6"):
|
|
499
|
+
return self.answer(400, b'{"ok":false,"error":"space: random or 1..6"}')
|
|
500
|
+
cur["space"] = str(req["space"])
|
|
501
|
+
if "track" in req: # the music: "random" (new each load, then the next) or a track "1".."10"
|
|
502
|
+
if not re.fullmatch(r"random|[1-9]|10", str(req["track"])):
|
|
503
|
+
return self.answer(400, b'{"ok":false,"error":"track: random or 1..10"}')
|
|
504
|
+
cur["track"] = str(req["track"])
|
|
505
|
+
if "ships" in req: # the ship positions you dragged on the office page
|
|
506
|
+
cur["ships"] = clean_ships(req["ships"])
|
|
507
|
+
OFFICE_SETTINGS.write_text(json.dumps(cur))
|
|
508
|
+
return self.answer(200, json.dumps({"ok": True, "every": office_every(), "space": cur.get("space"), "track": cur.get("track"),
|
|
509
|
+
"ships": cur.get("ships", {})}).encode())
|
|
332
510
|
every = office_every()
|
|
333
511
|
# a page load: a quick pass when updating every minute, a full one otherwise; ⟳: always full
|
|
334
512
|
quick = bool(req.get("quick")) or (bool(req.get("load")) and every == "minute")
|
|
@@ -336,12 +514,15 @@ class Handler(http.server.SimpleHTTPRequestHandler):
|
|
|
336
514
|
if not quick:
|
|
337
515
|
Handler.office_full = time.time()
|
|
338
516
|
start_office_refresh(quick=quick)
|
|
339
|
-
return self.answer(200, json.dumps({"ok": True, "started": True, "every": every
|
|
517
|
+
return self.answer(200, json.dumps({"ok": True, "started": True, "every": every,
|
|
518
|
+
"space": office_settings().get("space"), "track": office_settings().get("track"),
|
|
519
|
+
"ships": clean_ships(office_settings().get("ships"))}).encode())
|
|
340
520
|
if self.path == "/hv-office-action":
|
|
341
521
|
try:
|
|
342
522
|
length = min(int(self.headers.get("Content-Length") or 0), 4096)
|
|
343
523
|
req = json.loads(self.rfile.read(length) or b"{}")
|
|
344
|
-
ok, msg = office_action(str(req.get("pane"
|
|
524
|
+
ok, msg = office_action(str(req.get("id") or req.get("pane") or ""), str(req.get("action", "")),
|
|
525
|
+
str(req.get("session") or ""))
|
|
345
526
|
except (ValueError, OSError, subprocess.SubprocessError) as e:
|
|
346
527
|
ok, msg = False, str(e)[:200]
|
|
347
528
|
return self.answer(200, json.dumps({"ok": ok, "message": msg}).encode())
|