""" Crow ACP Client - A transparent, observable agent client. This is our microscope. Our Frankenstein monitor. Full visibility into: - AgentSession state (database) - Message flow (what we send/receive) - Agent behavior (logs, tool calls) Usage: # Single-shot mode (default) - send prompt, get response, exit crow-client "list the files in this directory" # Interactive mode - REPL loop crow-client -i # Load existing session crow-client -s lumpy-energetic-hyrax-of-opportunity-77bcbd # Combine flags crow-client -i -s exuberant-grinning-nautilus-of-sunshine-9d3d35 # Inspect database crow-client inspect crow-client inspect --session lumpy-energetic-hyrax-of-opportunity-77bcbd """ import asyncio import json import sys import uuid from datetime import datetime, timezone from pathlib import Path from typing import Any from acp import ( PROTOCOL_VERSION, Client, RequestError, connect_to_agent, ) from acp.core import ClientSideConnection from acp.schema import ( AgentMessageChunk, AgentThoughtChunk, AudioContentBlock, ClientCapabilities, CreateTerminalResponse, EmbeddedResourceContentBlock, ImageContentBlock, Implementation, KillTerminalResponse, PermissionOption, ReadTextFileResponse, ReleaseTerminalResponse, ResourceContentBlock, TerminalExitStatus, TerminalOutputResponse, TextContentBlock, ToolCall, ToolCallProgress, ToolCallStart, UsageUpdate, WaitForTerminalExitResponse, WriteTextFileResponse, ) from crow_cli import __version__ from crow_cli.acp_helpers import text_block from crow_cli.client.subagent import spawn_agent_process, spawn_argv_process from crow_cli.client.terminal import TerminalManager from rich.console import Console from rich.panel import Panel from rich.table import Table from rich.text import Text # Tool kind -> icon mapping TOOL_ICONS = { "read": "📖", "edit": "✏ïļ", "write": "📝", "delete": "🗑ïļ", "move": "ðŸ“Ķ", "search": "🔍", "fetch": "🌐", "execute": "⚡", "other": "🔧", } # Status -> indicator mapping STATUS_ICONS = { "pending": "âģ", "in_progress": "🔄", "completed": "✅", "failed": "❌", } class CrowClient(Client): """ Minimal ACP client that streams agent output beautifully. """ _last_chunk: AgentMessageChunk | AgentThoughtChunk | None = None _console: Console _tool_calls: dict[str, dict] = {} # Track tool call metadata by ID _task_list: list[dict] = [] def __init__(self, console: Console): self._console = console self._task_list = [] self._terminals = TerminalManager() self._json_mode = False self._json_pending: tuple[str, list[str]] | None = None # -- JSONL output (-j): one event per line, pipeable to jq -- def _emit_json(self, **event: Any) -> None: print(json.dumps(event), flush=True) def _buffer_json(self, kind: str, text: str) -> None: if self._json_pending is None or self._json_pending[0] != kind: self._flush_json() self._json_pending = (kind, []) self._json_pending[1].append(text) def _flush_json(self) -> None: if self._json_pending: kind, parts = self._json_pending self._emit_json(type=kind, text="".join(parts)) self._json_pending = None async def request_permission( self, options: list[PermissionOption], session_id: str, tool_call: ToolCall, **kwargs: Any, ) -> Any: raise RequestError.method_not_found("session/request_permission") async def write_text_file( self, content: str, path: str, session_id: str, **kwargs: Any ) -> WriteTextFileResponse | None: raise RequestError.method_not_found("fs/write_text_file") async def read_text_file( self, path: str, session_id: str, **kwargs: Any ) -> ReadTextFileResponse: raise RequestError.method_not_found("fs/read_text_file") async def session_update( self, session_id: str, update: AgentMessageChunk | AgentThoughtChunk | ToolCallStart | ToolCallProgress, **kwargs: Any, ) -> None: """Handle streaming updates from the agent.""" if self._json_mode: if isinstance(update, AgentMessageChunk): self._buffer_json("message", self._extract_text(update.content)) elif isinstance(update, AgentThoughtChunk): self._buffer_json("thinking", self._extract_text(update.content)) elif isinstance(update, ToolCallStart): self._flush_json() self._emit_json( type="tool_call", event="start", tool_call_id=getattr(update, "tool_call_id", None), title=update.title, kind=update.kind, status=update.status, ) elif isinstance(update, ToolCallProgress): self._flush_json() self._emit_json( type="tool_call", event="progress", tool_call_id=getattr(update, "tool_call_id", None), title=update.title, kind=update.kind, status=update.status, ) elif isinstance(update, UsageUpdate): self._flush_json() self._emit_json(type="usage", used=update.used, size=update.size) return if isinstance(update, AgentMessageChunk): if ( self._last_chunk is None or isinstance(self._last_chunk, AgentThoughtChunk) or isinstance(self._last_chunk, (ToolCallStart, ToolCallProgress)) ): # Transition to message output self._console.print() self._console.rule("[bold purple]Assistant[/bold purple]") self._console.print() self._last_chunk = update content = update.content text = self._extract_text(content) self._console.print(text, end="", style="purple", highlight=False) elif isinstance(update, AgentThoughtChunk): if ( self._last_chunk is None or isinstance(self._last_chunk, AgentMessageChunk) or isinstance(self._last_chunk, (ToolCallStart, ToolCallProgress)) ): # Transition to thinking output self._console.print() self._console.rule("[dim green]Thinking[/dim green]") self._console.print() self._last_chunk = update content = update.content text = self._extract_text(content) self._console.print(text, end="", style="dim green italic", highlight=False) elif isinstance(update, ToolCallStart): # Tool call started self._last_chunk = update icon = TOOL_ICONS.get(update.kind, TOOL_ICONS["other"]) status = STATUS_ICONS.get(update.status, "âģ") self._console.print(f"\n{status} {icon} {update.title}", style="cyan") elif isinstance(update, ToolCallProgress): # Tool call progress/completion self._last_chunk = update icon = TOOL_ICONS.get(update.kind, TOOL_ICONS["other"]) status = STATUS_ICONS.get(update.status, "âģ") style = ( "green" if update.status == "completed" else "red" if update.status == "failed" else "yellow" ) self._console.print( f"{status} {icon} {update.title or 'tool'}", style=style ) def _extract_text(self, content: Any) -> str: """Extract text from various content block types.""" if isinstance(content, TextContentBlock): return content.text elif isinstance(content, ImageContentBlock): return "" elif isinstance(content, AudioContentBlock): return "