"""MoonSSH Herdr event hook. Optional reply excerpts are encrypted on this host.""" import base64 import contextlib from datetime import date, datetime, timedelta import fcntl import getpass import hashlib import http.client from itertools import islice import json import os from pathlib import Path import re import socket import sqlite3 import stat import subprocess import sys import tempfile import time import unicodedata from urllib.error import HTTPError, URLError from urllib.parse import urlsplit from urllib.request import HTTPRedirectHandler, Request, build_opener import uuid AGENTS = set("pi claude codex gemini cursor devin agy cline omp mastracode opencode copilot kimi kiro droid amp grok hermes kilo qodercli qwen letta maki muse".split()) MAX_TAIL = 256 * 1024 PROC_ROOT = Path("/proc") CODEX_TITLE_ID = re.compile(r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{5}(?:[0-9a-f]{7}|\.\.\.)") def directory(socket_path): root = Path.home() / ".config" / "moonssh-herdr-push" root.mkdir(parents=True, mode=0o700, exist_ok=True) info = root.lstat() if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077: raise ValueError("Private configuration directory required") return root / hashlib.sha256(os.fsencode(os.path.realpath(socket_path))).hexdigest() def relay_origin(value): url = urlsplit(value) if (url.scheme != "https" or not url.hostname or url.username or url.password or url.path not in ("", "/") or url.query or url.fragment): raise ValueError("HTTPS relay origin required") return url def configure(path): if not sys.stdin.isatty(): raise ValueError("Interactive terminal required") url = relay_origin(input("MoonSSH relay HTTPS address: ").strip()) key = getpass.getpass("MoonSSH host key: ").strip() if not re.fullmatch(r"[A-Za-z0-9_-]{43}", key): raise ValueError("Invalid host key") with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, delete=False) as stream: json.dump({"relay": url.geturl(), "key": key}, stream) name = stream.name os.replace(name, path.with_suffix(".json")) print("MoonSSH host paired.") def herdr_request(socket_path, method, params, timeout=1): with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: client.settimeout(timeout) client.connect(socket_path) request = {"id": "moonssh", "method": method, "params": params} client.sendall(json.dumps(request).encode() + b"\n") with client.makefile("rb") as stream: response = json.loads(stream.readline(256 * 1024)) return response["result"] def pane_request(socket_path, pane_id, method): return herdr_request(socket_path, method, {"pane_id": pane_id}) def pane_info(socket_path, pane_id): return pane_request(socket_path, pane_id, "pane.get")["pane"] def claim_event(database, socket_path, pane_id, status, configs=()): started = None with contextlib.closing(sqlite3.connect(database, timeout=2)) as db, db: db.execute("BEGIN IMMEDIATE") # Resolve the current pane under the same lock as the state transition. # Older hook processes must not overwrite a newer live status. pane = pane_info(socket_path, pane_id) terminal = pane.get("terminal_id") if pane.get("pane_id") != pane_id or pane.get("agent_status") != status or not terminal: return None, None, None, None fingerprint = hashlib.sha256((pane_id + "\0" + terminal).encode()).hexdigest() db.execute("""CREATE TABLE IF NOT EXISTS status ( target TEXT PRIMARY KEY, value TEXT, updated INTEGER)""") previous = db.execute("SELECT value, updated FROM status WHERE target = ?", (fingerprint,)).fetchone() if previous and previous[0] == status: return None, None, None, None prior = previous[0] if previous else None now = time.time() db.execute("DELETE FROM status WHERE updated < ?", (now - 7 * 86400,)) db.execute("INSERT OR REPLACE INTO status VALUES (?, ?, ?)", (fingerprint, status, int(now))) if status == "working" or prior == "working": # Keep the old status schema readable by earlier plugin versions. db.execute("""CREATE TABLE IF NOT EXISTS working_session ( target TEXT PRIMARY KEY, identity TEXT NOT NULL, started REAL NOT NULL)""") agent = pane.get("agent") identifier = session_identity(pane, agent) identity = agent + ":" + identifier if identifier else None if status == "working": db.execute("DELETE FROM working_session WHERE target = ? OR started < ?", (fingerprint, now - 7 * 86400)) if identity: db.execute("INSERT INTO working_session VALUES (?, ?, ?)", (fingerprint, identity, now)) else: turn = db.execute("SELECT identity, started FROM working_session WHERE target = ?", (fingerprint,)).fetchone() db.execute("DELETE FROM working_session WHERE target = ?", (fingerprint,)) if turn and turn[0] == identity and int(turn[1]) == previous[1]: started = turn[1] kind = None if status == "blocked" and prior != "blocked": kind = "attention" if (status == "done" and prior not in ("done", "idle")) or (status == "idle" and prior == "working"): kind = "completed" if not kind: return None, None, None, None payload = {"eventId": str(uuid.uuid4()), "kind": kind, "target": fingerprint} if pane.get("agent") in AGENTS: payload["agent"] = pane["agent"] # Commit the status transition AND generic alert atomically. A crash # during optional preview generation can only omit the preview. outbox_table(db) db.execute("DELETE FROM outbox WHERE created <= ? OR attempts >= 9", (now - 900,)) for config, settings in configs: db.execute("INSERT INTO outbox VALUES (?, ?, ?, ?, ?, 0, ?)", (payload["eventId"], config.name, credential_id(settings), json.dumps(payload), now, now + 20)) db.execute("DELETE FROM outbox WHERE rowid IN (SELECT rowid FROM outbox ORDER BY created DESC LIMIT -1 OFFSET 512)") return kind, payload, pane, started def session_id(pane, agent): session = pane.get("agent_session") if (agent not in ("codex", "claude") or not isinstance(session, dict) or session.get("source") != "herdr:" + agent or session.get("agent") != agent or session.get("kind") != "id" or not isinstance(session.get("value"), str)): return None try: return uuid.UUID(session["value"]) except ValueError: return None def codex_title_id(value): if isinstance(value, str) and CODEX_TITLE_ID.fullmatch(value): return value.removesuffix("...") return None def session_identity(pane, agent): native = session_id(pane, agent) if agent == "codex": title = codex_title_id(pane.get("terminal_title_stripped") or pane.get("terminal_title")) if title: return title if native is None or str(native).startswith(title) else None return str(native) if native else None def transcript(pane, agent): identifier = session_identity(pane, agent) if identifier is None: return None home = Path.home().resolve() if agent == "claude": cwd = pane.get("foreground_cwd") or pane.get("cwd") if not isinstance(cwd, str) or not cwd.startswith("/"): return None root = home / ".claude" / "projects" candidate = root / re.sub(r"[^a-zA-Z0-9-]", "-", cwd) / (identifier + ".jsonl") return candidate if candidate == candidate.resolve() and candidate.is_file() else None root = home / ".codex" / "sessions" today = date.today() days = {today, today - timedelta(days=1)} uuid_hint = uuid.UUID(identifier.ljust(36, "0")) if uuid_hint.version == 7: try: created = datetime.fromtimestamp((uuid_hint.int >> 80) / 1000).date() days.update((created, created - timedelta(days=1), created + timedelta(days=1))) except (OverflowError, OSError, ValueError): pass suffix = identifier + ("[0-9a-f]" * (36 - len(identifier))) matches = { path for day in days for path in (root / day.strftime("%Y/%m/%d")).glob("rollout-*-" + suffix + ".jsonl") if path == path.resolve() and path.is_file() } return next(iter(matches)) if len(matches) == 1 else None def read_tail(path, started, open_target=None, expected_session=None): flags = os.O_RDONLY | os.O_NONBLOCK if open_target is None: flags |= os.O_NOFOLLOW with os.fdopen(os.open(path, flags), "rb") as stream: info = os.fstat(stream.fileno()) if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mtime < started: return None if open_target is not None: current = path.stat() if os.readlink(path) != open_target or (info.st_dev, info.st_ino) != (current.st_dev, current.st_ino): return None if expected_session is not None: header = json.loads(stream.readline(64 * 1024)) if header.get("type") != "session_meta" or header.get("payload", {}).get("id") != expected_session: return None stream.seek(0) if info.st_size > MAX_TAIL: stream.seek(info.st_size - MAX_TAIL) stream.readline(MAX_TAIL) return stream.read(MAX_TAIL).splitlines() def live_codex_tail(socket_path, pane, identifier, started): # A running Codex can keep writing after its rollout is removed or replaced. process_info = pane_request(socket_path, pane["pane_id"], "pane.process_info")["process_info"] group = process_info.get("foreground_process_group_id") if process_info.get("pane_id") != pane["pane_id"] or not isinstance(group, int) or group <= 0: return None root = Path.home().resolve() / ".codex" / "sessions" pattern = re.compile(r"\d{4}/\d{2}/\d{2}/rollout-[^/]+-" + str(identifier) + r"\.jsonl") for process in process_info.get("foreground_processes", []): pid = process.get("pid") if process.get("name") != "codex" or not isinstance(pid, int) or pid <= 0: continue proc = PROC_ROOT / str(pid) try: if (proc.stat().st_uid != os.getuid() or os.getpgid(pid) != group or (proc / "comm").read_text().strip() != "codex"): continue for fd in islice((proc / "fd").iterdir(), 512): try: link = os.readlink(fd) target = Path(link.removesuffix(" (deleted)")) if (not target.is_relative_to(root) or not pattern.fullmatch(str(target.relative_to(root))) or target != target.resolve()): continue info = fd.stat() if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid(): continue if lines := read_tail(fd, started, open_target=link): return lines except OSError: continue except OSError: continue return None def reply_excerpt(pane, agent, started, socket_path=None): path = transcript(pane, agent) title = agent == "codex" and codex_title_id(pane.get("terminal_title_stripped") or pane.get("terminal_title")) try: lines = read_tail(path, started, expected_session=path.stem[-36:] if title else None) if path else None except FileNotFoundError: lines = None if not lines and not title and socket_path and agent == "codex" and sys.platform == "linux": identifier = session_id(pane, agent) if identifier is not None: lines = live_codex_tail(socket_path, pane, identifier, started) if not lines: return None final = answer = None for line in lines: try: entry = json.loads(line) stamp = datetime.fromisoformat(entry["timestamp"].replace("Z", "+00:00")) if stamp.tzinfo is None: continue at = stamp.timestamp() except (KeyError, AttributeError, TypeError, ValueError, OverflowError): continue if at < started or at > time.time() + 5: continue if agent == "codex": payload = entry.get("payload") or {} if entry.get("type") == "event_msg": if payload.get("type") in ("task_started", "user_message", "turn_aborted"): final = answer = None elif payload.get("type") == "task_complete": reply = payload.get("last_agent_message") final = (reply, at) if reply and reply == answer else None elif (entry.get("type") == "response_item" and payload.get("type") == "message" and payload.get("role") == "assistant" and payload.get("phase") == "final_answer"): answer = "\n".join(item["text"] for item in payload.get("content", []) if item.get("type") == "output_text" and isinstance(item.get("text"), str)) elif entry.get("sessionId") == path.stem and not entry.get("isSidechain"): message = entry.get("message") or {} if entry.get("type") == "user": final = None elif entry.get("type") == "assistant" and message.get("role") == "assistant": blocks = message.get("content", []) if isinstance(blocks, list): texts = [block["text"] for block in blocks if isinstance(block, dict) and block.get("type") == "text" and isinstance(block.get("text"), str)] final = (" ".join(texts), at) if texts and message.get("stop_reason") == "end_turn" else None if not final or time.time() - final[1] > 20: return None plain = " ".join("".join( " " if c.isspace() else c for c in final[0] if c.isspace() or not unicodedata.category(c).startswith("C") ).split()) if len(plain) > 140 or len(plain.encode()) > 260: plain = plain[:139].encode()[:257].decode(errors="ignore").rstrip() + "…" return plain or None def task_name(socket_path, pane): def field(method, params, section, name): try: return herdr_request(socket_path, method, params, timeout=0.2)[section].get(name) except (OSError, ValueError, KeyError, TypeError, AttributeError): return None def label(value, limit): if not isinstance(value, str): return "" text = " ".join("".join(c for c in value if not unicodedata.category(c).startswith("C")).split()) encoded = text.encode() return text if len(encoded) <= limit else encoded[:limit - 3].decode(errors="ignore").rstrip() + "…" pane_id = pane["pane_id"] try: agent = herdr_request(socket_path, "agent.get", {"target": pane_id}, timeout=0.2)["agent"] name = agent.get("name") if agent.get("terminal_id") == pane.get("terminal_id") else None except (OSError, ValueError, KeyError, TypeError, AttributeError): name = None for candidate in (name, pane.get("label"), pane.get("title")): if (display := label(candidate, 180)) and not (pane.get("agent") == "codex" and codex_title_id(display)): return display workspace = label(field("workspace.get", {"workspace_id": pane.get("workspace_id")}, "workspace", "label"), 65) tab = label(field("tab.get", {"tab_id": pane.get("tab_id")}, "tab", "label"), 65) return " · ".join(dict.fromkeys(part for part in (workspace, tab) if part)) def encrypt_reply(public_key, event_id, preview): # Security.framework exports PKCS#1; wrap it in SubjectPublicKeyInfo for OpenSSL. rsa = base64.b64decode(public_key, validate=True) if not 384 <= len(rsa) <= 410: return None def sequence(tag, data): return bytes([tag, 0x82]) + len(data).to_bytes(2, "big") + data spki = sequence(0x30, bytes.fromhex("300d06092a864886f70d0101010500") + sequence(0x03, b"\0" + rsa)) with tempfile.NamedTemporaryFile() as key: key.write(b"-----BEGIN PUBLIC KEY-----\n" + base64.encodebytes(spki) + b"-----END PUBLIC KEY-----\n") key.flush() result = subprocess.run([ "/usr/bin/openssl", "pkeyutl", "-encrypt", "-pubin", "-inkey", key.name, "-pkeyopt", "rsa_padding_mode:oaep", "-pkeyopt", "rsa_oaep_md:sha256", "-pkeyopt", "rsa_mgf1_md:sha256", ], input=(event_id + "\n" + preview).encode(), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=1, check=True) return base64.b64encode(result.stdout).decode() if len(result.stdout) == 384 else None class RejectRedirect(HTTPRedirectHandler): def redirect_request(self, request, fp, code, msg, headers, newurl): return None def relay_request(config, endpoint, payload=None): url = relay_origin(config["relay"]) return Request(url.geturl().rstrip("/") + "/v1/" + endpoint, method="POST", data=json.dumps(payload, ensure_ascii=False).encode() if payload is not None else None, headers={ "Content-Type": "application/json", "Authorization": "Bearer " + config["key"], "User-Agent": "MoonSSH-Herdr/0.5.1", }) def preview_allowed(config, kind): try: endpoint = "preview?kind=attention" if kind == "attention" else "preview" with build_opener(RejectRedirect()).open(relay_request(config, endpoint), timeout=1.5) as response: return response.status == 204 except HTTPError as error: error.close() except (URLError, OSError, http.client.HTTPException): pass return False def deliver(config, payload): request = relay_request(config, "event", payload) # The host's HTTPS proxy can carry the connection. TLS still validates the # relay, and redirects must never send the host key to another origin. opener = build_opener(RejectRedirect()) try: with opener.open(request, timeout=5) as response: if response.status == 204: return True except HTTPError as error: error.close() if error.code == 401: return False if error.code < 500 and error.code not in (408, 429): raise RejectedEvent("Relay rejected event") from None except (URLError, OSError, http.client.HTTPException): pass raise RuntimeError("Relay temporarily unavailable") class RejectedEvent(RuntimeError): pass def read_settings(config): with os.fdopen(os.open(config, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)) as stream: info = os.fstat(stream.fileno()) if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077: raise ValueError("Private pairing file required") return json.load(stream) def credential_id(settings): return hashlib.sha256((settings.get("relay", "") + "\0" + settings.get("key", "")).encode()).hexdigest() def outbox_table(db): db.execute("""CREATE TABLE IF NOT EXISTS outbox ( id TEXT, config TEXT, credential TEXT, payload TEXT, created REAL, attempts INTEGER, due REAL, PRIMARY KEY(id, config))""") def drain_outbox(path, limit=4): database = path.with_suffix(".sqlite") # No state creation on an unpaired/idle host. if not database.is_file(): return None for _ in range(limit): now = time.time() with contextlib.closing(sqlite3.connect(database, timeout=2)) as db, db: db.execute("BEGIN IMMEDIATE") outbox_table(db) db.execute("DELETE FROM outbox WHERE created <= ? OR attempts >= 9", (now - 900,)) row = db.execute("SELECT id, config, credential, payload, attempts FROM outbox WHERE due <= ? ORDER BY due LIMIT 1", (now,)).fetchone() if row: event_id, name, credential, payload, attempts = row # Lease each item; other hook/worker processes cannot send it concurrently. db.execute("UPDATE outbox SET attempts = attempts + 1, due = ? WHERE id = ? AND config = ?", (now + 30, event_id, name)) if not row: break config = path.parent / name remove = True try: if config not in pairing_files(path): continue settings = read_settings(config) if credential_id(settings) != credential: continue if not deliver(settings, json.loads(payload)): config.unlink(missing_ok=True) except RejectedEvent: pass # Invalid events never spin or retry. except RuntimeError: remove = False except (OSError, ValueError, KeyError): pass # Revoked, rotated or corrupt pairing: drop its pending event. finally: with contextlib.closing(sqlite3.connect(database, timeout=2)) as db, db: if remove: db.execute("DELETE FROM outbox WHERE id = ? AND config = ?", (event_id, name)) else: delay = min(300, 2 * 3 ** attempts) db.execute("UPDATE outbox SET due = ? WHERE id = ? AND config = ?", (time.time() + delay, event_id, name)) with contextlib.closing(sqlite3.connect(database, timeout=2)) as db: return db.execute("SELECT MIN(MIN(due, created + 900)) FROM outbox").fetchone()[0] def start_retry(socket_path): env = dict(os.environ, HERDR_SOCKET_PATH=socket_path) env.pop("HERDR_PLUGIN_EVENT_JSON", None) subprocess.Popen([sys.executable, "-I", str(Path(__file__).resolve()), "retry"], env=env, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True, start_new_session=True) def retry_pending(socket_path): path = directory(socket_path) # One sleeping retry worker per Herdr socket, never a resident daemon. descriptor = os.open(path.with_suffix(".retry.lock"), os.O_CREAT | os.O_WRONLY | os.O_NOFOLLOW, 0o600) with os.fdopen(descriptor, "w") as lock: try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: return while pairing_files(path): due = drain_outbox(path, limit=32) if due is None: return time.sleep(max(0.1, due - time.time())) def pairing_files(path): legacy = path.with_suffix(".json") return ([legacy] if legacy.is_file() else []) + sorted(path.parent.glob(path.name + ".*.json")) def handle(socket_path): event = json.loads(os.environ.get("HERDR_PLUGIN_EVENT_JSON", "{}")) if event.get("event") not in ("pane_agent_status_changed", "pane.agent_status_changed"): return data = event["data"] status, pane_id = data["agent_status"], data["pane_id"] if status not in ("working", "blocked", "done", "idle", "unknown"): return path = directory(socket_path) legacy = path.with_suffix(".json") configs = [] for config in pairing_files(path): try: configs.append((config, read_settings(config))) except (OSError, ValueError): continue if not configs: return kind, payload, pane, started = claim_event(path.with_suffix(".sqlite"), socket_path, pane_id, status, configs) if not kind: if drain_outbox(path) is not None: start_retry(socket_path) return # Start the sleeper before any potentially slow preview/network operation. # A hook timeout cannot strand its already committed generic alert. start_retry(socket_path) agent = pane.get("agent") preview = None task = None loaded_content = False for config, settings in configs: try: message = dict(payload) public_key = settings.get("previewKey") if public_key and preview_allowed(settings, kind): if not loaded_content: loaded_content = True task = task_name(socket_path, pane) if started is not None and agent in ("codex", "claude"): try: preview = reply_excerpt(pane, agent, started, socket_path) except (OSError, ValueError, KeyError, TypeError, AttributeError): pass try: if task and (encrypted := encrypt_reply(public_key, payload["eventId"], "task\n" + task)): message["sealedTask"] = encrypted if preview and (encrypted := encrypt_reply(public_key, payload["eventId"], preview)): message["sealedReply"] = encrypted except (OSError, ValueError, TypeError, AttributeError, subprocess.SubprocessError): pass # A preview failure must not prevent the status alert. with contextlib.closing(sqlite3.connect(path.with_suffix(".sqlite"), timeout=2)) as db, db: db.execute("UPDATE outbox SET payload = ?, due = ? WHERE id = ? AND config = ?", (json.dumps(message), time.time(), payload["eventId"], config.name)) except (OSError, ValueError, KeyError, RuntimeError): pass # The atomically queued generic alert remains deliverable. if drain_outbox(path) is not None: start_retry(socket_path) def main(): os.umask(0o077) socket_path = os.environ.get("HERDR_SOCKET_PATH") if not socket_path: raise ValueError("Run setup from a pane in the Herdr session to pair") if sys.argv[1:] == ["pair"]: configure(directory(socket_path)) elif sys.argv[1:] == ["unpair"]: path = directory(socket_path) for config in pairing_files(path): config.unlink(missing_ok=True) path.with_suffix(".sqlite").unlink(missing_ok=True) elif sys.argv[1:] == ["retry"]: retry_pending(socket_path) elif not sys.argv[1:]: handle(socket_path) else: raise ValueError("Unknown command") if __name__ == "__main__": try: main() except RuntimeError: print("MoonSSH could not deliver the event. Check the relay, HTTPS connection, or proxy.", file=sys.stderr) sys.exit(1) except (OSError, ValueError, KeyError, TypeError, sqlite3.Error): # Herdr records command stderr. Never print exceptions containing input. print("MoonSSH push setup could not be read. Check the host pairing.", file=sys.stderr) sys.exit(1)