|
| 1 | +"""Claude Code agent adapter — uses the `claude` CLI with JSON streaming.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import json |
| 7 | +import uuid |
| 8 | +from typing import AsyncIterator |
| 9 | + |
| 10 | +from engram_bridge.agents.base import AgentMessage, BaseAgent |
| 11 | +from engram_bridge.config import AgentConfig |
| 12 | + |
| 13 | + |
| 14 | +class ClaudeAgent(BaseAgent): |
| 15 | + """Runs Claude Code via subprocess, reading NDJSON streaming output.""" |
| 16 | + |
| 17 | + def __init__(self, config: AgentConfig): |
| 18 | + self._model = config.model or "claude-opus-4-6" |
| 19 | + self._allowed_tools = config.allowed_tools |
| 20 | + self._session_id: str | None = None |
| 21 | + self._proc: asyncio.subprocess.Process | None = None |
| 22 | + |
| 23 | + @property |
| 24 | + def name(self) -> str: |
| 25 | + return "claude-code" |
| 26 | + |
| 27 | + @property |
| 28 | + def is_running(self) -> bool: |
| 29 | + return self._proc is not None and self._proc.returncode is None |
| 30 | + |
| 31 | + async def send( |
| 32 | + self, message: str, cwd: str, session_id: str | None = None |
| 33 | + ) -> AsyncIterator[AgentMessage]: |
| 34 | + sid = session_id or self._session_id or uuid.uuid4().hex[:12] |
| 35 | + self._session_id = sid |
| 36 | + |
| 37 | + cmd = [ |
| 38 | + "claude", "--json", |
| 39 | + "--model", self._model, |
| 40 | + "--print", # non-interactive mode |
| 41 | + "--output-format", "stream-json", |
| 42 | + ] |
| 43 | + if self._allowed_tools: |
| 44 | + cmd += ["--allowedTools", ",".join(self._allowed_tools)] |
| 45 | + if session_id: |
| 46 | + cmd += ["--resume", session_id] |
| 47 | + cmd += ["-p", message] |
| 48 | + |
| 49 | + try: |
| 50 | + self._proc = await asyncio.create_subprocess_exec( |
| 51 | + *cmd, |
| 52 | + stdout=asyncio.subprocess.PIPE, |
| 53 | + stderr=asyncio.subprocess.PIPE, |
| 54 | + cwd=cwd, |
| 55 | + ) |
| 56 | + except FileNotFoundError: |
| 57 | + yield AgentMessage( |
| 58 | + "error", |
| 59 | + "Claude CLI not found. Install it: npm install -g @anthropic-ai/claude-code", |
| 60 | + sid, {}, |
| 61 | + ) |
| 62 | + return |
| 63 | + |
| 64 | + collected_text: list[str] = [] |
| 65 | + |
| 66 | + async for line in self._proc.stdout: |
| 67 | + line = line.decode("utf-8", errors="replace").strip() |
| 68 | + if not line: |
| 69 | + continue |
| 70 | + try: |
| 71 | + event = json.loads(line) |
| 72 | + except json.JSONDecodeError: |
| 73 | + # Plain text fallback |
| 74 | + collected_text.append(line) |
| 75 | + continue |
| 76 | + |
| 77 | + msg = self._parse_event(event, sid) |
| 78 | + if msg: |
| 79 | + if msg.type == "text": |
| 80 | + collected_text.append(msg.content) |
| 81 | + yield msg |
| 82 | + |
| 83 | + await self._proc.wait() |
| 84 | + |
| 85 | + # If process failed, read stderr |
| 86 | + if self._proc.returncode and self._proc.returncode != 0: |
| 87 | + stderr = await self._proc.stderr.read() |
| 88 | + err = stderr.decode("utf-8", errors="replace").strip() |
| 89 | + if "rate" in err.lower() or "429" in err: |
| 90 | + yield AgentMessage("rate_limited", err, sid, {}) |
| 91 | + else: |
| 92 | + yield AgentMessage("error", err or f"Exit code {self._proc.returncode}", sid, {}) |
| 93 | + |
| 94 | + # Emit final combined text if we got plain output |
| 95 | + if collected_text and not any(True for _ in []): |
| 96 | + # The text messages were already yielded above |
| 97 | + pass |
| 98 | + |
| 99 | + self._proc = None |
| 100 | + |
| 101 | + def _parse_event(self, event: dict, sid: str) -> AgentMessage | None: |
| 102 | + """Parse a JSON streaming event from Claude CLI.""" |
| 103 | + etype = event.get("type", "") |
| 104 | + |
| 105 | + if etype == "assistant" or etype == "result": |
| 106 | + # Final or intermediate text |
| 107 | + content = event.get("result", "") or event.get("content", "") |
| 108 | + if isinstance(content, list): |
| 109 | + # content blocks |
| 110 | + texts = [b.get("text", "") for b in content if b.get("type") == "text"] |
| 111 | + content = "\n".join(texts) |
| 112 | + new_sid = event.get("session_id", sid) |
| 113 | + if new_sid: |
| 114 | + self._session_id = new_sid |
| 115 | + if content: |
| 116 | + return AgentMessage("text", content, self._session_id or sid, {}) |
| 117 | + |
| 118 | + elif etype == "tool_use": |
| 119 | + tool = event.get("name", event.get("tool", "unknown")) |
| 120 | + inp = event.get("input", {}) |
| 121 | + display = f"Using {tool}..." |
| 122 | + if "file_path" in inp: |
| 123 | + display = f"{tool}: {inp['file_path']}" |
| 124 | + elif "command" in inp: |
| 125 | + cmd_str = inp["command"] |
| 126 | + if len(cmd_str) > 80: |
| 127 | + cmd_str = cmd_str[:77] + "..." |
| 128 | + display = f"{tool}: {cmd_str}" |
| 129 | + return AgentMessage("tool_use", display, self._session_id or sid, {"tool": tool, "input": inp}) |
| 130 | + |
| 131 | + elif etype == "tool_result": |
| 132 | + content = event.get("content", "") |
| 133 | + if isinstance(content, list): |
| 134 | + content = "\n".join(b.get("text", "") for b in content if isinstance(b, dict)) |
| 135 | + return AgentMessage("tool_result", content[:500], self._session_id or sid, {}) |
| 136 | + |
| 137 | + elif etype == "error": |
| 138 | + msg = event.get("error", {}).get("message", str(event)) |
| 139 | + if "rate" in msg.lower() or "429" in msg: |
| 140 | + return AgentMessage("rate_limited", msg, self._session_id or sid, {}) |
| 141 | + return AgentMessage("error", msg, self._session_id or sid, {}) |
| 142 | + |
| 143 | + return None |
| 144 | + |
| 145 | + async def stop(self) -> None: |
| 146 | + if self._proc and self._proc.returncode is None: |
| 147 | + self._proc.terminate() |
| 148 | + try: |
| 149 | + await asyncio.wait_for(self._proc.wait(), timeout=5.0) |
| 150 | + except asyncio.TimeoutError: |
| 151 | + self._proc.kill() |
| 152 | + self._proc = None |
0 commit comments