main
1#!/usr/bin/env python3
2"""Raffi script filter for browsing and controlling a local Herdr session."""
3
4from __future__ import annotations
5
6import base64
7import json
8import os
9import re
10import subprocess
11import sys
12from typing import Any
13
14ANSI_ESCAPE = re.compile(r"\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\))")
15MODES = {
16 "ws": "workspaces",
17 "tab": "tabs",
18 "pane": "panes",
19 "msg": "messages",
20}
21STATUS_ORDER = {"working": 0, "blocked": 1, "idle": 2, "done": 3, "unknown": 4}
22UPSTREAM_FILTER = os.path.join(os.path.dirname(__file__), "herdr", "herdr_filter.py")
23
24
25def parse_query(query: str) -> tuple[str, str]:
26 """Return the requested catalog mode and its remaining search text."""
27 first, _, rest = query.strip().partition(" ")
28 return MODES.get(first, "agents"), rest.strip() if first in MODES else query.strip()
29
30
31def strip_ansi(text: str) -> str:
32 """Remove terminal styling and normalize carriage-return line endings."""
33 return ANSI_ESCAPE.sub("", text).replace("\r\n", "\n").replace("\r", "\n")
34
35
36def run_herdr(*args: str) -> Any:
37 """Run Herdr and return its JSON result payload."""
38 completed = subprocess.run(
39 ["herdr", *args], capture_output=True, text=True, check=False, timeout=5
40 )
41 if completed.returncode:
42 message = completed.stderr.strip() or completed.stdout.strip() or "Herdr command failed"
43 raise RuntimeError(message)
44 try:
45 envelope = json.loads(completed.stdout)
46 return envelope["result"]
47 except (json.JSONDecodeError, KeyError) as error:
48 raise RuntimeError("Herdr returned an invalid response") from error
49
50
51def run_herdr_text(*args: str) -> str:
52 """Run a Herdr terminal-read command that intentionally returns raw text."""
53 completed = subprocess.run(
54 ["herdr", *args], capture_output=True, text=True, check=False, timeout=5
55 )
56 if completed.returncode:
57 message = completed.stderr.strip() or completed.stdout.strip() or "Herdr command failed"
58 raise RuntimeError(message)
59 return completed.stdout
60
61
62def typed_arg(action: str, kind: str, identifier: str) -> str:
63 return f"{action}:{kind}:{identifier}"
64
65
66def parse_arg(value: str) -> tuple[str, str, str]:
67 action, kind, identifier = value.split(":", 2)
68 if action not in {"focus", "message"} or kind not in {
69 "agent",
70 "workspace",
71 "tab",
72 "pane",
73 }:
74 raise ValueError("invalid Herdr Raffi action")
75 return action, kind, identifier
76
77
78def agent_result(agent: dict[str, Any], action: str) -> dict[str, str]:
79 """Render an agent response as one Raffi script-filter item."""
80 pane_id = agent["pane_id"]
81 status = agent.get("agent_status", "unknown")
82 title = agent.get("terminal_title_stripped") or agent.get("terminal_title") or pane_id
83 cwd = agent.get("cwd") or "unknown directory"
84 result: dict[str, Any] = {
85 "title": title,
86 "subtitle": f"{status} — {agent.get('workspace_id', '?')} / {agent.get('tab_id', '?')} / {pane_id} — {cwd}",
87 "arg": pane_id if action == "message" else typed_arg(action, "agent", pane_id),
88 }
89 if action == "message":
90 result["variables"] = {"HERDR_KIND": "agent", "HERDR_FOCUS": pane_id}
91 return result
92
93
94def generic_result(kind: str, item: dict[str, Any]) -> dict[str, str]:
95 identifier = item.get(f"{kind}_id") or item.get("pane_id") or item.get("tab_id") or item["workspace_id"]
96 if kind == "pane":
97 identifier = f"{item['tab_id']}|{item['pane_id']}"
98 title = item.get("label") or item.get("terminal_title_stripped") or identifier
99 subtitle = " — ".join(
100 str(part)
101 for part in (item.get("workspace_id"), item.get("tab_id"), item.get("pane_id"))
102 if part
103 )
104 return {"title": title, "subtitle": subtitle or kind, "arg": typed_arg("focus", kind, identifier)}
105
106
107def contains(item: dict[str, str], query: str) -> bool:
108 if not query:
109 return True
110 haystack = " ".join(item.values()).lower()
111 return all(word in haystack for word in query.lower().split())
112
113
114def list_tabs_or_panes(kind: str) -> list[dict[str, Any]]:
115 workspaces = run_herdr("workspace", "list").get("workspaces", [])
116 items: list[dict[str, Any]] = []
117 for workspace in workspaces:
118 result = run_herdr(kind[:-1], "list", "--workspace", workspace["workspace_id"])
119 items.extend(result.get(kind, []))
120 return items
121
122
123def list_items(mode: str, query: str) -> list[dict[str, str]]:
124 if mode in {"agents", "messages"}:
125 agents = run_herdr("agent", "list").get("agents", [])
126 agents.sort(
127 key=lambda agent: (
128 not agent.get("focused", False),
129 STATUS_ORDER.get(agent.get("agent_status", "unknown"), 99),
130 agent.get("workspace_id", ""),
131 agent.get("tab_id", ""),
132 agent.get("pane_id", ""),
133 )
134 )
135 action = "message" if mode == "messages" else "focus"
136 results = [agent_result(agent, action) for agent in agents]
137 elif mode == "workspaces":
138 results = [
139 generic_result("workspace", item)
140 for item in run_herdr("workspace", "list").get("workspaces", [])
141 ]
142 else:
143 results = [generic_result(mode[:-1], item) for item in list_tabs_or_panes(mode)]
144 return [item for item in results if contains(item, query)]
145
146
147def preview(value: str) -> dict[str, Any]:
148 """Build a dynamic Raffi preview for one selected item."""
149 try:
150 _, kind, identifier = parse_arg(value)
151 if kind != "agent":
152 return {"text": f"{kind}: {identifier}"}
153 agent = run_herdr("agent", "get", identifier).get("agent", {})
154 output = run_herdr_text(
155 "agent", "read", identifier, "--source", "recent-unwrapped", "--lines", "60"
156 )
157 text = strip_ansi(output)
158 metadata = [
159 ["Status", agent.get("agent_status", "unknown")],
160 ["Pane", identifier],
161 ["Directory", agent.get("cwd", "unknown")],
162 ]
163 return {"title": agent.get("terminal_title_stripped", identifier), "text": text, "metadata": metadata}
164 except (RuntimeError, ValueError) as error:
165 return {"title": "Herdr preview unavailable", "text": str(error)}
166
167
168def open_message(identifier: str) -> int:
169 """Open the Emacs composer for an agent pane."""
170 agent = run_herdr("agent", "get", identifier).get("agent", {})
171 payload = base64.b64encode(json.dumps(agent).encode()).decode()
172 expression = f'(vde/herdr-prompt-from-base64 "{payload}")'
173 completed = subprocess.run(["emacsclient", "-a", "emacs", "--eval", expression], check=False)
174 return completed.returncode
175
176
177def run_action(value: str) -> int:
178 """Run the selected focus or compose action."""
179 action, kind, identifier = parse_arg(value)
180 if action == "focus":
181 command = {
182 "agent": ("agent", "focus", identifier),
183 "workspace": ("workspace", "focus", identifier),
184 "tab": ("tab", "focus", identifier),
185 # Herdr has no direct arbitrary-pane focus API; focus its tab.
186 "pane": ("tab", "focus", identifier.split("|", 1)[0]),
187 }[kind]
188 run_herdr(*command)
189 return 0
190
191 return open_message(identifier)
192
193
194def main(argv: list[str]) -> int:
195 if len(argv) >= 3 and argv[:2] == ["action", "message"]:
196 try:
197 return open_message(argv[2])
198 except RuntimeError as error:
199 print(f"herdr-raffi: {error}", file=sys.stderr)
200 return 1
201
202 if len(argv) >= 2 and argv[0] == "action":
203 try:
204 return run_action(argv[1])
205 except (RuntimeError, ValueError) as error:
206 print(f"herdr-raffi: {error}", file=sys.stderr)
207 return 1
208
209 if os.environ.get("RAFFI_PREVIEW") == "1":
210 os.execv(UPSTREAM_FILTER, [UPSTREAM_FILTER])
211
212 if argv and argv[0] == "--message":
213 mode, query = "messages", " ".join(argv[1:]).strip()
214 else:
215 mode, query = parse_query(" ".join(argv))
216 try:
217 print(json.dumps({"items": list_items(mode, query)}, ensure_ascii=False))
218 except RuntimeError as error:
219 print(json.dumps({"items": [{"title": "Herdr unavailable", "subtitle": str(error), "arg": ""}]}))
220 return 0
221
222
223if __name__ == "__main__":
224 raise SystemExit(main(sys.argv[1:]))