|
| 1 | +"""Claude code bot implementations |
| 2 | +
|
| 3 | +Useful links: |
| 4 | +
|
| 5 | +* https://github.com/anthropics/claude-code |
| 6 | +* https://docs.anthropic.com/en/docs/claude-code/sdk/sdk-python |
| 7 | +""" |
| 8 | + |
| 9 | +from collections.abc import Mapping |
| 10 | +import dataclasses |
| 11 | +import logging |
| 12 | +from typing import Any |
| 13 | + |
| 14 | +import claude_code_sdk as sdk |
| 15 | + |
| 16 | +from ..common import UnreachableError, reindent |
| 17 | +from .common import ActionSummary, Bot, Goal, UserFeedback, Worktree |
| 18 | + |
| 19 | + |
| 20 | +_logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +def new_bot() -> Bot: |
| 24 | + return _Bot() |
| 25 | + |
| 26 | + |
| 27 | +_PROMPT_SUFFIX = reindent(""" |
| 28 | + ALWAYS use the feedback's MCP server ask_user tool if you need to request |
| 29 | + any information from the user. NEVER repeat yourself by also asking your |
| 30 | + question to the user in other ways. |
| 31 | +""") |
| 32 | + |
| 33 | + |
| 34 | +class _Bot(Bot): |
| 35 | + def __init__(self) -> None: |
| 36 | + self._options = sdk.ClaudeCodeOptions( |
| 37 | + allowed_tools=["Read", "Write", "mcp__feedback__ask_user"], |
| 38 | + permission_mode="bypassPermissions", # TODO: Tighten |
| 39 | + append_system_prompt=_PROMPT_SUFFIX, |
| 40 | + ) |
| 41 | + |
| 42 | + async def act( |
| 43 | + self, goal: Goal, tree: Worktree, feedback: UserFeedback |
| 44 | + ) -> ActionSummary: |
| 45 | + summary = ActionSummary() |
| 46 | + with tree.edit_files() as tree_path: |
| 47 | + options = dataclasses.replace( |
| 48 | + self._options, |
| 49 | + cwd=tree_path, |
| 50 | + mcp_servers={"feedback": _feedback_mcp_server(feedback)}, |
| 51 | + ) |
| 52 | + async with sdk.ClaudeSDKClient(options) as client: |
| 53 | + await client.query(goal.prompt) |
| 54 | + async for msg in client.receive_response(): |
| 55 | + _logger.debug("SDK message: %s", msg) |
| 56 | + match msg: |
| 57 | + case sdk.UserMessage(content): |
| 58 | + _notify(feedback, content) |
| 59 | + case sdk.AssistantMessage(content, _): |
| 60 | + _notify(feedback, content) |
| 61 | + case sdk.ResultMessage() as message: |
| 62 | + # This message's result appears to be identical to |
| 63 | + # the last assistant message's content, so we do |
| 64 | + # not need to show it. |
| 65 | + summary.turn_count = message.num_turns |
| 66 | + summary.cost = message.total_cost_usd |
| 67 | + if usage := message.usage: |
| 68 | + summary.token_count = _token_count(usage) |
| 69 | + summary.usage_details = usage |
| 70 | + case sdk.SystemMessage(): |
| 71 | + pass # TODO: Notify on tool usage? |
| 72 | + return summary |
| 73 | + |
| 74 | + |
| 75 | +def _token_count(usage: Mapping[str, Any]) -> int: |
| 76 | + return ( |
| 77 | + usage["input_tokens"] |
| 78 | + + usage["cache_creation_input_tokens"] |
| 79 | + + usage["cache_read_input_tokens"] |
| 80 | + + usage["output_tokens"] |
| 81 | + ) |
| 82 | + |
| 83 | + |
| 84 | +def _notify( |
| 85 | + feedback: UserFeedback, content: str | list[sdk.ContentBlock] |
| 86 | +) -> None: |
| 87 | + if isinstance(content, str): |
| 88 | + feedback.notify(content) |
| 89 | + return |
| 90 | + |
| 91 | + for block in content: |
| 92 | + match block: |
| 93 | + case sdk.TextBlock(text): |
| 94 | + feedback.notify(text) |
| 95 | + case sdk.ThinkingBlock(thinking, signature): |
| 96 | + feedback.notify(thinking) |
| 97 | + feedback.notify(signature) |
| 98 | + case sdk.ToolUseBlock() | sdk.ToolResultBlock() as block: |
| 99 | + _logger.debug("Using tool: %s", block) |
| 100 | + case _: |
| 101 | + raise UnreachableError() |
| 102 | + |
| 103 | + |
| 104 | +def _feedback_mcp_server(feedback: UserFeedback) -> sdk.McpServerConfig: |
| 105 | + @sdk.tool("ask_user", "Request feedback from the user", {"question": str}) |
| 106 | + async def ask_user(args: Any) -> Any: |
| 107 | + question = args["question"] |
| 108 | + return {"content": [{"type": "text", "text": feedback.ask(question)}]} |
| 109 | + |
| 110 | + return sdk.create_sdk_mcp_server(name="feedback", tools=[ask_user]) |
0 commit comments