@hivey/cli 0.9.63 → 0.9.65
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 +9 -4
- package/repo/skills/hivey-agent-map/scripts/agent_map.py +1 -1
- package/repo/skills/hivey-agent-map/scripts/office/office.html +32 -1
- package/repo/skills/hivey-agent-map/scripts/office/office.js +210 -39
- package/repo/skills/hivey-agent-map/scripts/office/ship.js +289 -68
- package/repo/skills/hivey-agent-map/scripts/office.py +144 -35
- package/repo/skills/hivey-agent-map/scripts/serve.py +295 -42
|
@@ -7,12 +7,21 @@ 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
|
|
14
18
|
|
|
15
|
-
While an office page is open (it polls /office/office.json),
|
|
19
|
+
While an office page is open (it polls /office/office.json), a live pass runs every minute (status,
|
|
20
|
+
context, screen; only desks whose status changed go to the model) and a full re-summary every 5 minutes.
|
|
21
|
+
The office page's ⏱ setting (POST /hv-office-settings {"every": "minute" | "5min" | "15min" | "1h" | "reload"}, saved in
|
|
22
|
+
~/.hivey/agent-map/office-settings.json) picks every minute (above), every 5 / 15 minutes or every hour (full passes only)
|
|
23
|
+
or on reload only (no clock). POST /hv-office-refresh: {} a full pass now (⟳), {"load": true} when a page
|
|
24
|
+
opens (a quick pass in minute mode, a full one otherwise), {"quick": true} a quick pass.
|
|
16
25
|
It stops after 2 hours unused. Python standard library only.
|
|
17
26
|
"""
|
|
18
27
|
from __future__ import annotations
|
|
@@ -21,6 +30,7 @@ import http.server
|
|
|
21
30
|
import json
|
|
22
31
|
import os
|
|
23
32
|
import re
|
|
33
|
+
import shlex
|
|
24
34
|
import shutil
|
|
25
35
|
import subprocess
|
|
26
36
|
import sys
|
|
@@ -30,6 +40,9 @@ import urllib.request
|
|
|
30
40
|
from pathlib import Path
|
|
31
41
|
|
|
32
42
|
STATE = Path.home() / ".hivey" / "agent-map"
|
|
43
|
+
OFFICE_SETTINGS = STATE / "office-settings.json" # {"every": "minute" | ..., "ships": {"<session>": {"x", "z"}}}
|
|
44
|
+
EVERY_MODES = ("minute", "5min", "15min", "1h", "reload")
|
|
45
|
+
FULL_EVERY = {"minute": 300, "5min": 300, "15min": 900, "1h": 3600} # seconds between full passes per mode
|
|
33
46
|
REPORTS = STATE / "reports"
|
|
34
47
|
INFO = STATE / "server.json"
|
|
35
48
|
SCRIPTS = Path(__file__).resolve().parent
|
|
@@ -37,8 +50,9 @@ PREFERRED_PORT = 42817 # unregistered and below macOS's temporary-port range, s
|
|
|
37
50
|
IDLE_SECONDS = 2 * 3600
|
|
38
51
|
PING = "/hv-ping"
|
|
39
52
|
MARK = b"hivey-agent-map"
|
|
40
|
-
VERSION = b"office-
|
|
41
|
-
OFFICE_EVERY = 300 # seconds between office refreshes while its page is open
|
|
53
|
+
VERSION = b"office-11" # bump when the server gains actions, so `ensure` replaces an older one
|
|
54
|
+
OFFICE_EVERY = 300 # seconds between full office refreshes (every terminal re-summarized) while its page is open
|
|
55
|
+
OFFICE_LIVE = 60 # seconds between live passes (status, context, screen; only changed statuses summarized)
|
|
42
56
|
OFFICE_WATCHED = 600 # the page counts as open for this long after its last poll
|
|
43
57
|
OFFICE_JSON = REPORTS / "office" / "office.json"
|
|
44
58
|
PANE = re.compile(r"^[\w-]{1,24}:[\w-]{1,24}$")
|
|
@@ -51,9 +65,40 @@ def hivey_bin() -> str | None:
|
|
|
51
65
|
return exe if exe and os.path.isfile(exe) else shutil.which("hivey")
|
|
52
66
|
|
|
53
67
|
|
|
54
|
-
def
|
|
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
|
+
|
|
89
|
+
def office_every() -> str:
|
|
90
|
+
"""The office page's refresh setting (every minute by default)."""
|
|
91
|
+
try:
|
|
92
|
+
mode = office_settings().get("every")
|
|
93
|
+
except (OSError, ValueError, AttributeError):
|
|
94
|
+
mode = None
|
|
95
|
+
return mode if mode in EVERY_MODES else "minute"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def start_office_refresh(llm: bool = True, quick: bool = False) -> None:
|
|
55
99
|
"""office.py run in the background (it holds its own lock, so overlapping starts are dropped)."""
|
|
56
|
-
cmd = [sys.executable, "-I", str(SCRIPTS / "office.py"), "run"] + ([] if llm else ["--no-llm"])
|
|
100
|
+
cmd = [sys.executable, "-I", str(SCRIPTS / "office.py"), "run"] + ([] if llm else ["--no-llm"]) \
|
|
101
|
+
+ (["--quick"] if quick else [])
|
|
57
102
|
with open(STATE / "office.log", "a") as fh:
|
|
58
103
|
subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=fh, stderr=fh, start_new_session=True)
|
|
59
104
|
|
|
@@ -67,8 +112,9 @@ def request_office_refresh(port: int) -> None:
|
|
|
67
112
|
pass
|
|
68
113
|
|
|
69
114
|
|
|
70
|
-
def client_ttys() -> list[str]:
|
|
71
|
-
"""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)."""
|
|
72
118
|
out = subprocess.run(["ps", "-axo", "pid=,tty=,command="], capture_output=True, text=True, timeout=5).stdout
|
|
73
119
|
found = []
|
|
74
120
|
for line in out.splitlines():
|
|
@@ -76,9 +122,14 @@ def client_ttys() -> list[str]:
|
|
|
76
122
|
if len(f) < 3 or f[1] in ("??", "-"):
|
|
77
123
|
continue
|
|
78
124
|
args = f[2].split()
|
|
79
|
-
if os.path.basename(args[0]) == "hivey" and (len(args) == 1 or args[1] in ("attach", "--session", "-s")
|
|
80
|
-
|
|
81
|
-
|
|
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]
|
|
82
133
|
|
|
83
134
|
|
|
84
135
|
RAISE_TERMINAL = """
|
|
@@ -122,57 +173,223 @@ end run
|
|
|
122
173
|
"""
|
|
123
174
|
|
|
124
175
|
|
|
125
|
-
|
|
126
|
-
|
|
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)
|
|
127
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 ""
|
|
128
253
|
script = {"Terminal": RAISE_TERMINAL, "iTerm": RAISE_ITERM}.get(app)
|
|
129
254
|
if script:
|
|
130
|
-
for tty in
|
|
255
|
+
for tty in mine:
|
|
131
256
|
try:
|
|
132
257
|
p = subprocess.run(["osascript", "-e", script, tty], capture_output=True, text=True, timeout=10)
|
|
133
258
|
except (OSError, subprocess.SubprocessError):
|
|
134
259
|
break
|
|
135
260
|
if p.stdout.strip() == "ok":
|
|
136
|
-
return
|
|
261
|
+
return "raised"
|
|
137
262
|
subprocess.run(["open", "-a", app], capture_output=True, timeout=10)
|
|
263
|
+
return "raised"
|
|
138
264
|
|
|
139
265
|
|
|
140
|
-
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)."""
|
|
141
268
|
try:
|
|
142
269
|
agents = json.loads(OFFICE_JSON.read_text()).get("agents", [])
|
|
143
270
|
except (OSError, ValueError):
|
|
144
271
|
return None
|
|
145
|
-
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
|
+
|
|
146
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")
|
|
147
278
|
|
|
148
|
-
|
|
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)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def live_status(exe: str, sock: str | None, pane: str) -> str | None:
|
|
149
290
|
try:
|
|
150
|
-
|
|
151
|
-
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")
|
|
152
292
|
except (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError):
|
|
153
293
|
return None
|
|
154
294
|
|
|
155
295
|
|
|
156
|
-
def
|
|
157
|
-
|
|
158
|
-
|
|
296
|
+
def waiting_in_prompt(exe: str, sock: str | None, pane: str, command: str) -> bool:
|
|
297
|
+
"""True while the command still sits typed in the agent's input box (its Enter not taken yet)."""
|
|
298
|
+
try:
|
|
299
|
+
out = hv(exe, sock, "pane", "read", pane, "--source", "recent", "--lines", "15", timeout=5).stdout
|
|
300
|
+
except (OSError, subprocess.SubprocessError):
|
|
301
|
+
return False
|
|
302
|
+
try: # the CLI answers JSON or plain text depending on the version
|
|
303
|
+
out = json.loads(out)["result"].get("text", out)
|
|
304
|
+
except (ValueError, KeyError, TypeError, AttributeError):
|
|
305
|
+
pass
|
|
306
|
+
return any(re.match(r"^[│|\s]*[>❯›]\s*" + re.escape(command) + r"\s*[│|]?\s*$", line)
|
|
307
|
+
for line in str(out).splitlines()[-10:])
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def send_command(exe: str, sock: str | None, pane: str, command: str) -> tuple[bool, str]:
|
|
311
|
+
"""Type a slash command into an agent and press Enter as its own key press, so the CLI does not take
|
|
312
|
+
text and Enter as one paste (or let its slash-command menu swallow the Enter); press Enter again
|
|
313
|
+
while the command is still waiting in the input box."""
|
|
314
|
+
p = hv(exe, sock, "pane", "send-text", pane, command)
|
|
315
|
+
if p.returncode != 0:
|
|
316
|
+
return False, (p.stderr or p.stdout).strip()[-200:] or f"{command} failed"
|
|
317
|
+
for wait in (0.5, 1.2, 1.5):
|
|
318
|
+
time.sleep(wait)
|
|
319
|
+
if wait > 0.5 and not waiting_in_prompt(exe, sock, pane, command):
|
|
320
|
+
return True, f"sent {command} and Enter"
|
|
321
|
+
p = hv(exe, sock, "pane", "send-keys", pane, "Enter")
|
|
322
|
+
if p.returncode != 0:
|
|
323
|
+
return False, (p.stderr or p.stdout).strip()[-200:] or "Enter failed"
|
|
324
|
+
time.sleep(1.5)
|
|
325
|
+
if waiting_in_prompt(exe, sock, pane, command):
|
|
326
|
+
return False, f"{command} is typed but the agent has not taken it; press Enter in its terminal"
|
|
327
|
+
return True, f"sent {command} and Enter"
|
|
328
|
+
|
|
329
|
+
|
|
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:
|
|
159
370
|
return False, "hivey not found"
|
|
160
|
-
|
|
371
|
+
desk = office_desk(desk_id)
|
|
372
|
+
pane = (desk or {}).get("pane") or ""
|
|
373
|
+
if not desk or not PANE.match(pane):
|
|
161
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"
|
|
162
380
|
if action == "focus":
|
|
163
|
-
p =
|
|
381
|
+
p = hv(exe, sock, "agent", "focus", pane)
|
|
164
382
|
if p.returncode != 0:
|
|
165
383
|
return False, (p.stderr or p.stdout).strip()[-200:] or "focus failed"
|
|
166
|
-
raise_terminal()
|
|
167
|
-
|
|
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)")
|
|
168
388
|
if action in ("compact", "clear"):
|
|
169
|
-
status = live_status(
|
|
389
|
+
status = live_status(exe, sock, pane)
|
|
170
390
|
if status in ("working", "blocked"):
|
|
171
391
|
return False, f"it is {status} now; try when it is idle"
|
|
172
|
-
|
|
173
|
-
if p.returncode != 0:
|
|
174
|
-
return False, (p.stderr or p.stdout).strip()[-200:] or f"/{action} failed"
|
|
175
|
-
return True, f"sent /{action}"
|
|
392
|
+
return send_command(exe, sock, pane, f"/{action}")
|
|
176
393
|
return False, "unknown action"
|
|
177
394
|
|
|
178
395
|
|
|
@@ -230,6 +447,7 @@ class Handler(http.server.SimpleHTTPRequestHandler):
|
|
|
230
447
|
busy = threading.Lock()
|
|
231
448
|
last_used = time.time()
|
|
232
449
|
office_polled = 0.0
|
|
450
|
+
office_full = 0.0 # last full (all re-summarized) office refresh started by this server
|
|
233
451
|
|
|
234
452
|
def __init__(self, *args, **kwargs):
|
|
235
453
|
super().__init__(*args, directory=str(REPORTS), **kwargs)
|
|
@@ -259,18 +477,48 @@ class Handler(http.server.SimpleHTTPRequestHandler):
|
|
|
259
477
|
def do_POST(self) -> None:
|
|
260
478
|
Handler.last_used = time.time()
|
|
261
479
|
port = self.server.server_address[1]
|
|
262
|
-
if self.path not in ("/hv-refresh", "/hv-office-refresh", "/hv-office-action"):
|
|
480
|
+
if self.path not in ("/hv-refresh", "/hv-office-refresh", "/hv-office-action", "/hv-office-settings"):
|
|
263
481
|
return self.answer(404, b'{"ok":false,"error":"not found"}')
|
|
264
482
|
if self.headers.get("Origin") not in (f"http://127.0.0.1:{port}", f"http://localhost:{port}"):
|
|
265
483
|
return self.answer(403, b'{"ok":false,"error":"only the agent map pages can do this"}')
|
|
266
|
-
if self.path
|
|
267
|
-
|
|
268
|
-
|
|
484
|
+
if self.path in ("/hv-office-refresh", "/hv-office-settings"):
|
|
485
|
+
try:
|
|
486
|
+
length = min(int(self.headers.get("Content-Length") or 0), 4096)
|
|
487
|
+
req = json.loads(self.rfile.read(length) or b"{}")
|
|
488
|
+
req = req if isinstance(req, dict) else {}
|
|
489
|
+
except ValueError:
|
|
490
|
+
req = {}
|
|
491
|
+
if self.path == "/hv-office-settings":
|
|
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 "ships" in req: # the ship positions you dragged on the office page
|
|
502
|
+
cur["ships"] = clean_ships(req["ships"])
|
|
503
|
+
OFFICE_SETTINGS.write_text(json.dumps(cur))
|
|
504
|
+
return self.answer(200, json.dumps({"ok": True, "every": office_every(), "space": cur.get("space"),
|
|
505
|
+
"ships": cur.get("ships", {})}).encode())
|
|
506
|
+
every = office_every()
|
|
507
|
+
# a page load: a quick pass when updating every minute, a full one otherwise; ⟳: always full
|
|
508
|
+
quick = bool(req.get("quick")) or (bool(req.get("load")) and every == "minute")
|
|
509
|
+
Handler.office_polled = time.time()
|
|
510
|
+
if not quick:
|
|
511
|
+
Handler.office_full = time.time()
|
|
512
|
+
start_office_refresh(quick=quick)
|
|
513
|
+
return self.answer(200, json.dumps({"ok": True, "started": True, "every": every,
|
|
514
|
+
"space": office_settings().get("space"),
|
|
515
|
+
"ships": clean_ships(office_settings().get("ships"))}).encode())
|
|
269
516
|
if self.path == "/hv-office-action":
|
|
270
517
|
try:
|
|
271
518
|
length = min(int(self.headers.get("Content-Length") or 0), 4096)
|
|
272
519
|
req = json.loads(self.rfile.read(length) or b"{}")
|
|
273
|
-
ok, msg = office_action(str(req.get("pane"
|
|
520
|
+
ok, msg = office_action(str(req.get("id") or req.get("pane") or ""), str(req.get("action", "")),
|
|
521
|
+
str(req.get("session") or ""))
|
|
274
522
|
except (ValueError, OSError, subprocess.SubprocessError) as e:
|
|
275
523
|
ok, msg = False, str(e)[:200]
|
|
276
524
|
return self.answer(200, json.dumps({"ok": ok, "message": msg}).encode())
|
|
@@ -306,18 +554,23 @@ def serve() -> int:
|
|
|
306
554
|
return
|
|
307
555
|
|
|
308
556
|
def office_clock() -> None:
|
|
309
|
-
"""
|
|
557
|
+
"""While an office page is open: a live pass every minute, a full re-summary every 5 minutes."""
|
|
310
558
|
while True:
|
|
311
|
-
time.sleep(
|
|
312
|
-
|
|
559
|
+
time.sleep(10)
|
|
560
|
+
every = office_every()
|
|
561
|
+
if every == "reload" or time.time() - Handler.office_polled > OFFICE_WATCHED:
|
|
313
562
|
continue
|
|
314
563
|
try:
|
|
315
564
|
age = time.time() - OFFICE_JSON.stat().st_mtime
|
|
316
565
|
except OSError:
|
|
317
566
|
age = OFFICE_EVERY
|
|
318
|
-
if
|
|
567
|
+
if time.time() - Handler.office_full >= FULL_EVERY.get(every, OFFICE_EVERY):
|
|
568
|
+
Handler.office_full = time.time()
|
|
319
569
|
start_office_refresh()
|
|
320
|
-
time.sleep(
|
|
570
|
+
time.sleep(30) # give it time to write before checking the age again
|
|
571
|
+
elif every == "minute" and age >= OFFICE_LIVE:
|
|
572
|
+
start_office_refresh(quick=True)
|
|
573
|
+
time.sleep(20)
|
|
321
574
|
|
|
322
575
|
threading.Thread(target=watchdog, daemon=True).start()
|
|
323
576
|
threading.Thread(target=office_clock, daemon=True).start()
|