""" Tool execution utilities. Intercepts terminal commands to enforce --project usage for 'uv' in ephemeral environments. """ import asyncio import json from contextlib import suppress from typing import Any from acp.schema import ( TerminalToolCallContent, ToolCallLocation, ToolCallProgress, ToolCallStart, ToolKind, ) from fastmcp import Client as MCPClient from mcp.types import ( ImageContent, TextContent, ) from crow_cli.acp_helpers import ( image_block, start_edit_tool_call, start_read_tool_call, start_tool_call, text_block, tool_content, tool_diff_content, update_tool_call, ) from crow_cli.agent.context import TurnCtx def tool_match(tool_name: str, terms: tuple[str]) -> bool: return any([x in tool_name.lower() for x in terms]) def get_tool_kind(tool_name: str) -> ToolKind: """Map tool names to ACP ToolKind.""" # Orchestration tools: exact-match first so the substring rules below don't # misclassify them (task_read->read, task_write->edit, send_prompt->execute). if tool_name in ("send_prompt", "task", "task_read", "task_write", "task_send"): return "other" # Common MCP tool patterns if tool_match(tool_name, ("read_file", "read", "view", "list_directory", "list")): return "read" elif tool_match( tool_name, ("write_file", "write", "edit", "create", "str_replace") ): return "edit" elif tool_match(tool_name, ("delete", "remove")): return "delete" elif tool_match(tool_name, ("move", "rename")): return "move" elif tool_match(tool_name, ("search", "grep", "find")): return "search" elif tool_match(tool_name, ("fetch", "download")): return "fetch" elif tool_match(tool_name, ("terminal", "bash", "shell", "execute", "prompt")): return "execute" else: return "other" def mcp_content_to_acp_blocks( mcp_content: list[TextContent | ImageContent], ) -> list: """ Convert MCP content blocks to ACP content blocks. Handles TextContent and ImageContent from MCP protocol and converts them to appropriate ACP content blocks. Args: mcp_content: List of content blocks from MCP CallToolResult Returns: List of ACP tool content blocks wrapped with tool_content() """ acp_blocks = [] for item in mcp_content: if isinstance(item, TextContent): acp_blocks.append(tool_content(text_block(item.text))) elif isinstance(item, ImageContent): # MCP uses mimeType (camelCase), ACP uses mime_type (snake_case) acp_blocks.append( tool_content(image_block(data=item.data, mime_type=item.mimeType)) ) else: # Fallback: try to extract text if possible if hasattr(item, "text"): acp_blocks.append(tool_content(text_block(str(item.text)))) elif hasattr(item, "data"): # Binary data as string representation acp_blocks.append(tool_content(text_block(str(item.data)))) else: # Last resort: convert entire object to string acp_blocks.append(tool_content(text_block(str(item)))) return acp_blocks def mcp_content_to_openai_format( mcp_content: list[TextContent | ImageContent], ) -> list | str: """ Convert MCP content blocks to OpenAI-compatible content format. Returns a list of content blocks (text + images) so the LLM can see images returned by MCP tools (e.g. vision/capture tools). Args: mcp_content: List of content blocks from MCP CallToolResult Returns: List of OpenAI content blocks, or plain string if only text. """ if not mcp_content: return "" blocks = [] for item in mcp_content: if isinstance(item, TextContent): blocks.append({"type": "text", "text": item.text}) elif isinstance(item, ImageContent): blocks.append( { "type": "image_url", "image_url": {"url": f"data:{item.mimeType};base64,{item.data}"}, } ) else: # Fallback: convert to text text = getattr(item, "text", str(item)) blocks.append({"type": "text", "text": text}) # If only one text block, return plain string for compatibility if len(blocks) == 1 and blocks[0]["type"] == "text": return blocks[0]["text"] return blocks async def _terminal_via_mcp( ctx: TurnCtx, mcp_clients: dict[str, MCPClient], acp_tool_call_id: str, args: dict[str, Any], ) -> str: """The no-client-capability backend: the MCP `terminal` tool. Same reporting contract as the ACP-terminal path — in_progress, then completed/failed with the tool's content — but execution (and the shell's working directory) belongs to the MCP server. The session cwd and id ride the call's `_meta`: arguments the LLM never derived and cannot forge, the same channel the task tool uses. """ conn, logger = ctx.conn, ctx.logger session_id = ctx.session_id await conn.session_update( session_id=session_id, update=update_tool_call(acp_tool_call_id, status="in_progress"), ) logger.info( f"No client terminal capability — executing terminal via MCP " f"in {ctx.cwd} (session {session_id})" ) mcp_client = mcp_clients.get(session_id) if not mcp_client: raise RuntimeError(f"No MCP client for session {session_id}") result = await mcp_client.call_tool( "terminal", args, meta={"cwd": ctx.cwd, "session_id": session_id} ) acp_content_blocks = mcp_content_to_acp_blocks(result.content) result_content = mcp_content_to_openai_format(result.content) status = "completed" if not getattr(result, "isError", False) else "failed" await conn.session_update( session_id=session_id, update=update_tool_call( acp_tool_call_id, status=status, content=acp_content_blocks, ), ) return result_content async def execute_acp_terminal( ctx: TurnCtx, mcp_clients: dict[str, MCPClient], tool_call_id: str, args: dict[str, Any], ) -> str: """ Execute terminal command — the ONE terminal handler. The ACP tool-call lifecycle (start → in_progress → completed with the content ACP expects) is identical either way; only the execution backend branches on the client's advertised capability: - Client declared terminal support → the ACP client-side terminal (`terminal/create` with the session cwd, live `Terminal` content, `wait_for_terminal_exit`, release). - No capability → the MCP `terminal` tool, with the session cwd and id riding the call's `_meta` (the model never sees them) so shells run in the session's working directory instead of the MCP server's process cwd. Client-side terminal capabilities are on their way out (v2), so this is the path that survives. Args: ctx: Turn context — conn, wire session id, cwd, logger, command hooks mcp_clients: Per-session MCP clients (the no-capability backend) tool_call_id: LLM tool call ID args: Tool arguments from LLM Returns: Result string with output and status """ conn, logger = ctx.conn, ctx.logger command = args.get("command", "") timeout_seconds = float(args.get("timeout") or 30.0) acp_tool_call_id = ctx.tcid(tool_call_id) session_id = ctx.session_id cwd = ctx.cwd terminal_id: str | None = None timed_out = False try: # 1. Send tool call start await conn.session_update( session_id=session_id, update=ToolCallStart( session_update="tool_call", tool_call_id=acp_tool_call_id, title=command, name="terminal", kind="execute", status="pending", ), ) # --- Command hooks: pre-execution guards --- # Ephemeral terminals do not persist cwd or env — hooks enforce policies. for hook in ctx.hooks: rejection = hook(command) if rejection is not None: return rejection if not ctx.terminal_via_client: return await _terminal_via_mcp(ctx, mcp_clients, acp_tool_call_id, args) # 2. Create terminal via ACP client logger.info(f"Creating ACP terminal for command: {command}") terminal_response = await conn.create_terminal( command=command, session_id=session_id, cwd=cwd, output_byte_limit=100000, # 100KB limit ) terminal_id = terminal_response.terminal_id logger.info(f"Terminal created: {terminal_id}") # 3. Send tool call update with terminal content for live display await conn.session_update( session_id=session_id, update=ToolCallProgress( session_update="tool_call_update", tool_call_id=acp_tool_call_id, status="in_progress", content=[ TerminalToolCallContent( type="terminal", terminal_id=terminal_id, ) ], ), ) # 4. Wait for terminal to exit with timeout exit_code = None exit_signal = None try: async with asyncio.timeout(timeout_seconds): exit_response = await conn.wait_for_terminal_exit( session_id=session_id, terminal_id=terminal_id, ) exit_code = exit_response.exit_code exit_signal = exit_response.signal logger.info( f"Terminal exited with code: {exit_code}, signal: {exit_signal}" ) except TimeoutError: logger.warning(f"Terminal timed out after {timeout_seconds}s") timed_out = True await conn.kill_terminal(session_id=session_id, terminal_id=terminal_id) # 5. Get final output output_response = await conn.terminal_output( session_id=session_id, terminal_id=terminal_id ) output = output_response.output truncated_note = " Output was truncated." if output_response.truncated else "" # 6. Send final tool call update final_status = ( "failed" if (exit_code and exit_code != 0) or exit_signal or timed_out else "completed" ) await conn.session_update( session_id=session_id, update=ToolCallProgress( session_update="tool_call_update", tool_call_id=acp_tool_call_id, status=final_status, ), ) # 7. Build result message if timed_out: return f"⏱️ Command killed by timeout ({timeout_seconds}s){truncated_note}\n\nOutput:\n{output}" elif exit_signal: return f"⚠️ Command terminated by signal: {exit_signal}{truncated_note}\n\nOutput:\n{output}" elif exit_code not in (None, 0): return f"❌ Command failed with exit code: {exit_code}{truncated_note}\n\nOutput:\n{output}" else: if truncated_note: return f"{output}\n\n{truncated_note.strip()}" return output except Exception as e: logger.error(f"Error executing ACP terminal: {e}", exc_info=True) return f"Error: {str(e)}" finally: # 8. Release terminal if created if terminal_id: with suppress(Exception): await conn.release_terminal( session_id=session_id, terminal_id=terminal_id ) logger.info(f"Released terminal: {terminal_id}") async def execute_acp_write( ctx: TurnCtx, tool_call_id: str, args: dict[str, Any] ) -> str: """ Write file via ACP client filesystem. Args: ctx: Turn context — conn, wire session id, logger, snapshot hooks tool_call_id: LLM tool call ID args: Tool arguments from LLM (file_path, content) Returns: Success message """ conn, logger = ctx.conn, ctx.logger path = args.get("file_path", "") content = args.get("content", "") # maximal_deserialize may have decoded JSON strings into dicts/lists. # If content is not a string, serialize it back so write_text_file works. if not isinstance(content, str): content = json.dumps(content, ensure_ascii=False, indent=2) session_id = ctx.session_id acp_tool_call_id = ctx.tcid(tool_call_id) # Pre-hook: capture before state for Monaco diffs if path and ctx.snapshot_hooks: for hook in ctx.snapshot_hooks: hook(ctx.session, acp_tool_call_id, "write", path, logger) try: # 1. Send tool call start title = f"write: {path}" await conn.session_update( session_id=session_id, update=start_edit_tool_call( tool_call_id=acp_tool_call_id, title=title, path=path, content=content, name="write", ), ) # 2. Send in_progress update with diff content await conn.session_update( session_id=session_id, update=update_tool_call( acp_tool_call_id, status="in_progress", content=[tool_diff_content(path=path, new_text=content)], ), ) # 3. Write file via ACP client logger.info(f"Writing file via ACP: {path}") await conn.write_text_file( session_id=session_id, path=path, content=content, ) # 4. Send completion update await conn.session_update( session_id=session_id, update=update_tool_call(acp_tool_call_id, status="completed"), ) return f"Successfully wrote to {path}" except Exception as e: logger.error(f"Error writing file via ACP: {e}", exc_info=True) # Send failed status await conn.session_update( session_id=session_id, update=update_tool_call(acp_tool_call_id, status="failed"), ) return f"Error writing file: {str(e)}" async def execute_acp_read( ctx: TurnCtx, tool_call_id: str, args: dict[str, Any] ) -> str: """ Read file via ACP client filesystem. Args: ctx: Turn context — conn, wire session id, logger tool_call_id: LLM tool call ID args: Tool arguments from LLM (file_path, offset, limit) Returns: File contents with line numbers """ conn, logger = ctx.conn, ctx.logger path = args.get("file_path", "") offset = args.get("offset", 1) limit = args.get("limit", 4000) session_id = ctx.session_id acp_tool_call_id = ctx.tcid(tool_call_id) try: # 1. Send tool call start title = f"read: {path}" await conn.session_update( session_id=session_id, update=start_read_tool_call( tool_call_id=acp_tool_call_id, title=title, path=path, name="read", ), ) # 2. Send in_progress update await conn.session_update( session_id=session_id, update=update_tool_call(acp_tool_call_id, status="in_progress"), ) # 3. Read file via ACP client logger.info(f"Reading file via ACP: {path}") response = await conn.read_text_file( session_id=session_id, path=path, line=offset, limit=limit, ) content = response.content or "" # 4. Send completion update with file content await conn.session_update( session_id=session_id, update=update_tool_call( acp_tool_call_id, status="completed", content=[tool_content(text_block(content))], ), ) return content except Exception as e: logger.error(f"Error reading file via ACP: {e}", exc_info=True) # Send failed status await conn.session_update( session_id=session_id, update=update_tool_call(acp_tool_call_id, status="failed"), ) return f"Error reading file: {str(e)}" async def execute_acp_edit( ctx: TurnCtx, mcp_clients: dict[str, MCPClient], tool_call_id: str, args: dict[str, Any] ) -> str: """ Edit file with fuzzy matching, sending diff content to ACP client. This executes the edit locally (fuzzy matching is agent-side) but sends proper diff content for the client to display. Args: ctx: Turn context — conn, wire session id, logger, snapshot hooks mcp_clients: Per-wire-session MCP clients (the edit tool runs there) tool_call_id: LLM tool call ID args: Tool arguments from LLM (file_path, old_string, new_string, replace_all) Returns: Result string from the edit operation """ conn, logger = ctx.conn, ctx.logger path = args.get("file_path", "") old_text = args.get("old_string", "") new_text = args.get("new_string", "") session_id = ctx.session_id acp_tool_call_id = ctx.tcid(tool_call_id) # Pre-hook: capture before state for Monaco diffs if path and ctx.snapshot_hooks: for hook in ctx.snapshot_hooks: hook(ctx.session, acp_tool_call_id, "edit", path, logger) try: # 1. Send tool call start title = f"edit: {path}" await conn.session_update( session_id=session_id, update=start_edit_tool_call( tool_call_id=acp_tool_call_id, title=title, path=path, content=new_text, name="edit", ), ) # 2. Send in_progress update with diff content await conn.session_update( session_id=session_id, update=update_tool_call( acp_tool_call_id, status="in_progress", content=[ tool_diff_content(path=path, new_text=new_text, old_text=old_text) ], ), ) # 3. Execute edit via local MCP tool (fuzzy matching is agent-side) logger.info(f"Executing edit via MCP: {path}") mcp_client = mcp_clients.get(session_id) if not mcp_client: raise RuntimeError(f"No MCP client for session {session_id}") result = await mcp_client.call_tool("edit", args) result_content = result.content[0].text # 4. Send completion update status = "completed" if "Error" not in result_content else "failed" await conn.session_update( session_id=session_id, update=update_tool_call(acp_tool_call_id, status=status), ) return result_content except Exception as e: logger.error(f"Error executing edit: {e}", exc_info=True) await conn.session_update( session_id=session_id, update=update_tool_call(acp_tool_call_id, status="failed"), ) return f"Error: {str(e)}" async def execute_acp_task( ctx: TurnCtx, mcp_clients: dict[str, MCPClient], tool_call_id: str, args: dict[str, Any] ) -> str: """ Execute the `task` tool with the calling session's wire id attached. The MCP-side tool's Context param is filtered out of the LLM schema; the model supplies only `updates`, and the owner session rides the call's _meta — attribution passes through the function call, never the environment, and the model can neither see nor forge it. Args: ctx: Turn context — conn, wire session id, logger mcp_clients: Per-session MCP clients tool_call_id: LLM tool call ID args: Tool arguments from LLM (updates) Returns: Result string from the tool """ conn, logger = ctx.conn, ctx.logger session_id = ctx.session_id acp_tool_call_id = ctx.tcid(tool_call_id) try: await conn.session_update( session_id=session_id, update=ToolCallStart( session_update="tool_call", tool_call_id=acp_tool_call_id, title="task", name="task", kind="other", status="pending", ), ) await conn.session_update( session_id=session_id, update=update_tool_call(acp_tool_call_id, status="in_progress"), ) logger.info(f"Executing task tool via MCP for session {session_id}") mcp_client = mcp_clients.get(session_id) if not mcp_client: raise RuntimeError(f"No MCP client for session {session_id}") result = await mcp_client.call_tool( "task", args, meta={"session_id": session_id} ) acp_content_blocks = mcp_content_to_acp_blocks(result.content) result_content = mcp_content_to_openai_format(result.content) status = "completed" if not getattr(result, "isError", False) else "failed" await conn.session_update( session_id=session_id, update=update_tool_call( acp_tool_call_id, status=status, content=acp_content_blocks, ), ) return result_content except Exception as e: logger.error(f"Error executing task tool: {e}", exc_info=True) await conn.session_update( session_id=session_id, update=update_tool_call(acp_tool_call_id, status="failed"), ) return f"Error: {str(e)}" async def execute_acp_execute( ctx: TurnCtx, mcp_clients: dict[str, MCPClient], tool_call_id: str, args: dict[str, Any], ) -> str: """Execute Python in the persistent kernel — the MCP `execute` tool. Same reporting contract as the other MCP-backed tools (in_progress, then completed/failed with content). The session cwd and id ride the call's `_meta` so the kernel is keyed per session and starts in the session's working directory — arguments the LLM never derived and cannot forge, the same channel terminal and task use. """ conn, logger = ctx.conn, ctx.logger session_id = ctx.session_id acp_tool_call_id = ctx.tcid(tool_call_id) # The code the LLM sent, fenced for markdown rendering — attached at start # so the user sees what will run before the cell finishes. The client # merges update fields over the start, so the completion update must # re-include it or its content would clobber this one. code = str(args.get("code", "")) code_block = tool_content(text_block(f"```python\n{code}\n```")) try: await conn.session_update( session_id=session_id, update=ToolCallStart( session_update="tool_call", tool_call_id=acp_tool_call_id, title="execute", name="execute", kind="execute", status="pending", content=[code_block], ), ) await conn.session_update( session_id=session_id, update=update_tool_call(acp_tool_call_id, status="in_progress"), ) logger.info(f"Executing execute tool via MCP for session {session_id}") mcp_client = mcp_clients.get(session_id) if not mcp_client: raise RuntimeError(f"No MCP client for session {session_id}") result = await mcp_client.call_tool( "execute", args, meta={ "cwd": ctx.cwd, "session_id": session_id, "tool_call_id": acp_tool_call_id, "db_uri": ctx.config.db_uri, "images_dir": _images_dir(ctx.config), # Delegation depth, so an in-cell rlm knows whether it is # allowed to delegate at all. Derived from the session's own # persisted prompt_args, never from the model's arguments. "rlm_depth": ctx.session.rlm_depth, }, ) # Tools called INSIDE the cell wrote themselves through to # subtool_calls; the drain emits each as its OWN ACP tool call — # diff content, args, locations — so the client sees every file the # code touched. It returns the LLM channel: hydrated image_url # blocks PREPENDED to execute's text, the one addition to what the # cell printed. image_blocks = await _emit_subtool_calls(ctx, acp_tool_call_id) acp_content_blocks = mcp_content_to_acp_blocks(result.content) result_content = mcp_content_to_openai_format(result.content) if image_blocks: if isinstance(result_content, str): result_content = [{"type": "text", "text": result_content}] result_content = [*image_blocks, *result_content] status = "completed" if not getattr(result, "isError", False) else "failed" await conn.session_update( session_id=session_id, update=update_tool_call( acp_tool_call_id, status=status, content=[code_block, *acp_content_blocks], ), ) return result_content except Exception as e: logger.error(f"Error executing execute tool: {e}", exc_info=True) # A cell that died halfway still made real edits — rows were written # through at call time, so the drain works even on a wedged kernel. await _emit_subtool_calls(ctx, acp_tool_call_id) await conn.session_update( session_id=session_id, update=update_tool_call(acp_tool_call_id, status="failed"), ) return f"Error: {str(e)}" def _images_dir(config) -> str: """Session ImageStore directory — same derivation as agent/memory.py: sqlite -> beside the db file; other backends -> beside the config.""" from pathlib import Path db_uri = config.db_uri or "" if db_uri.startswith("sqlite:///"): return str(Path(db_uri.removeprefix("sqlite:///")).parent / "images") return str(Path(config.config_dir) / "images") _KIND_BY_RESULT: dict[str, ToolKind] = { "diff": "edit", "read": "read", "search": "search", # Rows read out of the agent's own memory. The mode cannot decide this # one either: get_tool_kind("list") is "read" and get_tool_kind("search") # is "search", but all three modes are the same artifact — rows from a # connection that is read-only at the OS level. "memory": "read", # A multi-file replace modifies files, so it is an edit-kind call even # though its own payload is the summary text (the per-file diffs ride # their own rows). Decided here rather than by get_tool_kind's substring # rules: those classify "rewrite" as an edit only because it happens to # contain "write", and "sub" does not. "rewrite": "edit", # A page read, whether httpx fetched it or a browser rendered it. The # mode name cannot decide this one: get_tool_kind("fetch") is "fetch" # but get_tool_kind("run") is "other", and a browser loading a URL is # the same artifact either way. "web": "fetch", # A delegation — a fork of the calling session, asked one question. The # name decides nothing here: get_tool_kind("rlm") matches no substring # rule and falls to "other", but the artifact is reasoning the agent paid # for out of a fork instead of out of its own context, which is "think". "rlm": "think", } """ACP kind follows the ARTIFACT, not the tool name: a multi-mode tool (``fs``) is one name doing read/glob/search, and ``get_tool_kind("fs")`` is "other". Rows whose result_kind isn't an artifact shape (image, text, error) fall back to the mode, then the tool.""" def _subtool_id(ctx: TurnCtx, row_id: int) -> str: """Synthetic ACP toolCallId for a call made inside an execute cell. Shaped like every other id on the wire (``/call_...``) so the client renders it as the tool call it stands for; the row id keeps it deterministic and collision-free. One row is one call. A tool that touches N files records N rows — that is what fs rewrite does, by calling write() per changed file — so the artifacts land where the diffs already live instead of megabytes of whole files going into a single row. """ return ctx.tcid(f"call_sub{row_id}") async def _emit_subtool_call( ctx: TurnCtx, sub_id: str, row: Any, title: str, kind: ToolKind, *, path: str | None = None, content: list | None = None, ) -> None: """Put one in-cell tool call on the wire. Three beats, the same ones crow sends for a real edit/write call: pending (carrying the args the code passed as ``rawInput`` plus the file location), in_progress with the artifact (diff / image / error text), then the final status. The client cannot tell this from a call the LLM made — which is the point: the user sees every file the code touched. """ status = "completed" if row.status == "completed" else "failed" try: await ctx.conn.session_update( session_id=ctx.session_id, update=start_tool_call( sub_id, title, name=row.tool, kind=kind, status="pending", locations=[ToolCallLocation(path=path)] if path else None, raw_input=row.args or None, ), ) await ctx.conn.session_update( session_id=ctx.session_id, update=update_tool_call(sub_id, status="in_progress", content=content), ) await ctx.conn.session_update( session_id=ctx.session_id, update=update_tool_call(sub_id, status=status), ) except Exception: ctx.logger.warning(f"subtool emission failed: {sub_id}", exc_info=True) def _hydrate_images(ctx: TurnCtx, row, llm_blocks: list[dict], store: Any): """(ACP image content, store) for one row's llm_images refs. Hoisted out of the image branch because images are orthogonal to the payload's shape: a vision call is ALL image, while a browser call is the rendered page PLUS a screenshot — one call, one row, two artifacts. The LLM's image_url blocks are appended to ``llm_blocks`` either way, since that prepend is the only channel a vision model can see through. """ if not row.llm_images: return [], store import base64 if store is None: from pathlib import Path from crow_cli.memory.image_store import resolve_image_store store = resolve_image_store( ctx.config.image_store.get("s3"), Path(_images_dir(ctx.config)), ) blocks = [] for ref in row.llm_images: data = store.get(ref.get("key", "")) if data is None: ctx.logger.warning(f"image blob missing: {ref.get('key')}") continue mime = ref.get("mime", "image/png") b64 = base64.b64encode(data).decode() blocks.append(tool_content(image_block(data=b64, mime_type=mime))) llm_blocks.append( { "type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}, } ) return blocks, store async def _emit_subtool_calls(ctx: TurnCtx, parent_acp_id: str) -> list[dict]: """Drain subtool_calls recorded by tools inside an execute cell and emit each as its OWN ACP tool call — the client's view of the work the code did, even though the LLM only ever called execute. Two channels, deliberately different: * ACP gets the pretty face — one synthetic tool call per artifact, shaped exactly like a real edit/write call (kind, title, locations, ``rawInput`` = the args the code passed, content = the diff / image / error text) so the client renders a diff view per file changed. * The LLM gets NONE of this. It sees execute's stdout and, when a vision tool ran, the hydrated image_url blocks this returns for the caller to PREPEND. Subtools are code, not conversation. Lineage lives in the table (parent_tool_call_id); ACP v1 has no parent field on the wire, so the synthetic ids carry the turn prefix like every other call and the row id keeps them deterministic and collision-free. Rows were written through from the kernel at call time (the table is the queue), so this works even if the kernel wedged mid-cell. """ if not ctx.config.db_uri: return [] try: from sqlalchemy import select from sqlalchemy import update as sa_update from crow_cli.memory.db import get_engine from crow_cli.memory.models import SubtoolCall engine = get_engine(ctx.config.db_uri) try: with engine.begin() as conn: rows = list( conn.execute( select(SubtoolCall) .where( SubtoolCall.parent_tool_call_id == parent_acp_id, SubtoolCall.emitted == 0, ) .order_by(SubtoolCall.id) ) ) if rows: conn.execute( sa_update(SubtoolCall) .where(SubtoolCall.id.in_([r.id for r in rows])) .values(emitted=1) ) finally: engine.dispose() except Exception: ctx.logger.warning("subtool drain failed", exc_info=True) return [] llm_blocks: list[dict] = [] store = None # resolved lazily — only image rows touch the store for row in rows: payload = row.acp_payload or {} kind = _KIND_BY_RESULT.get(row.result_kind) or get_tool_kind( row.mode or row.tool ) title = f"{row.tool}/{row.mode}" if row.mode else row.tool blocks, store = _hydrate_images(ctx, row, llm_blocks, store) if row.result_kind == "diff": path = payload.get("path", "") await _emit_subtool_call( ctx, _subtool_id(ctx, row.id), row, title=f"{row.tool}: {path}", kind=kind, path=path, content=[ tool_diff_content( path=path, new_text=payload.get("new_text", ""), old_text=payload.get("old_text"), ) ], ) elif row.result_kind == "read": # Mirrors execute_acp_read: a read-kind call located at the # file, carrying the text the code read. path = payload.get("path", "") text = payload.get("text", "") await _emit_subtool_call( ctx, _subtool_id(ctx, row.id), row, title=f"{title}: {path}", kind=kind, path=path, content=[tool_content(text_block(text))] if text else None, ) elif row.result_kind == "image": await _emit_subtool_call( ctx, _subtool_id(ctx, row.id), row, title=title, kind=kind, content=blocks or None, ) else: text = payload.get("text") or ( f"{title} failed: {row.error}" if row.status == "failed" else "" ) # A result may name its own SUBJECT — a URL, a query — and the # title reads better carrying it. Deliberately not "path": a # subject is displayed, never claimed as a location, because a # page is not a file. subject = payload.get("subject") content = [tool_content(text_block(text))] if text else [] await _emit_subtool_call( ctx, _subtool_id(ctx, row.id), row, title=f"{title}: {subject}" if subject else title, kind=kind, content=(content + blocks) or None, ) return llm_blocks async def execute_acp_tool( ctx: TurnCtx, mcp_clients: dict[str, MCPClient], tool_call_id: str, tool_name: str, args: dict[str, Any], ) -> str: """ Execute a generic tool via MCP and report with content. Used for tools like search, fetch, etc. that return text content to display to the user. Args: ctx: Turn context — conn, wire session id, logger mcp_clients: Per-session MCP clients tool_call_id: LLM tool call ID tool_name: Name of the MCP tool to call args: Tool arguments from LLM Returns: Result string from the tool """ conn, logger = ctx.conn, ctx.logger session_id = ctx.session_id acp_tool_call_id = ctx.tcid(tool_call_id) kind: ToolKind = get_tool_kind(tool_name) try: # 1. Send tool call start title = f"{tool_name}" await conn.session_update( session_id=session_id, update=ToolCallStart( session_update="tool_call", tool_call_id=acp_tool_call_id, title=title, name=tool_name, kind=kind, status="pending", ), ) # 2. Send in_progress update await conn.session_update( session_id=session_id, update=update_tool_call(acp_tool_call_id, status="in_progress"), ) # 3. Execute tool via MCP logger.info(f"Executing tool via MCP: {tool_name}") mcp_client = mcp_clients.get(session_id) if not mcp_client: raise RuntimeError(f"No MCP client for session {session_id}") result = await mcp_client.call_tool(tool_name, args) # Convert MCP content to ACP content blocks (for client display) acp_content_blocks = mcp_content_to_acp_blocks(result.content) # Convert MCP content to OpenAI format (for LLM tool response) # This preserves images so the LLM can see them result_content = mcp_content_to_openai_format(result.content) # 4. Send completion update with content status = "completed" if not getattr(result, "isError", False) else "failed" await conn.session_update( session_id=session_id, update=update_tool_call( acp_tool_call_id, status=status, content=acp_content_blocks, ), ) return result_content except Exception as e: logger.error(f"Error executing tool {tool_name}: {e}", exc_info=True) await conn.session_update( session_id=session_id, update=update_tool_call(acp_tool_call_id, status="failed"), ) return f"Error: {str(e)}"