CLI for SidePulse
Python
Fix lightweight agent hooks and status bar setup
Peter Kuhar733f055f99ad
diff --git a/README.md b/README.mdindex 658bf42..7daf115 100644--- a/README.md+++ b/README.md@@ -163,6 +163,12 @@ Install locally for the `sidepulse` CLI:python3 -m pip install -e .```+To use the macOS status-bar app, install its Cocoa extra:++```sh+python3 -m pip install -e ".[status-bar]"+```+On Homebrew Python, use the user-site install form:```sh@@ -184,6 +190,10 @@ sidepulse agent-monitor install codexsidepulse agent-monitor install claude```+Each hook invokes a small, standard-library-only Python entry point. It writes+the event to the monitor log and then makes a short best-effort local socket+delivery to the status-bar app.+Show current aggregated status:```shdiff --git a/pyproject.toml b/pyproject.tomlindex 0e708e3..5b871ef 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,6 +10,9 @@ readme = "README.md"requires-python = ">=3.10"dependencies = []+[project.optional-dependencies]+status-bar = ["pyobjc-framework-Cocoa>=10"]+[project.scripts]sidepulse = "agent_monitor.cli:sidepulse_main"agent-monitor = "agent_monitor.cli:main"diff --git a/src/agent_monitor/hook_entry.py b/src/agent_monitor/hook_entry.pynew file mode 100644index 0000000..8b545f5--- /dev/null+++ b/src/agent_monitor/hook_entry.py@@ -0,0 +1,28 @@+"""Minimal, dependency-free process entry point for Codex and Claude hooks."""++import json+import os+import socket+import sys+from datetime import datetime, timezone+from pathlib import Path+++provider, log_path = sys.argv[sys.argv.index("--provider") + 1], Path(sys.argv[sys.argv.index("--log") + 1]).expanduser()+try:+ event = json.loads(sys.stdin.read() or "{}")+except json.JSONDecodeError:+ event = {"hook_event_name": "ParseError"}+now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+line = {"logged_at": now, "event": event} if provider == "codex" else dict(event, logged_at=event.get("logged_at", now)) if isinstance(event, dict) else {"logged_at": now, "event": event}+log_path.parent.mkdir(parents=True, exist_ok=True)+with log_path.open("a", encoding="utf-8") as output:+ output.write(json.dumps(line, separators=(",", ":"), ensure_ascii=False) + "\n")+state = Path(os.environ.get("XDG_STATE_HOME", Path.home() / ".local" / "state")) / "sidepulse/agent-monitor/events.sock"+try:+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:+ client.settimeout(0.05)+ client.connect(str(state))+ client.sendall(json.dumps({"provider": provider, "line": line}, separators=(",", ":"), ensure_ascii=False).encode())+except OSError:+ passdiff --git a/src/agent_monitor/install.py b/src/agent_monitor/install.pyindex 094a4a7..c8e8b20 100644--- a/src/agent_monitor/install.py+++ b/src/agent_monitor/install.py@@ -189,19 +189,18 @@ def hook_command(python_executable: str | None = None,) -> str:executable = python_executable or sys.executable or "python3"+ entry_point = Path(__file__).with_name("hook_entry.py")command = " ".join([shlex.quote(executable),- "-m",- "agent_monitor",- "hook-log",+ shlex.quote(str(entry_point)),"--provider",shlex.quote(provider),"--log",shlex.quote(str(log_path.expanduser())),])- return hook_pythonpath_assignment() + command+ return commanddef hook_pythonpath_assignment() -> str:@@ -351,7 +350,7 @@ def resolve_codex_hook_hashes(key = hook.get("key")if hook.get("sourcePath") != source_path:continue- if not isinstance(command, str) or "agent_monitor hook-log" not in command:+ if not isinstance(command, str) or "hook_entry.py" not in command:continueif not isinstance(current_hash, str) or not isinstance(key, str):continue@@ -364,6 +363,7 @@ def codex_cli_path() -> Path | None:candidates = [Path(env_path).expanduser() if env_path else None,Path("/Applications/Codex.app/Contents/Resources/codex"),+ Path("/Applications/ChatGPT.app/Contents/Resources/codex"),Path(shutil.which("codex")).expanduser() if shutil.which("codex") else None,]for candidate in candidates:@@ -422,12 +422,11 @@ def toml_basic_string_escape(value: str) -> str:def strip_managed_block(text: str) -> str:- pattern = re.compile(- rf"^[^\n]*{re.escape(MANAGED_START)}[^\n]*\n.*?"- rf"^[^\n]*{re.escape(MANAGED_END)}[^\n]*\n?",- re.MULTILINE | re.DOTALL,- )- return pattern.sub("", text)+ # Codex may append its own tables between these comments when it rewrites+ # config.toml. Remove only the comments; hook tables are removed below.+ return "\n".join(+ line for line in text.splitlines() if line.strip() not in {MANAGED_START, MANAGED_END}+ ) + ("\n" if text.endswith("\n") else "")def remove_codex_hook_blocks_for_log(text: str, log_path: Path) -> str:@@ -448,7 +447,7 @@ def remove_codex_hook_blocks_for_log(text: str, log_path: Path) -> str:breakend += 1block = "".join(lines[index:end])- if target in block or "agent_monitor hook-log" in block:+ if target in block or "agent_monitor hook-log" in block or "hook_entry.py" in block:index = endcontinue@@ -476,7 +475,7 @@ def remove_claude_hooks_for_log(entries: list[Any], log_path: Path) -> list[dictif not isinstance(hook, dict):continuecommand = hook.get("command", "")- if target in command or "agent_monitor hook-log" in command:+ if target in command or "agent_monitor hook-log" in command or "hook_entry.py" in command:continuecleaned_hooks.append(hook)if cleaned_hooks:diff --git a/tests/test_agent_monitor.py b/tests/test_agent_monitor.pyindex e9c6f47..11874b7 100644--- a/tests/test_agent_monitor.py+++ b/tests/test_agent_monitor.py@@ -304,8 +304,7 @@ class AgentMonitorTests(unittest.TestCase):self.assertIn("hooks = true", text)self.assertIn('[hooks.state]', text)self.assertIn('source = "keep-me"', text)- self.assertIn("agent_monitor", text)- self.assertIn("hook-log", text)+ self.assertIn("hook_entry.py", text)self.assertIn("--provider codex", text)self.assertIn(str(log), text)self.assertNotIn("echo old", text)@@ -404,7 +403,7 @@ class AgentMonitorTests(unittest.TestCase):for hook in entry["hooks"]]self.assertIn("echo keep >> /tmp/other.log", commands)- self.assertTrue(any("agent_monitor" in command for command in commands))+ self.assertTrue(any("hook_entry.py" in command for command in commands))self.assertFalse(any(command.startswith("jq -c") for command in commands))self.assertEqual(data["permissions"]["allow"], ["Bash(date)"])