@hivey/cli 0.9.67 → 0.9.70
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/plugins/slack-relay/relay.py +70 -5
- package/repo/plugins/slack-relay/test_relay.py +43 -0
- package/repo/skills/hivey-agent-creator/SKILL.md +1 -1
- package/repo/skills/hivey-agent-creator/scripts/agent_gate.py +54 -1
- package/repo/skills/hivey-agent-creator/scripts/status_check.py +121 -0
- package/repo/skills/hivey-agent-map/SKILL.md +1 -1
- package/repo/skills/hivey-agent-map/scripts/office/office.html +8 -0
- package/repo/skills/hivey-agent-map/scripts/office/office.js +43 -0
- package/repo/skills/hivey-agent-map/scripts/office/ship.js +3 -3
- package/repo/skills/hivey-agent-map/scripts/office.py +81 -0
- package/repo/skills/hivey-agent-map/scripts/serve.py +25 -3
|
Binary file
|
package/package.json
CHANGED
|
@@ -24,6 +24,9 @@ Config: $HERDR_PLUGIN_CONFIG_DIR/config.json
|
|
|
24
24
|
{"token_command": "envsave get <id>", "mirror": "masters", "interval": 10}
|
|
25
25
|
The token comes from $SLACK_TOKEN if set, else from token_command's output.
|
|
26
26
|
Scopes needed: channels:history, chat:write (groups:history for private channels).
|
|
27
|
+
Failures Each direction fails on its own (a read error doesn't block posts). After 3 failed
|
|
28
|
+
rounds in a row the relay alerts once (desktop notification + a post in the channel,
|
|
29
|
+
when posting works), backs off up to 6× the interval, and says when it recovers.
|
|
27
30
|
State: <root>/.swarm/slack_relay_state.json (last Slack ts, bus offset, echo guards).
|
|
28
31
|
"""
|
|
29
32
|
import json
|
|
@@ -50,6 +53,8 @@ PALETTE = ["🦊", "🐙", "🦉", "🐝", "🦄", "🐬", "🦖", "🐢", "🦜
|
|
|
50
53
|
KEEP_GUARDS = 500 # echo-guard ids/timestamps remembered
|
|
51
54
|
KEEP_HELD = 500 # posts held in quiet mode
|
|
52
55
|
CATCH_UP_LINES = 40 # lines in the catch-up message; the rest are counted
|
|
56
|
+
ALERT_AFTER = 3 # failed rounds in a row before the relay alerts the user (then it backs off)
|
|
57
|
+
MAX_BACKOFF = 6 # at most interval × this between rounds while failing
|
|
53
58
|
|
|
54
59
|
|
|
55
60
|
# ---------------------------------------------------------------------------
|
|
@@ -275,14 +280,28 @@ def take_held_posts(channel):
|
|
|
275
280
|
return texts
|
|
276
281
|
|
|
277
282
|
|
|
283
|
+
def desktop_notify(text):
|
|
284
|
+
"""Best-effort macOS notification; silent elsewhere or if osascript is missing."""
|
|
285
|
+
if sys.platform != "darwin":
|
|
286
|
+
return
|
|
287
|
+
plain = re.sub(r"[*_`]", "", text).replace('"', "'")[:230]
|
|
288
|
+
try:
|
|
289
|
+
subprocess.run(["osascript", "-e", f'display notification "{plain}" with title "hivey relay"'],
|
|
290
|
+
capture_output=True, timeout=10)
|
|
291
|
+
except (OSError, subprocess.SubprocessError):
|
|
292
|
+
pass
|
|
293
|
+
|
|
294
|
+
|
|
278
295
|
def log(line):
|
|
279
296
|
print(f"{time.strftime('%H:%M:%S')} {line}", flush=True)
|
|
280
297
|
|
|
281
298
|
|
|
282
299
|
class Relay:
|
|
283
300
|
def __init__(self, root, slack, hivey, channel, scope, quiet=quiet_mode_on,
|
|
284
|
-
held_posts=take_held_posts):
|
|
301
|
+
held_posts=take_held_posts, notify=None):
|
|
285
302
|
self.root, self.slack, self.hivey = Path(root), slack, hivey
|
|
303
|
+
self.notify = notify or desktop_notify
|
|
304
|
+
self.failures, self.alerted, self.last_error = 0, False, ""
|
|
286
305
|
self.channel, self.scope = channel, scope
|
|
287
306
|
self.quiet, self.held_posts = quiet, held_posts
|
|
288
307
|
self.state_path = self.root / ".swarm" / "slack_relay_state.json"
|
|
@@ -356,10 +375,55 @@ class Relay:
|
|
|
356
375
|
log(f"bus → slack catch-up of {len(held)} held post(s)")
|
|
357
376
|
|
|
358
377
|
def step(self):
|
|
378
|
+
"""One round. The two directions fail independently: a read error (e.g. a missing
|
|
379
|
+
groups:history scope) must not stop agents' posts from reaching Slack."""
|
|
359
380
|
manifest = self.manifest()
|
|
360
|
-
|
|
361
|
-
self.bus_to_slack
|
|
381
|
+
errors = []
|
|
382
|
+
for part in (self.slack_to_bus, self.bus_to_slack):
|
|
383
|
+
try:
|
|
384
|
+
part(manifest)
|
|
385
|
+
except Exception as err: # network blips, Slack errors: keep the other direction going
|
|
386
|
+
errors.append(f"{part.__name__.replace('_', ' ')}: {err}")
|
|
362
387
|
self.save()
|
|
388
|
+
self.track(errors)
|
|
389
|
+
return errors
|
|
390
|
+
|
|
391
|
+
def track(self, errors):
|
|
392
|
+
"""Silent retry loops hid a broken relay for 30 minutes (verifier audit 2026-11-05):
|
|
393
|
+
after ALERT_AFTER failed rounds in a row, tell the user once; say when it recovers."""
|
|
394
|
+
if not errors:
|
|
395
|
+
if self.alerted:
|
|
396
|
+
self.alert(f"✅ *hivey relay → you*: #{self.slug()} works again after "
|
|
397
|
+
f"{self.failures} failed rounds.")
|
|
398
|
+
self.failures, self.alerted, self.last_error = 0, False, ""
|
|
399
|
+
return
|
|
400
|
+
self.failures += 1
|
|
401
|
+
self.last_error = errors[0]
|
|
402
|
+
for e in errors:
|
|
403
|
+
log(f"error: {e}")
|
|
404
|
+
if self.failures >= ALERT_AFTER and not self.alerted:
|
|
405
|
+
self.alerted = True
|
|
406
|
+
self.alert(f"⚠️ *hivey relay → you*: #{self.slug()} is failing ({self.failures} rounds "
|
|
407
|
+
f"in a row): {errors[0][:200]}. Messages may not reach agents or Slack until "
|
|
408
|
+
f"it's fixed. Log: the relay pane of this swarm.")
|
|
409
|
+
|
|
410
|
+
def slug(self):
|
|
411
|
+
try:
|
|
412
|
+
return self.manifest().get("slug", "?")
|
|
413
|
+
except (OSError, json.JSONDecodeError):
|
|
414
|
+
return "?"
|
|
415
|
+
|
|
416
|
+
def alert(self, text):
|
|
417
|
+
log(f"ALERT {text}")
|
|
418
|
+
self.notify(text)
|
|
419
|
+
try: # posting may still work when reading doesn't
|
|
420
|
+
self.state["posted"].append(self.slack.post(self.channel, text))
|
|
421
|
+
self.save()
|
|
422
|
+
except Exception as err:
|
|
423
|
+
log(f"alert post failed too: {err}")
|
|
424
|
+
|
|
425
|
+
def wait_seconds(self, interval):
|
|
426
|
+
return interval * min(MAX_BACKOFF, max(1, self.failures))
|
|
363
427
|
|
|
364
428
|
|
|
365
429
|
def claim(pid_path):
|
|
@@ -406,9 +470,10 @@ def main():
|
|
|
406
470
|
return
|
|
407
471
|
try:
|
|
408
472
|
relay.step()
|
|
409
|
-
except Exception as err: #
|
|
473
|
+
except Exception as err: # a bad manifest read: keep relaying
|
|
410
474
|
log(f"error: {err}")
|
|
411
|
-
|
|
475
|
+
relay.track([f"step: {err}"])
|
|
476
|
+
time.sleep(relay.wait_seconds(interval))
|
|
412
477
|
|
|
413
478
|
|
|
414
479
|
if __name__ == "__main__":
|
|
@@ -267,5 +267,48 @@ class HeldPostFiles(unittest.TestCase):
|
|
|
267
267
|
self.assertEqual(list(held.iterdir()), [])
|
|
268
268
|
|
|
269
269
|
|
|
270
|
+
|
|
271
|
+
class Failures(unittest.TestCase):
|
|
272
|
+
"""A broken read (e.g. missing groups:history) must not block posts, and must be reported."""
|
|
273
|
+
|
|
274
|
+
def test_read_failure_still_posts_alerts_once_and_recovers(self):
|
|
275
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
276
|
+
root = Path(tmp)
|
|
277
|
+
(root / ".swarm").mkdir()
|
|
278
|
+
(root / ".swarm" / "agents.json").write_text(json.dumps(MANIFEST))
|
|
279
|
+
bus = root / ".swarm" / "bus.jsonl"
|
|
280
|
+
bus.write_text("")
|
|
281
|
+
slack, hivey, notes = FakeSlack(), FakeHivey(bus), []
|
|
282
|
+
broken = {"on": True}
|
|
283
|
+
real_history = slack.history
|
|
284
|
+
|
|
285
|
+
def history(channel, oldest):
|
|
286
|
+
if broken["on"]:
|
|
287
|
+
raise RuntimeError("slack conversations.history: missing_scope")
|
|
288
|
+
return real_history(channel, oldest)
|
|
289
|
+
|
|
290
|
+
slack.history = history
|
|
291
|
+
r = relay.Relay(root, slack, hivey, "C1", "masters", quiet=lambda: False,
|
|
292
|
+
held_posts=lambda c: [], notify=notes.append)
|
|
293
|
+
r.state["last_ts"] = "0"
|
|
294
|
+
with open(bus, "a") as f:
|
|
295
|
+
f.write(json.dumps({"ev": "msg", "id": "a1", "from": "ideas/coordinator",
|
|
296
|
+
"to": "human", "swarm": "ideas", "text": "decisions"}) + "\n")
|
|
297
|
+
errors = r.step()
|
|
298
|
+
self.assertTrue(errors and "missing_scope" in errors[0])
|
|
299
|
+
self.assertEqual(len(slack.posted), 1, "the agent's post still reaches Slack")
|
|
300
|
+
for _ in range(5):
|
|
301
|
+
r.step()
|
|
302
|
+
self.assertEqual(len(notes), 1, "alerts once, not every round")
|
|
303
|
+
self.assertIn("is failing", notes[0])
|
|
304
|
+
self.assertTrue(relay.is_relay_post(slack.posted[-1]), "the alert is never re-injected")
|
|
305
|
+
self.assertEqual(r.wait_seconds(10), 60, "backs off while failing")
|
|
306
|
+
broken["on"] = False
|
|
307
|
+
self.assertEqual(r.step(), [])
|
|
308
|
+
self.assertIn("works again", notes[-1])
|
|
309
|
+
self.assertEqual(r.wait_seconds(10), 10)
|
|
310
|
+
self.assertEqual(hivey.sent, [], "alert posts coming back through history aren't injected")
|
|
311
|
+
|
|
312
|
+
|
|
270
313
|
if __name__ == "__main__":
|
|
271
314
|
unittest.main()
|
|
@@ -189,7 +189,7 @@ The harness, when chosen:
|
|
|
189
189
|
|
|
190
190
|
| Piece | What it does |
|
|
191
191
|
|---|---|
|
|
192
|
-
| Done gate | Stop hook `agent_gate.py`: while `.agent/state/run_active` exists, runs the check when the agent tries to finish and blocks it (at most 3 times), logging to `.agent/state/gate.log` |
|
|
192
|
+
| Done gate | Stop hook `agent_gate.py`: while `.agent/state/run_active` exists, runs the check when the agent tries to finish and blocks it (at most 3 times), logging to `.agent/state/gate.log`. After the check passes it also requires `status_check.py --today` (Status dated today, ≤ 40 lines, no unreviewed work under done; off with `"status_check": false`) and, when `review.critics` > 0, a fresh review from this run that says APPROVED or used all `review.rounds` |
|
|
193
193
|
| Resume context | SessionStart hook `agent_context.py`: on startup, resume and compaction injects run-in-progress, gate log, `tasks.json` progress, recent commits and the newest progress-log entries |
|
|
194
194
|
| Fresh review | the hivey skill's `fresh_review.py run --folder .`: N one-shot critics in parallel (`claude -p`, empty context, no saved session, read-only), merged into one review in `.agent/reviews/`; exit 0 only if every critic PASSes and the check exits 0 |
|
|
195
195
|
|
|
@@ -7,10 +7,20 @@ finish runs the agent's check command from .agent/config.json. If the check fail
|
|
|
7
7
|
blocked and the agent gets the check output as its next instruction. After MAX_ATTEMPTS failed
|
|
8
8
|
attempts the gate gives up (so it can never loop forever), logs it, and lets the agent stop.
|
|
9
9
|
With no run in progress, it does nothing: normal conversation is never blocked.
|
|
10
|
+
|
|
11
|
+
After the check passes, two more gates (verifier audit 2026-11-05: stale Status files and self-graded
|
|
12
|
+
"done" made agents' status untrustworthy):
|
|
13
|
+
- Status: status_check.py --today must pass (Status rewritten for this run, ≤ 40 lines, dated today,
|
|
14
|
+
no unreviewed work under "done"). Off with "status_check": false in .agent/config.json.
|
|
15
|
+
- Review: when .agent/config.json has review.critics > 0, a fresh review written during this run must
|
|
16
|
+
say APPROVED, or the run must have used all review.rounds (leftovers noted). The agent re-reading its
|
|
17
|
+
own fixes doesn't count. A run labelled in run_active (e.g. `echo evening > .agent/state/run_active`)
|
|
18
|
+
skips this only if the label is listed in review.optional_for.
|
|
10
19
|
"""
|
|
11
20
|
import argparse
|
|
12
21
|
import json
|
|
13
22
|
import os
|
|
23
|
+
import re
|
|
14
24
|
import subprocess
|
|
15
25
|
import sys
|
|
16
26
|
import time
|
|
@@ -18,6 +28,44 @@ from pathlib import Path
|
|
|
18
28
|
|
|
19
29
|
MAX_ATTEMPTS = 3
|
|
20
30
|
TIMEOUT_S = 300
|
|
31
|
+
HERE = Path(__file__).resolve().parent
|
|
32
|
+
VERDICT_RE = re.compile(r"^\*\*Verdict:\*\*\s*(\w+)", re.M)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def review_gate(root, cfg, active):
|
|
36
|
+
"""None if the run's review requirement is met, else the reason it isn't."""
|
|
37
|
+
review = cfg.get("review") or {}
|
|
38
|
+
if int(review.get("critics") or 0) <= 0:
|
|
39
|
+
return None
|
|
40
|
+
label = active.read_text().strip() if active.exists() else ""
|
|
41
|
+
if label and label in (review.get("optional_for") or []):
|
|
42
|
+
return None
|
|
43
|
+
start = active.stat().st_mtime
|
|
44
|
+
files = []
|
|
45
|
+
for d in (root / ".swarm" / "reviews", root / ".agent" / "reviews"):
|
|
46
|
+
if d.is_dir():
|
|
47
|
+
files += [f for f in d.glob("*.md") if f.stat().st_mtime >= start]
|
|
48
|
+
if not files:
|
|
49
|
+
return ("no fresh review was run during this run. Run the fresh review your brief names "
|
|
50
|
+
"(fresh_review.py run …) and fix what it finds; your own re-read doesn't count.")
|
|
51
|
+
files.sort(key=lambda f: f.stat().st_mtime)
|
|
52
|
+
verdicts = [(VERDICT_RE.search(f.read_text(errors="ignore")) or [None, "?"])[1] for f in files]
|
|
53
|
+
if verdicts[-1] == "APPROVED":
|
|
54
|
+
return None
|
|
55
|
+
rounds = int(review.get("rounds") or 3)
|
|
56
|
+
if len(files) >= rounds:
|
|
57
|
+
return None # max rounds used: allowed to finish, leftovers must be noted in Status
|
|
58
|
+
return (f"the latest fresh review says {verdicts[-1]} ({files[-1].name}). Fixing its defects yourself "
|
|
59
|
+
f"isn't a review: run round {len(files) + 1} (--round {len(files) + 1} --previous {files[-1]}) "
|
|
60
|
+
f"until APPROVED, or until {rounds} rounds are used and the leftovers are noted in Status.")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def status_gate(root, cfg):
|
|
64
|
+
if cfg.get("status_check") is False or not (HERE / "status_check.py").exists():
|
|
65
|
+
return None
|
|
66
|
+
r = subprocess.run([sys.executable, str(HERE / "status_check.py"), str(root), "--today"],
|
|
67
|
+
capture_output=True, text=True, timeout=60)
|
|
68
|
+
return None if r.returncode == 0 else (r.stdout + r.stderr).strip()
|
|
21
69
|
|
|
22
70
|
|
|
23
71
|
def log(state, line):
|
|
@@ -38,7 +86,8 @@ def main():
|
|
|
38
86
|
active = state / "run_active"
|
|
39
87
|
if not cfg_path.exists() or not active.exists():
|
|
40
88
|
return
|
|
41
|
-
|
|
89
|
+
cfg = json.loads(cfg_path.read_text())
|
|
90
|
+
check = cfg.get("check")
|
|
42
91
|
if not check:
|
|
43
92
|
return
|
|
44
93
|
|
|
@@ -49,6 +98,10 @@ def main():
|
|
|
49
98
|
except subprocess.TimeoutExpired:
|
|
50
99
|
code, output = 124, f"check timed out after {TIMEOUT_S}s"
|
|
51
100
|
|
|
101
|
+
if code == 0:
|
|
102
|
+
extra = [x for x in (status_gate(root, cfg), review_gate(root, cfg, active)) if x]
|
|
103
|
+
if extra:
|
|
104
|
+
code, output = 1, "The check passed, but:\n- " + "\n- ".join(extra)
|
|
52
105
|
if code == 0:
|
|
53
106
|
active.unlink(missing_ok=True)
|
|
54
107
|
attempts_file.unlink(missing_ok=True)
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Check that a hivey agent's Status is short, current and honest ("rewrite, don't append").
|
|
3
|
+
|
|
4
|
+
Finds the Status block between <!-- STATUS:START --> and <!-- STATUS:END --> in CLAUDE.md, else
|
|
5
|
+
STATUS.md. Fails when:
|
|
6
|
+
- it has more than --max-lines non-empty lines (default 40) or --max-chars (default 5000): old
|
|
7
|
+
lines belong in the wiki/log;
|
|
8
|
+
- its first lines carry no YYYY-MM-DD date;
|
|
9
|
+
- that date is older than today (--today, used by the done gate at the end of a run) or older
|
|
10
|
+
than the folder's last git commit (stale: work happened after the Status was written);
|
|
11
|
+
- a line counts unreviewed work as done ("✅ … not re-reviewed", "done (self-reviewed)", or an
|
|
12
|
+
"unreviewed" line under a Done/Shipped heading).
|
|
13
|
+
Why: the verifier audit of 2026-11-05 found 24-34 KB Status files, 92% stale, that named wrong rows and
|
|
14
|
+
called posted posts "queued", and fixes graded by the agent itself filed under "done".
|
|
15
|
+
|
|
16
|
+
status_check.py <folder> [--today] [--max-lines 40] exit 0 = OK, 1 = problems (printed)
|
|
17
|
+
status_check.py --all ~/agents report for every agent folder
|
|
18
|
+
"""
|
|
19
|
+
import argparse
|
|
20
|
+
import datetime as dt
|
|
21
|
+
import re
|
|
22
|
+
import subprocess
|
|
23
|
+
import sys
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
DATE_RE = re.compile(r"\b(20\d\d-\d\d-\d\d)\b")
|
|
27
|
+
UNREVIEWED_RE = re.compile(r"not (re-?)?reviewed|unreviewed|self-?reviewed|self-?graded|no (re-?)?review", re.I)
|
|
28
|
+
DONE_RE = re.compile(r"✅|\bdone\b|\bcomplete[d]?\b|\bshipped\b|built and reviewed|\bfixed\b", re.I)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def find_status(folder):
|
|
32
|
+
claude = folder / "CLAUDE.md"
|
|
33
|
+
if claude.exists():
|
|
34
|
+
text = claude.read_text(errors="ignore")
|
|
35
|
+
m = re.search(r"<!--\s*STATUS:START\s*-->(.*?)<!--\s*STATUS:END\s*-->", text, re.S)
|
|
36
|
+
if m:
|
|
37
|
+
return "CLAUDE.md Status", m.group(1)
|
|
38
|
+
status = folder / "STATUS.md"
|
|
39
|
+
if status.exists():
|
|
40
|
+
return "STATUS.md", status.read_text(errors="ignore")
|
|
41
|
+
return None, None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def last_commit_date(folder):
|
|
45
|
+
try:
|
|
46
|
+
r = subprocess.run(["git", "-C", str(folder), "log", "-1", "--format=%cs", "--", "."],
|
|
47
|
+
capture_output=True, text=True, timeout=20)
|
|
48
|
+
return dt.date.fromisoformat(r.stdout.strip()) if r.returncode == 0 and r.stdout.strip() else None
|
|
49
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def check(folder, today=False, max_lines=40, max_chars=5000):
|
|
54
|
+
folder = Path(folder).expanduser()
|
|
55
|
+
where, body = find_status(folder)
|
|
56
|
+
if body is None:
|
|
57
|
+
return None, []
|
|
58
|
+
lines = [l for l in body.splitlines() if l.strip()]
|
|
59
|
+
problems = []
|
|
60
|
+
if len(lines) > max_lines:
|
|
61
|
+
problems.append(f"{where} has {len(lines)} lines (max {max_lines}): rewrite it, don't append. "
|
|
62
|
+
"Move history and finished items into your wiki or log, keep only what's current.")
|
|
63
|
+
size = sum(len(l) for l in lines)
|
|
64
|
+
if size > max_chars:
|
|
65
|
+
problems.append(f"{where} is {size} characters (max {max_chars}): it's re-read every turn. Keep "
|
|
66
|
+
"it to the current state; move history into your wiki or log.")
|
|
67
|
+
date = None
|
|
68
|
+
for l in lines[:5]:
|
|
69
|
+
m = DATE_RE.search(l)
|
|
70
|
+
if m:
|
|
71
|
+
date = dt.date.fromisoformat(m.group(1))
|
|
72
|
+
break
|
|
73
|
+
if not date:
|
|
74
|
+
problems.append(f"{where} has no YYYY-MM-DD date in its first lines (add **Updated:** YYYY-MM-DD HH:MM).")
|
|
75
|
+
else:
|
|
76
|
+
if today and date < dt.date.today():
|
|
77
|
+
problems.append(f"{where} is dated {date}, not today: rewrite it for this run.")
|
|
78
|
+
commit = last_commit_date(folder)
|
|
79
|
+
if commit and date < commit:
|
|
80
|
+
problems.append(f"{where} is dated {date} but this folder has commits from {commit}: it's stale.")
|
|
81
|
+
heading = ""
|
|
82
|
+
for l in lines:
|
|
83
|
+
if l.lstrip().startswith("#") or re.match(r"^\*\*[^*]+:\*\*\s*$", l.strip()):
|
|
84
|
+
heading = l
|
|
85
|
+
if UNREVIEWED_RE.search(l) and (DONE_RE.search(l) or DONE_RE.search(heading)):
|
|
86
|
+
problems.append(f"{where} counts unreviewed work as done: {l.strip()[:160]!r}. Either get it "
|
|
87
|
+
"reviewed (fresh review) or list it under open/pending, not done.")
|
|
88
|
+
return where, problems
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def main():
|
|
92
|
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
93
|
+
ap.add_argument("folder", nargs="?", default=".")
|
|
94
|
+
ap.add_argument("--today", action="store_true", help="the Status must be dated today (end of a run)")
|
|
95
|
+
ap.add_argument("--max-lines", type=int, default=40)
|
|
96
|
+
ap.add_argument("--max-chars", type=int, default=5000)
|
|
97
|
+
ap.add_argument("--all", metavar="DIR", help="report on every sub-folder of DIR that has a Status")
|
|
98
|
+
a = ap.parse_args()
|
|
99
|
+
if a.all:
|
|
100
|
+
bad = 0
|
|
101
|
+
for f in sorted(Path(a.all).expanduser().iterdir()):
|
|
102
|
+
if not f.is_dir():
|
|
103
|
+
continue
|
|
104
|
+
where, problems = check(f, False, a.max_lines, a.max_chars)
|
|
105
|
+
if where is None:
|
|
106
|
+
continue
|
|
107
|
+
bad += bool(problems)
|
|
108
|
+
print(f"{'FAIL' if problems else 'OK '} {f.name}: " + (" | ".join(p[:110] for p in problems) or where))
|
|
109
|
+
sys.exit(1 if bad else 0)
|
|
110
|
+
where, problems = check(a.folder, a.today, a.max_lines, a.max_chars)
|
|
111
|
+
if where is None:
|
|
112
|
+
print("STATUS OK (no Status block or STATUS.md here)")
|
|
113
|
+
return
|
|
114
|
+
if problems:
|
|
115
|
+
print("STATUS FAIL:\n- " + "\n- ".join(problems))
|
|
116
|
+
sys.exit(1)
|
|
117
|
+
print(f"STATUS OK ({where})")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
if __name__ == "__main__":
|
|
121
|
+
main()
|
|
@@ -182,7 +182,7 @@ hivey agent-map schedule install [--at 06:30] [--model sonnet] # | remove | st
|
|
|
182
182
|
## Agent fleet (what every agent does now)
|
|
183
183
|
|
|
184
184
|
`hivey agent-map fleet` (or `office`; hivey menu → agent fleet) opens http://127.0.0.1:42817/office/: every live
|
|
185
|
-
agent in hivey at a desk in a 3D office, one room per space, and one spaceship per hivey session (`hivey session list`: the default session flies the classic frigate, the others a carrier, an explorer or a recoloured frigate, their name painted on the hull; a stopped session's ship has cold engines and its agents asleep at their desks, read from its saved `session.json`; a running one's engines burn). Click an agent to open its session in a terminal: the one already showing it, or a new Terminal/iTerm window running `hivey session attach <name>`, which also starts a stopped session. Click the name painted on a ship's hull for its menu (hover shows its agent count): open/start the session, or stop it (a second click confirms; `hivey session stop` ends all its agents and closes its terminal; never the default session). The space outside is one of six scenes (violet, emerald, crimson, deep blue, golden twin suns, a singularity with its lensed accretion disk), chosen with the page's 🌌 setting: a new one on every load, or always the one you pick (saved with the ⏱ setting; `?space=1..6` in the address overrides it). Drag the hull name to move the ship; positions are kept in `~/.hivey/agent-map/office-settings.json` with the ⏱ setting. Open, compact and clear reach the agent through its own session's socket. After a /compact the context shown is the compacted size until the agent's next reply. Solo agents, extra sessions in a space and
|
|
185
|
+
agent in hivey at a desk in a 3D office, one room per space, and one spaceship per hivey session (`hivey session list`: the default session flies the classic frigate, the others a carrier, an explorer or a recoloured frigate, their name painted on the hull; a stopped session's ship has cold engines and its agents asleep at their desks, read from its saved `session.json`; a running one's engines burn). Click an agent to open its session in a terminal: the one already showing it, or a new Terminal/iTerm window running `hivey session attach <name>`, which also starts a stopped session. Click the name painted on a ship's hull for its menu (hover shows its agent count): open/start the session, or stop it (a second click confirms; `hivey session stop` ends all its agents and closes its terminal; never the default session). The space outside is one of six scenes (violet, emerald, crimson, deep blue, golden twin suns, a singularity with its lensed accretion disk), chosen with the page's 🌌 setting: a new one on every load, or always the one you pick (saved with the ⏱ setting; `?space=1..6` in the address overrides it). Drag the hull name to move the ship; positions are kept in `~/.hivey/agent-map/office-settings.json` with the ⏱ setting. Open, compact and clear reach the agent through its own session's socket. The details panel (right-click an agent, or ⓘ) has a 📚 Wiki section: the agent's own `<name>-wiki/` (in its folder, or the folder named after its space under `~/agents` or `~/swarms`), its 8 newest pages and reports and its latest `log.md` entries; click one to open it in Obsidian (`obsidian://open`; a wiki that is not an Obsidian vault yet opens in the default Markdown app). After a /compact the context shown is the compacted size until the agent's next reply. Solo agents, extra sessions in a space and
|
|
186
186
|
each swarm's coordinator get a desk; a swarm's workers and critics stand beside their coordinator's desk.
|
|
187
187
|
|
|
188
188
|
- **Reads** each desk's terminal (`hivey pane read`, any CLI) and its Claude Code session log (context
|
|
@@ -96,6 +96,14 @@ main{position:relative}
|
|
|
96
96
|
.ship-menu button{text-align:left;background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:7px 10px;color:inherit;cursor:pointer}
|
|
97
97
|
.ship-menu button:hover{border-color:var(--honey)}
|
|
98
98
|
.ship-menu button.danger{color:#fda4af}.ship-menu button.danger.arm{background:#7f1d1d;color:#fff;border-color:#fb7185}
|
|
99
|
+
#drawer .wiki a{color:inherit;text-decoration:none}
|
|
100
|
+
#drawer .wiki-head a{font-weight:600;color:#9befc8}
|
|
101
|
+
#drawer .wiki-head a:hover,#drawer .wiki-page:hover .wt{text-decoration:underline}
|
|
102
|
+
#drawer .wiki-sub{margin:8px 0 3px;text-transform:uppercase;font-size:10px;letter-spacing:.06em}
|
|
103
|
+
#drawer .wiki-page{display:flex;flex-direction:column;padding:4px 6px;margin:0 -6px;border-radius:7px}
|
|
104
|
+
#drawer .wiki-page:hover{background:var(--panel2)}
|
|
105
|
+
#drawer .wiki-page .meta{font-size:11px}
|
|
106
|
+
#drawer .wiki-log{font-size:12px;line-height:1.35;margin:2px 0}
|
|
99
107
|
.ship-menu .note{font-size:11px;color:#93a4c3;padding:0 4px}
|
|
100
108
|
.ship-label{cursor:grab;touch-action:none;user-select:none}.ship-label.dragging{cursor:grabbing;border-color:var(--honey)}
|
|
101
109
|
#hud{position:absolute;left:14px;bottom:12px;display:flex;gap:8px;align-items:center;color:var(--muted);font-size:12px}
|
|
@@ -287,6 +287,12 @@ function openDrawer(a) {
|
|
|
287
287
|
${(s.done || []).length ? `<dt>Achieved</dt><dd>${s.done.map(d => '✓ ' + esc(d)).join('<br>')}</dd>` : ''}
|
|
288
288
|
${s.next ? `<dt>Next</dt><dd>→ ${esc(s.next)}</dd>` : ''}
|
|
289
289
|
${a.about ? `<dt>About</dt><dd>${esc(a.about)}</dd>` : ''}
|
|
290
|
+
${a.wiki ? `<dt>📚 Wiki</dt><dd class="wiki">
|
|
291
|
+
<div class="wiki-head"><a href="#" data-wiki="" title="Open its index in Obsidian">${esc(a.wiki.short)}</a> <span class="meta">${a.wiki.pages} pages${a.wiki.vault ? '' : ' · not an Obsidian vault yet'}</span></div>
|
|
292
|
+
${(a.wiki.recent || []).length ? `<div class="meta wiki-sub">Newest pages and reports</div>` + a.wiki.recent.map(r => `<a href="#" class="wiki-page" data-wiki="${esc(r.path)}" title="${esc(r.path)}: open in Obsidian">
|
|
293
|
+
<span class="wt">${/report|daily|brief/i.test(r.path) ? '📊' : '📄'} ${esc(r.title)}</span><span class="meta">${esc(r.folder || '')}${r.folder ? ' · ' : ''}${ago(r.at)}</span></a>`).join('') : ''}
|
|
294
|
+
${(a.wiki.log || []).length ? `<div class="meta wiki-sub">Latest log entries</div>` + a.wiki.log.map(l => `<div class="wiki-log"><span class="meta">${esc(l.date)}</span> ${esc(l.what)}</div>`).join('') : ''}
|
|
295
|
+
</dd>` : ''}
|
|
290
296
|
${a.team?.length ? `<dt>Swarm team</dt><dd>${a.team.map(m => `${st(m.status).emoji} ${esc(m.name)} <span class="meta">${esc(m.role)}</span>`).join('<br>')}</dd>` : ''}
|
|
291
297
|
${a.last_prompt ? `<dt>Your last prompt</dt><dd>${esc(a.last_prompt)}</dd>` : ''}
|
|
292
298
|
${a.recap ? `<dt>Session recap</dt><dd>${esc(a.recap)}</dd>` : ''}
|
|
@@ -306,6 +312,14 @@ function openDrawer(a) {
|
|
|
306
312
|
office.markSelected();
|
|
307
313
|
}
|
|
308
314
|
function wireDrawer(a) {
|
|
315
|
+
$('#drawer').querySelectorAll('[data-wiki]').forEach(l => l.onclick = async e => {
|
|
316
|
+
e.preventDefault(); e.stopPropagation();
|
|
317
|
+
try {
|
|
318
|
+
const r = await fetch('/hv-office-action', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: a.id, action: 'wiki', path: l.dataset.wiki }) });
|
|
319
|
+
const j = await r.json();
|
|
320
|
+
toast(j.ok ? `📚 ${j.message}` : `${a.name}: ${j.message}`);
|
|
321
|
+
} catch (err) { toast('The office server is not answering: run `hivey agent-map fleet` again'); }
|
|
322
|
+
});
|
|
309
323
|
$('#drawer').querySelectorAll('button[data-act]').forEach(b => b.onclick = e => {
|
|
310
324
|
e.stopPropagation();
|
|
311
325
|
if (b.disabled) return;
|
|
@@ -560,8 +574,35 @@ const office = (() => {
|
|
|
560
574
|
return e;
|
|
561
575
|
}
|
|
562
576
|
// one spaceship per hivey session, flying in a column (the default session first, stopped ones dark and empty)
|
|
577
|
+
// free what the old scene used and the new one does not (shapes, materials, textures stay on the GPU
|
|
578
|
+
// otherwise: every rebuild leaked ~10 MB until the page froze)
|
|
579
|
+
function release(prev, next) {
|
|
580
|
+
const keep = new Set([scene.background, scene.environment]);
|
|
581
|
+
const texturesOf = m => Object.values(m).filter(v => v && v.isTexture);
|
|
582
|
+
next.traverse(o => {
|
|
583
|
+
if (o.geometry) keep.add(o.geometry);
|
|
584
|
+
if (o.skeleton) keep.add(o.skeleton);
|
|
585
|
+
[].concat(o.material || []).forEach(m => { keep.add(m); texturesOf(m).forEach(t => keep.add(t)); });
|
|
586
|
+
});
|
|
587
|
+
prev.traverse(o => {
|
|
588
|
+
if (o.geometry && !keep.has(o.geometry)) o.geometry.dispose();
|
|
589
|
+
if (o.skeleton && !keep.has(o.skeleton)) o.skeleton.dispose(); // each robot's bone texture
|
|
590
|
+
[].concat(o.material || []).forEach(m => {
|
|
591
|
+
if (keep.has(m)) return;
|
|
592
|
+
texturesOf(m).forEach(t => { if (!keep.has(t)) t.dispose(); });
|
|
593
|
+
m.dispose();
|
|
594
|
+
});
|
|
595
|
+
});
|
|
596
|
+
}
|
|
563
597
|
function build(list, sessions) {
|
|
598
|
+
// rebuild only when something drawn changed (searching, polling and view switches call this often)
|
|
599
|
+
const sig = JSON.stringify([list.map(a => [a.id, a.status, a.name, a.space, a.context_pct, a.asleep, a.summary?.bubble,
|
|
600
|
+
a.summary?.needs_you, a.summary?.advice, (a.team || []).map(m => m.status)]), sessions, ui.toon, ui.ships]);
|
|
601
|
+
if (sig === build.sig && world.children.length) return;
|
|
602
|
+
build.sig = sig;
|
|
603
|
+
const prev = world;
|
|
564
604
|
scene.remove(world); world = new THREE.Group(); scene.add(world);
|
|
605
|
+
ship.reset();
|
|
565
606
|
desks = []; labels.innerHTML = ''; tags = new Map(); roomTags = [];
|
|
566
607
|
sessions = sessions?.length ? sessions : [{ name: 'default', running: true, default: true }];
|
|
567
608
|
const known = new Set(sessions.map(s => s.name));
|
|
@@ -638,6 +679,7 @@ const office = (() => {
|
|
|
638
679
|
sun.shadow.camera.updateProjectionMatrix();
|
|
639
680
|
applyStyle(world);
|
|
640
681
|
markSelected();
|
|
682
|
+
release(prev, world);
|
|
641
683
|
if (!build.done) { fit(); build.done = true; }
|
|
642
684
|
dirty = true;
|
|
643
685
|
}
|
|
@@ -875,6 +917,7 @@ const office = (() => {
|
|
|
875
917
|
dirty = true;
|
|
876
918
|
return ship.spaceNo();
|
|
877
919
|
}
|
|
920
|
+
globalThis.__fleet = { memory: () => ({ ...renderer.info.memory, programs: renderer.info.programs?.length }), world: () => world }; // for debugging leaks
|
|
878
921
|
return { ok: true, build, markSelected, resize, fit, flash, setSpace, ready: ship.load() };
|
|
879
922
|
})();
|
|
880
923
|
|
|
@@ -403,7 +403,6 @@ export function createShip(opts) {
|
|
|
403
403
|
}
|
|
404
404
|
function thrust(s) {
|
|
405
405
|
for (const e of engines) {
|
|
406
|
-
if (!e.sp.parent?.parent) continue; // a ship from an older build
|
|
407
406
|
const k = 1 + 0.1 * Math.sin(s * 23 + e.ph) + 0.05 * Math.sin(s * 61 + e.ph * 2);
|
|
408
407
|
e.sp.scale.setScalar(e.s * k);
|
|
409
408
|
e.pl.scale.y = e.s * 0.8 * (1 + 0.18 * Math.sin(s * 31 + e.ph));
|
|
@@ -416,7 +415,6 @@ export function createShip(opts) {
|
|
|
416
415
|
SH = st.hull ? once('hull:' + st.hull, () => { const m = HULL.clone(); m.color.set(st.hull); return m; }) : HULL;
|
|
417
416
|
SHD = st.dark ? once('dark:' + st.dark, () => { const m = HULL_DARK.clone(); m.color.set(st.dark); return m; }) : HULL_DARK;
|
|
418
417
|
ACC = st.acc; KIND = st.kind; NAME = name ? String(name).toUpperCase() : '';
|
|
419
|
-
for (let i = engines.length - 1; i >= 0; i--) if (!engines[i].sp.parent?.parent) engines.splice(i, 1);
|
|
420
418
|
}
|
|
421
419
|
// the ship's name painted on its hull, in its light colour
|
|
422
420
|
function nameplate(grp, text, x, y, z, w, h) {
|
|
@@ -795,5 +793,7 @@ export function createShip(opts) {
|
|
|
795
793
|
spaceNo = n;
|
|
796
794
|
return galaxyTex(n);
|
|
797
795
|
}
|
|
798
|
-
return { load, makeRobot, makeStation, decorate, bridge, background, pod, space, scenes: SCENES.map(s => s.name), spaceNo: () => spaceNo, planets: () => planets
|
|
796
|
+
return { load, makeRobot, makeStation, decorate, bridge, background, pod, space, scenes: SCENES.map(s => s.name), spaceNo: () => spaceNo, planets: () => planets, thrusting: () => engines.length > 0, thrust,
|
|
797
|
+
// a new scene is being built: forget the old ships' engines and planets (they kept the old scene in memory)
|
|
798
|
+
reset: () => { engines.length = 0; planets.length = 0; }, accent, statusLed, NO_LINE };
|
|
799
799
|
}
|
|
@@ -216,6 +216,85 @@ def asleep_desks(hs: dict) -> list[dict]:
|
|
|
216
216
|
return out
|
|
217
217
|
|
|
218
218
|
|
|
219
|
+
# ---------------------------------------------------------------- its wiki: newest pages and log entries
|
|
220
|
+
|
|
221
|
+
WIKI_SKIP = {"raw", ".obsidian", ".trash", ".git", "node_modules", "assets", "attachments", "templates", "_templates"}
|
|
222
|
+
WIKI_META = {"log.md", "index.md", "claude.md", "agents.md", "ingest-ledger.md", "readme.md"}
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def obsidian_vaults() -> list[str]:
|
|
226
|
+
"""Folders Obsidian knows as vaults (pages inside them open with obsidian://open)."""
|
|
227
|
+
try:
|
|
228
|
+
got = json.loads((HOME / "Library/Application Support/obsidian/obsidian.json").read_text())
|
|
229
|
+
return [os.path.realpath(v["path"]) for v in (got.get("vaults") or {}).values() if v.get("path")]
|
|
230
|
+
except (OSError, ValueError, AttributeError, TypeError):
|
|
231
|
+
return []
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def wiki_dir(folder: str | None, space: str = "") -> Path | None:
|
|
235
|
+
"""The agent's or swarm's own wiki: a `<name>-wiki/` folder in its folder (or the folder itself); when its
|
|
236
|
+
terminal sits one level up (~/swarms), the folder named after its space."""
|
|
237
|
+
bases = [Path(folder)] if folder and os.path.isdir(folder) else []
|
|
238
|
+
if space and re.fullmatch(r"[\w.-]{1,64}", space):
|
|
239
|
+
bases += [b / space for b in bases] + [HOME / "agents" / space, HOME / "swarms" / space]
|
|
240
|
+
for base in bases:
|
|
241
|
+
if not base.is_dir():
|
|
242
|
+
continue
|
|
243
|
+
for cand in [base] + sorted(base.glob("*-wiki")):
|
|
244
|
+
if cand.is_dir() and cand.name.endswith("-wiki") and any((cand / n).exists() for n in ("index.md", "log.md", "wiki")):
|
|
245
|
+
return cand
|
|
246
|
+
return None
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def wiki_info(folder: str | None, vaults: list[str], space: str = "") -> dict | None:
|
|
250
|
+
"""The newest pages and reports the agent wrote in its wiki and its latest log entries."""
|
|
251
|
+
root = wiki_dir(folder, space)
|
|
252
|
+
if not root:
|
|
253
|
+
return None
|
|
254
|
+
pages, seen = [], 0
|
|
255
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
256
|
+
dirnames[:] = [d for d in dirnames if d.lower() not in WIKI_SKIP and not d.startswith(".")]
|
|
257
|
+
for f in filenames:
|
|
258
|
+
if not f.endswith(".md") or f.lower() in WIKI_META or f.endswith(".excalidraw.md"):
|
|
259
|
+
continue
|
|
260
|
+
seen += 1
|
|
261
|
+
p = os.path.join(dirpath, f)
|
|
262
|
+
try:
|
|
263
|
+
pages.append((os.path.getmtime(p), p))
|
|
264
|
+
except OSError:
|
|
265
|
+
pass
|
|
266
|
+
if seen > 20000:
|
|
267
|
+
break
|
|
268
|
+
recent = []
|
|
269
|
+
for mtime, p in sorted(pages, reverse=True)[:8]:
|
|
270
|
+
title = Path(p).stem.replace("-", " ")
|
|
271
|
+
try:
|
|
272
|
+
with open(p, encoding="utf-8", errors="replace") as fh:
|
|
273
|
+
for line in fh.read(4000).splitlines():
|
|
274
|
+
if line.startswith("# "):
|
|
275
|
+
title = line[2:].strip()
|
|
276
|
+
break
|
|
277
|
+
except OSError:
|
|
278
|
+
pass
|
|
279
|
+
rel = os.path.relpath(p, root)
|
|
280
|
+
recent.append({"path": rel, "title": title[:120], "folder": os.path.dirname(rel),
|
|
281
|
+
"at": dt.datetime.fromtimestamp(mtime, dt.timezone.utc).isoformat(timespec="seconds")})
|
|
282
|
+
log = []
|
|
283
|
+
for lp in (root / "log.md", root / "wiki" / "log.md"):
|
|
284
|
+
try:
|
|
285
|
+
text = lp.read_text(errors="replace")[-20000:]
|
|
286
|
+
except OSError:
|
|
287
|
+
continue
|
|
288
|
+
for m in re.finditer(r"^## \[([^\]]+)\]\s*(.+)$", text, re.M):
|
|
289
|
+
log.append({"date": m.group(1).strip(), "what": m.group(2).strip()[:140]})
|
|
290
|
+
log = log[-5:][::-1]
|
|
291
|
+
break
|
|
292
|
+
real = os.path.realpath(root)
|
|
293
|
+
vault = next((v for v in vaults if real == v or real.startswith(v + os.sep)), None)
|
|
294
|
+
return {"dir": str(root), "short": short(str(root)), "vault": bool(vault), "pages": len(pages),
|
|
295
|
+
"recent": recent, "log": log}
|
|
296
|
+
|
|
297
|
+
|
|
219
298
|
# ---------------------------------------------------------------- what each one shows
|
|
220
299
|
|
|
221
300
|
def screen(hv: str, pane: str, sock: str | None = None) -> str:
|
|
@@ -442,8 +521,10 @@ def collect(hv: str, sessions: list[dict] | None = None) -> list[dict]:
|
|
|
442
521
|
for d in (desks(hv, hs) if hs["running"] else asleep_desks(hs))]
|
|
443
522
|
with cf.ThreadPoolExecutor(max_workers=8) as pool:
|
|
444
523
|
screens = list(pool.map(lambda d: "" if d.get("asleep") else screen(hv, d["pane"], d.get("sock")), people))
|
|
524
|
+
vaults = obsidian_vaults()
|
|
445
525
|
for d, scr in zip(people, screens):
|
|
446
526
|
d["screen"] = scr
|
|
527
|
+
d["wiki"] = wiki_info(d.get("folder"), vaults, d.get("space", ""))
|
|
447
528
|
log = session_log(transcript_of(d["session"], d["cli_id"]))
|
|
448
529
|
d["_log"] = log
|
|
449
530
|
d["log_uuid"] = log.get("uuid", "")
|
|
@@ -36,6 +36,7 @@ import subprocess
|
|
|
36
36
|
import sys
|
|
37
37
|
import threading
|
|
38
38
|
import time
|
|
39
|
+
import urllib.parse
|
|
39
40
|
import urllib.request
|
|
40
41
|
from pathlib import Path
|
|
41
42
|
|
|
@@ -50,7 +51,7 @@ PREFERRED_PORT = 42817 # unregistered and below macOS's temporary-port range, s
|
|
|
50
51
|
IDLE_SECONDS = 2 * 3600
|
|
51
52
|
PING = "/hv-ping"
|
|
52
53
|
MARK = b"hivey-agent-map"
|
|
53
|
-
VERSION = b"office-
|
|
54
|
+
VERSION = b"office-13" # bump when the server gains actions, so `ensure` replaces an older one
|
|
54
55
|
OFFICE_EVERY = 300 # seconds between full office refreshes (every terminal re-summarized) while its page is open
|
|
55
56
|
OFFICE_LIVE = 60 # seconds between live passes (status, context, screen; only changed statuses summarized)
|
|
56
57
|
OFFICE_WATCHED = 600 # the page counts as open for this long after its last poll
|
|
@@ -360,7 +361,26 @@ def session_action(session: str) -> tuple[bool, str]:
|
|
|
360
361
|
if how else (False, f"could not open a terminal; run: hivey session attach {session}")
|
|
361
362
|
|
|
362
363
|
|
|
363
|
-
def
|
|
364
|
+
def open_wiki_page(desk: dict, rel: str) -> tuple[bool, str]:
|
|
365
|
+
"""Open a page of the agent's own wiki in Obsidian (only .md files inside that wiki)."""
|
|
366
|
+
wiki = desk.get("wiki") or {}
|
|
367
|
+
root = os.path.realpath(wiki.get("dir") or "")
|
|
368
|
+
if not root or not os.path.isdir(root):
|
|
369
|
+
return False, "this agent has no wiki"
|
|
370
|
+
target = os.path.realpath(os.path.join(root, rel or ""))
|
|
371
|
+
if os.path.isdir(target) and target == root: # the wiki itself: its index
|
|
372
|
+
target = next((os.path.join(root, n) for n in ("index.md", "wiki/index.md") if os.path.isfile(os.path.join(root, n))), "")
|
|
373
|
+
if not target.endswith(".md") or not target.startswith(root + os.sep) or not os.path.isfile(target):
|
|
374
|
+
return False, "not a page of this agent's wiki"
|
|
375
|
+
if wiki.get("vault"):
|
|
376
|
+
p = subprocess.run(["open", "obsidian://open?path=" + urllib.parse.quote(target, safe="")],
|
|
377
|
+
capture_output=True, text=True, timeout=10)
|
|
378
|
+
return (p.returncode == 0), ("opened in Obsidian" if p.returncode == 0 else (p.stderr or "open failed").strip()[-200:])
|
|
379
|
+
subprocess.run(["open", target], capture_output=True, timeout=10)
|
|
380
|
+
return True, f"opened (not an Obsidian vault yet: in Obsidian, Open folder as vault → {wiki.get('short')})"
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def office_action(desk_id: str, action: str, session: str = "", path: str = "") -> tuple[bool, str]:
|
|
364
384
|
if action == "session":
|
|
365
385
|
return session_action(session)
|
|
366
386
|
if action == "stop-session":
|
|
@@ -373,6 +393,8 @@ def office_action(desk_id: str, action: str, session: str = "") -> tuple[bool, s
|
|
|
373
393
|
if not desk or not PANE.match(pane):
|
|
374
394
|
return False, "unknown agent"
|
|
375
395
|
sock = desk.get("sock") or None
|
|
396
|
+
if action == "wiki": # works for asleep agents too: their wiki is on disk
|
|
397
|
+
return open_wiki_page(desk, path)
|
|
376
398
|
if desk.get("asleep"): # an agent of a stopped session: start the session (compact/clear wait until then)
|
|
377
399
|
if action == "focus":
|
|
378
400
|
return session_action(desk.get("hv_session") or "")
|
|
@@ -522,7 +544,7 @@ class Handler(http.server.SimpleHTTPRequestHandler):
|
|
|
522
544
|
length = min(int(self.headers.get("Content-Length") or 0), 4096)
|
|
523
545
|
req = json.loads(self.rfile.read(length) or b"{}")
|
|
524
546
|
ok, msg = office_action(str(req.get("id") or req.get("pane") or ""), str(req.get("action", "")),
|
|
525
|
-
str(req.get("session") or ""))
|
|
547
|
+
str(req.get("session") or ""), str(req.get("path") or ""))
|
|
526
548
|
except (ValueError, OSError, subprocess.SubprocessError) as e:
|
|
527
549
|
ok, msg = False, str(e)[:200]
|
|
528
550
|
return self.answer(200, json.dumps({"ok": ok, "message": msg}).encode())
|