CLI for SidePulse
Python
Add Cursor as a hook provider (#35)
Colby1afa8fe69407
diff --git a/src/sidepulse/cli.py b/src/sidepulse/cli.pyindex 6beb235..ca8f460 100644--- a/src/sidepulse/cli.py+++ b/src/sidepulse/cli.py@@ -22,9 +22,11 @@ from .hook import hook_log_mainfrom .install import (install_claude_hooks,install_codex_hooks,+ install_cursor_hooks,install_grok_hooks,uninstall_claude_hooks,uninstall_codex_hooks,+ uninstall_cursor_hooks,uninstall_grok_hooks,)from .led_status import AgentLedController, LedStatusWrite@@ -143,6 +145,7 @@ def add_hook_log_parser(subparsers: argparse._SubParsersAction) -> None:hook_log = subparsers.add_parser("hook-log", help="Internal hook logging entry point.")hook_log.add_argument("--provider", choices=HOOK_PROVIDERS, required=True)hook_log.add_argument("--log", type=Path, required=True)+ hook_log.add_argument("--event", help="Provider-native lifecycle event name (used by cursor).")hook_log.set_defaults(func=cmd_hook_log)@@ -816,6 +819,8 @@ def install_hook_results(args: argparse.Namespace):results.append(install_codex_hooks(log_path=log_path, dry_run=args.dry_run))elif provider == "claude":results.append(install_claude_hooks(log_path=log_path, dry_run=args.dry_run))+ elif provider == "cursor":+ results.append(install_cursor_hooks(log_path=log_path, dry_run=args.dry_run))else:results.append(install_grok_hooks(log_path=log_path, dry_run=args.dry_run))return results@@ -842,6 +847,8 @@ def cmd_uninstall(args: argparse.Namespace) -> int:results.append(uninstall_codex_hooks(log_path=log_path, dry_run=args.dry_run))elif provider == "claude":results.append(uninstall_claude_hooks(log_path=log_path, dry_run=args.dry_run))+ elif provider == "cursor":+ results.append(uninstall_cursor_hooks(log_path=log_path, dry_run=args.dry_run))else:results.append(uninstall_grok_hooks(log_path=log_path, dry_run=args.dry_run))@@ -858,7 +865,7 @@ def cmd_uninstall(args: argparse.Namespace) -> int:def cmd_hook_log(args: argparse.Namespace) -> int:- return hook_log_main(args.provider, args.log)+ return hook_log_main(args.provider, args.log, event=getattr(args, "event", None))def monitor_from_args(args: argparse.Namespace) -> AgentMonitor:diff --git a/src/sidepulse/cursor_hook.py b/src/sidepulse/cursor_hook.pynew file mode 100644index 0000000..7b4c19e--- /dev/null+++ b/src/sidepulse/cursor_hook.py@@ -0,0 +1,104 @@+"""Adapt Cursor lifecycle hooks to SidePulse events."""++from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path+from typing import Any++from .hook import routed_hook_payload, write_hook_line, write_hook_status_audit+from .ipc import send_hook_event+++EVENT_ALIASES = {+ "sessionStart": "SessionStart",+ "sessionEnd": "SessionEnd",+ "beforeSubmitPrompt": "UserPromptSubmit",+ "preToolUse": "PreToolUse",+ "beforeShellExecution": "PreToolUse",+ "afterShellExecution": "PostToolUse",+ "afterFileEdit": "PostToolUse",+ "postToolUse": "PostToolUse",+ "postToolUseFailure": "StopFailure",+ "stop": "Stop",+}+++def normalize_payload(event_name: str, payload: dict[str, Any]) -> dict[str, Any]:+ normalized = dict(payload)+ normalized["hook_event_name"] = EVENT_ALIASES.get(event_name, event_name)+ normalized["session_id"] = str(+ payload.get("conversation_id") or payload.get("conversationId") or ""+ )+ normalized["agent_origin"] = "Cursor"+ normalized["agent_origin_kind"] = "cursor_app"+ normalized["agent_origin_source"] = "hook:cursor"+ normalized["agent_origin_confidence"] = "explicit"++ workspace_roots = payload.get("workspace_roots") or payload.get("workspaceRoots")+ if isinstance(workspace_roots, list) and workspace_roots:+ normalized["cwd"] = str(workspace_roots[0])+ elif payload.get("workspace_root"):+ normalized["cwd"] = str(payload["workspace_root"])++ prompt = payload.get("prompt")+ if isinstance(prompt, str):+ normalized["prompt"] = prompt++ if event_name in {"beforeShellExecution", "preToolUse"}:+ normalized["tool_name"] = str(payload.get("tool_name") or "shell")+ normalized["tool_input"] = payload.get("tool_input") or {+ "command": payload.get("command")+ }+ elif event_name in {+ "afterShellExecution",+ "afterFileEdit",+ "postToolUse",+ "postToolUseFailure",+ }:+ normalized["tool_name"] = str(payload.get("tool_name") or event_name)+ normalized["tool_response"] = {+ "status": payload.get("status"),+ "exit_code": payload.get("exit_code"),+ "error": payload.get("error_message"),+ }++ if event_name == "postToolUseFailure" and payload.get("error_message"):+ normalized["message"] = str(payload["error_message"])++ status = payload.get("status")+ if event_name == "stop" and isinstance(status, str):+ normalized["message"] = f"Cursor stopped: {status}"++ return normalized+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(add_help=False)+ parser.add_argument("--event", required=True)+ parser.add_argument("--log", required=True, type=Path)+ args = parser.parse_args(argv)++ try:+ raw = json.loads(sys.stdin.read() or "{}")+ payload = raw if isinstance(raw, dict) else {}+ normalized = normalize_payload(args.event, payload)+ provider, log_path, line = routed_hook_payload(+ "cursor",+ args.log.expanduser(),+ json.dumps(normalized, separators=(",", ":"), ensure_ascii=False),+ )+ send_hook_event(provider, line)+ write_hook_line(log_path, line)+ write_hook_status_audit(provider, line)+ except Exception:+ pass++ sys.stdout.write("{}\n")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/src/sidepulse/hook.py b/src/sidepulse/hook.pyindex aa7120c..82a1a23 100644--- a/src/sidepulse/hook.py+++ b/src/sidepulse/hook.py@@ -105,12 +105,24 @@ def hook_event_socket_disabled() -> bool:}-def hook_log_main(provider: str, log_path: Path) -> int:+def hook_log_main(provider: str, log_path: Path, event: str | None = None) -> int:try:+ payload_text = sys.stdin.read()+ if provider == "cursor" and event:+ from .cursor_hook import normalize_payload++ try:+ raw = json.loads(payload_text or "{}")+ except json.JSONDecodeError:+ raw = {}+ payload = raw if isinstance(raw, dict) else {}+ normalized = normalize_payload(event, payload)+ payload_text = json.dumps(normalized, separators=(",", ":"), ensure_ascii=False)+actual_provider, actual_log_path, line = routed_hook_payload(provider,log_path,- sys.stdin.read(),+ payload_text,)if not hook_event_socket_disabled():send_hook_event(actual_provider, line)diff --git a/src/sidepulse/hook_entry.py b/src/sidepulse/hook_entry.pyindex ac24efc..02f77db 100644--- a/src/sidepulse/hook_entry.py+++ b/src/sidepulse/hook_entry.py@@ -1,4 +1,4 @@-"""Process entry point for Codex, Claude, and Grok hooks."""+"""Process entry point for supported SidePulse agent hooks."""from __future__ import annotations@@ -24,7 +24,14 @@ def main(argv: list[str] | None = None) -> int:except (ValueError, IndexError):return 0- return _load_hook_main()(provider, log_path)+ event = None+ if "--event" in args:+ try:+ event = args[args.index("--event") + 1]+ except IndexError:+ event = None++ return _load_hook_main()(provider, log_path, event=event)if __name__ == "__main__":diff --git a/src/sidepulse/install.py b/src/sidepulse/install.pyindex cafbbe8..4d5669b 100644--- a/src/sidepulse/install.py+++ b/src/sidepulse/install.py@@ -18,7 +18,9 @@ from typing import Anyfrom .providers import (CLAUDE_EVENTS,CODEX_EVENTS,+ CURSOR_EVENTS,GROK_EVENTS,+ default_cursor_hook_config_path,default_grok_hook_config_path,detect_log_path,)@@ -280,6 +282,142 @@ def uninstall_grok_hooks(return InstallResult("grok", config, target_log, changed, backup, dry_run)+def install_cursor_hooks(+ log_path: Path | None = None,+ config_path: Path | None = None,+ dry_run: bool = False,+ python_executable: str | None = None,+) -> InstallResult:+ config = config_path or default_cursor_hook_config_path()+ target_log = (log_path or detect_log_path("cursor")).expanduser()+ data = read_json_config(config)+ original = json.dumps(data, sort_keys=True)+ data.setdefault("version", 1)+ hooks = data.setdefault("hooks", {})++ for event_name in CURSOR_EVENTS:+ entries = hooks.get(event_name, [])+ if not isinstance(entries, list):+ entries = []+ # Anything we did not write -- including entries in a shape a future+ # Cursor release introduces -- is preserved untouched.+ cleaned = remove_cursor_hook_entries(entries)+ cleaned.append(+ {+ "command": cursor_hook_command(+ event_name,+ target_log,+ python_executable,+ )+ }+ )+ hooks[event_name] = cleaned++ changed = json.dumps(data, sort_keys=True) != original+ backup = None+ if changed and not dry_run:+ config.parent.mkdir(parents=True, exist_ok=True)+ backup = backup_file(config)+ config.write_text(json.dumps(data, indent=2, sort_keys=False) + "\n")+ target_log.parent.mkdir(parents=True, exist_ok=True)+ target_log.touch(exist_ok=True)++ return InstallResult("cursor", config, target_log, changed, backup, dry_run)+++def uninstall_cursor_hooks(+ log_path: Path | None = None,+ config_path: Path | None = None,+ dry_run: bool = False,+) -> InstallResult:+ config = config_path or default_cursor_hook_config_path()+ target_log = (log_path or detect_log_path("cursor")).expanduser()+ data = read_json_config(config)+ original = json.dumps(data, sort_keys=True)+ hooks = data.get("hooks")+ if isinstance(hooks, dict):+ for event_name in list(hooks):+ entries = hooks.get(event_name)+ if not isinstance(entries, list):+ continue+ cleaned = remove_cursor_hook_entries(entries)+ if cleaned:+ hooks[event_name] = cleaned+ else:+ hooks.pop(event_name, None)+ if not hooks:+ data.pop("hooks", None)++ changed = json.dumps(data, sort_keys=True) != original+ backup = None+ if changed and not dry_run:+ config.parent.mkdir(parents=True, exist_ok=True)+ backup = backup_file(config)+ # Only remove the file if nothing of the user's is left in it.+ if data:+ config.write_text(json.dumps(data, indent=2, sort_keys=False) + "\n")+ else:+ try:+ config.unlink()+ except FileNotFoundError:+ pass++ return InstallResult("cursor", config, target_log, changed, backup, dry_run)+++def cursor_hook_command(+ event_name: str,+ log_path: Path,+ python_executable: str | None = None,+) -> str:+ executable = python_executable or sys.executable or "python3"+ if getattr(sys, "frozen", False) and python_executable is None:+ command = " ".join(+ [+ shlex.quote(executable),+ "agent-monitor",+ "hook-log",+ "--provider",+ "cursor",+ "--event",+ shlex.quote(event_name),+ "--log",+ shlex.quote(str(log_path.expanduser())),+ ]+ )+ return fail_open_command(command)+ entry_point = Path(__file__).with_name("hook_entry.py")+ command = " ".join(+ [+ shlex.quote(executable),+ shlex.quote(str(entry_point)),+ "--provider",+ "cursor",+ "--event",+ shlex.quote(event_name),+ "--log",+ shlex.quote(str(log_path.expanduser())),+ ]+ )+ return fail_open_command(command)+++def remove_cursor_hook_entries(entries: list[Any]) -> list[Any]:+ """Drop entries this installer wrote, in any generation's spelling."""+ return [+ entry+ for entry in entries+ if not (+ isinstance(entry, dict)+ and (+ "sidepulse.cursor_hook" in str(entry.get("command") or "")+ or "agent-monitor hook-log" in str(entry.get("command") or "")+ or "hook_entry.py" in str(entry.get("command") or "")+ )+ )+ ]++def hook_command(provider: str,log_path: Path,diff --git a/src/sidepulse/providers.py b/src/sidepulse/providers.pyindex 60942c3..516ec6c 100644--- a/src/sidepulse/providers.py+++ b/src/sidepulse/providers.py@@ -61,7 +61,20 @@ GROK_EVENTS = ("SessionEnd",)-HOOK_PROVIDERS = ("codex", "claude", "grok")+CURSOR_EVENTS = (+ "sessionStart",+ "sessionEnd",+ "beforeSubmitPrompt",+ "preToolUse",+ "beforeShellExecution",+ "afterShellExecution",+ "afterFileEdit",+ "postToolUse",+ "postToolUseFailure",+ "stop",+)++HOOK_PROVIDERS = ("codex", "claude", "grok", "cursor")KNOWN_EVENTS = tuple(dict.fromkeys(CODEX_EVENTS + CLAUDE_EVENTS + GROK_EVENTS))@@ -116,7 +129,12 @@ def default_log_path(provider: str, home: Path | None = None) -> Path:def detect_provider_configs(home: Path | None = None) -> list[ProviderConfig]:- return [detect_codex_config(home), detect_claude_config(home), detect_grok_config(home)]+ return [+ detect_codex_config(home),+ detect_claude_config(home),+ detect_grok_config(home),+ detect_cursor_config(home),+ ]def detect_codex_config(home: Path | None = None) -> ProviderConfig:@@ -258,6 +276,65 @@ def detect_grok_config(home: Path | None = None) -> ProviderConfig:)+def default_cursor_hook_config_path(home: Path | None = None) -> Path:+ base = home or Path.home()+ return base / ".cursor" / "hooks.json"+++def detect_cursor_config(home: Path | None = None) -> ProviderConfig:+ config_path = default_cursor_hook_config_path(home)+ if not config_path.exists():+ return ProviderConfig("cursor", config_path, False, False, (), ())++ try:+ data = json.loads(config_path.read_text())+ except Exception:+ return ProviderConfig("cursor", config_path, True, False, (), ())++ hooks = data.get("hooks") or {}+ hook_events: list[str] = []+ paths: list[Path] = []+ if isinstance(hooks, dict):+ for event_name, entries in hooks.items():+ if event_name not in CURSOR_EVENTS or not isinstance(entries, list):+ continue+ managed_entries = [+ entry+ for entry in entries+ if isinstance(entry, dict)+ and (+ "sidepulse.cursor_hook" in str(entry.get("command") or "")+ or "agent-monitor hook-log" in str(entry.get("command") or "")+ or "hook_entry.py" in str(entry.get("command") or "")+ )+ ]+ if managed_entries:+ hook_events.append(event_name)+ paths.extend(_paths_from_cursor_entries(managed_entries))++ return ProviderConfig(+ "cursor",+ config_path,+ True,+ bool(hook_events),+ tuple(sorted(set(hook_events))),+ _dedupe_paths(paths),+ )+++def _paths_from_cursor_entries(entries: list[Any]) -> list[Path]:+ """Cursor stores a flat ``{"command": ...}`` per entry, not a nested list."""+ paths: list[Path] = []+ for entry in entries:+ if not isinstance(entry, dict):+ continue+ command = entry.get("command")+ if isinstance(command, str):+ paths.extend(extract_log_paths_from_command(command))+ paths.extend(_paths_from_hook_entries([entry]))+ return paths++def detect_log_path(provider: str, home: Path | None = None) -> Path:if provider == "codex":config = detect_codex_config(home)@@ -265,6 +342,8 @@ def detect_log_path(provider: str, home: Path | None = None) -> Path:config = detect_claude_config(home)elif provider == "grok":config = detect_grok_config(home)+ elif provider == "cursor":+ config = detect_cursor_config(home)else:config = ProviderConfig(provider, default_log_path(provider, home), False, False, (), ())if config.log_paths:diff --git a/tests/test_cursor_provider.py b/tests/test_cursor_provider.pynew file mode 100644index 0000000..f448a85--- /dev/null+++ b/tests/test_cursor_provider.py@@ -0,0 +1,152 @@+from __future__ import annotations++import json+import tempfile+import unittest+from datetime import datetime, timezone+from pathlib import Path++from sidepulse.collector import AgentMonitor, SourceSpec+from sidepulse.cursor_hook import normalize_payload+from sidepulse.install import install_cursor_hooks, uninstall_cursor_hooks+from sidepulse.models import AgentMode+from sidepulse.providers import detect_cursor_config+++class CursorProviderTests(unittest.TestCase):+ def test_installer_preserves_existing_hooks(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ home = Path(tmp)+ config = home / ".cursor" / "hooks.json"+ config.parent.mkdir(parents=True)+ config.write_text(+ json.dumps(+ {+ "version": 1,+ "hooks": {"stop": [{"command": "python notify.py"}]},+ }+ )+ )+ log = home / "state" / "cursor.jsonl"++ install_cursor_hooks(+ config_path=config,+ log_path=log,+ python_executable="python3",+ )++ data = json.loads(config.read_text())+ stop_commands = [entry["command"] for entry in data["hooks"]["stop"]]+ self.assertIn("python notify.py", stop_commands)+ # Cursor routes through the shared hook_entry dispatcher, like every+ # other provider, so the hook keeps working when sidepulse is not on+ # the interpreter's import path.+ self.assertTrue(any("hook_entry.py" in item for item in stop_commands))+ self.assertTrue(any("--provider cursor" in item for item in stop_commands))+ self.assertTrue(any("--event stop" in item for item in stop_commands))+ detected = detect_cursor_config(home)+ self.assertTrue(detected.hooks_enabled)+ self.assertEqual(detected.log_paths, (log,))++ def test_uninstaller_removes_only_sidepulse_hooks(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ config = root / "hooks.json"+ log = root / "cursor.jsonl"+ config.write_text(+ json.dumps(+ {+ "version": 1,+ "hooks": {"stop": [{"command": "python notify.py"}]},+ }+ )+ )+ install_cursor_hooks(config_path=config, log_path=log)++ uninstall_cursor_hooks(config_path=config, log_path=log)++ data = json.loads(config.read_text())+ self.assertEqual(data["hooks"]["stop"], [{"command": "python notify.py"}])+ self.assertFalse(+ any(+ "sidepulse.cursor_hook" in str(entry.get("command") or "")+ for entries in data["hooks"].values()+ for entry in entries+ )+ )++ def test_installer_preserves_unknown_hook_entries(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ config = root / "hooks.json"+ log = root / "cursor.jsonl"+ config.write_text(+ json.dumps({"version": 1, "hooks": {"stop": ["future-hook"]}})+ )++ install_cursor_hooks(config_path=config, log_path=log)++ self.assertIn("future-hook", json.loads(config.read_text())["hooks"]["stop"])++ def test_prompt_and_stop_map_to_working_then_completed(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ log = Path(tmp) / "cursor.jsonl"+ now = datetime.now(timezone.utc).isoformat()+ prompt = normalize_payload(+ "beforeSubmitPrompt",+ {+ "conversation_id": "cursor-conversation",+ "workspace_roots": ["/tmp/project"],+ "prompt": "fix the test",+ },+ )+ prompt["logged_at"] = now+ stopped = normalize_payload(+ "stop",+ {"conversation_id": "cursor-conversation", "status": "completed"},+ )+ stopped["logged_at"] = now+ log.write_text(json.dumps(prompt) + "\n" + json.dumps(stopped) + "\n")++ snapshot = AgentMonitor(+ sources=(SourceSpec("cursor", log),),+ stale_after_seconds=3600,+ ).snapshot()++ self.assertEqual(snapshot.aggregate.mode, AgentMode.COMPLETED)+ self.assertEqual(snapshot.statuses[0].origin, "Cursor")++ def test_shell_hook_maps_to_tool_activity(self) -> None:+ normalized = normalize_payload(+ "beforeShellExecution",+ {"conversation_id": "cursor-conversation", "command": "pytest"},+ )+ self.assertEqual(normalized["hook_event_name"], "PreToolUse")+ self.assertEqual(normalized["tool_name"], "shell")++ def test_generic_tool_hooks_map_to_activity_and_failure(self) -> None:+ before = normalize_payload(+ "preToolUse",+ {+ "conversation_id": "cursor-conversation",+ "tool_name": "read_file",+ "tool_input": {"path": "README.md"},+ },+ )+ failed = normalize_payload(+ "postToolUseFailure",+ {+ "conversation_id": "cursor-conversation",+ "tool_name": "read_file",+ "error_message": "permission denied",+ },+ )++ self.assertEqual(before["hook_event_name"], "PreToolUse")+ self.assertEqual(before["tool_name"], "read_file")+ self.assertEqual(failed["hook_event_name"], "StopFailure")+ self.assertEqual(failed["message"], "permission denied")+++if __name__ == "__main__":+ unittest.main()