diff --git a/cptr/utils/agents/acp.py b/cptr/utils/agents/acp.py index 7870469..76a0754 100644 --- a/cptr/utils/agents/acp.py +++ b/cptr/utils/agents/acp.py @@ -17,7 +17,7 @@ class AcpClient: args: list[str], cwd: str, env: dict[str, str], - auth_method_id: str, + auth_method_id: str | None, client_capabilities: dict[str, Any] | None = None, resume_session_id: str | None = None, auto_approve_permissions: bool = False, @@ -37,6 +37,7 @@ class AcpClient: self.events: asyncio.Queue[dict[str, Any]] = asyncio.Queue() self.next_id = 1 self.session_id: str | None = None + self.initialize_result: dict[str, Any] = {} self.setup_result: dict[str, Any] = {} self.model_config_id: str | None = None @@ -52,7 +53,7 @@ class AcpClient: ) self.reader_task = asyncio.create_task(self._reader_loop()) self.stderr_task = asyncio.create_task(self._stderr_loop()) - await self.request( + self.initialize_result = await self.request( "initialize", { "protocolVersion": 1, @@ -64,7 +65,9 @@ class AcpClient: "clientInfo": {"name": "cptr", "version": "0"}, }, ) - await self.request("authenticate", {"methodId": self.auth_method_id}) + auth_method_id = self.auth_method_id or _first_auth_method(self.initialize_result) + if auth_method_id: + await self.request("authenticate", {"methodId": auth_method_id}) await self._open_session() async def close(self) -> None: @@ -270,6 +273,18 @@ def _extract_model_config_id(setup: dict[str, Any]) -> str | None: return None +def _first_auth_method(initialize_result: dict[str, Any]) -> str | None: + methods = initialize_result.get("authMethods") + if not isinstance(methods, list): + return None + for method in methods: + if isinstance(method, dict): + method_id = method.get("id") + if isinstance(method_id, str) and method_id.strip(): + return method_id.strip() + return None + + def _select_permission_option(params: dict[str, Any], kind: str) -> str | None: options = params.get("options") if not isinstance(options, list): diff --git a/cptr/utils/agents/cline.py b/cptr/utils/agents/cline.py new file mode 100644 index 0000000..ba385d7 --- /dev/null +++ b/cptr/utils/agents/cline.py @@ -0,0 +1,135 @@ +"""Cline ACP adapter.""" + +from __future__ import annotations + +import asyncio +import os +from contextlib import suppress +from typing import Any, AsyncIterator + +from cptr.utils.agents.acp import ( + AcpClient, + acp_event_stream, + acp_text_from_update, + acp_tool_from_update, +) +from cptr.utils.agents.attachments import PreparedAgentAttachments +from cptr.utils.agents.events import ( + AgentDone, + AgentError, + AgentEvent, + AgentTextDelta, + AgentToolUpdate, +) + + +def _prompt_from_messages(messages: list[dict[str, Any]]) -> str: + parts: list[str] = [] + for message in messages: + role = message.get("role", "user") + content = message.get("content", "") + if isinstance(content, list): + text = "\n".join( + str(block.get("text", "")) for block in content if isinstance(block, dict) + ) + else: + text = str(content or "") + if text: + parts.append(f"[{role}]\n{text}") + return "\n\n".join(parts) + + +def _auto_approve(chat_params: dict[str, Any]) -> bool: + if chat_params.get("tool_approval_mode") == "full": + return True + return bool(chat_params.get("auto_approve_tools")) + + +async def run_cline_agent( + *, + profile: dict[str, Any], + model: str, + workspace: str, + messages: list[dict[str, Any]], + system_prompt: str, + chat_params: dict[str, Any], + resume_state: dict[str, Any] | None, + attachments: PreparedAgentAttachments, +) -> AsyncIterator[AgentEvent]: + env = os.environ.copy() + if profile.get("home"): + env["HOME"] = os.path.expanduser(str(profile["home"])) + + session_id = None + if resume_state and isinstance(resume_state.get("session_id"), str): + session_id = resume_state["session_id"] + + client = AcpClient( + command=str(profile["command"]), + args=["--acp"], + cwd=workspace, + env=env, + auth_method_id=None, + resume_session_id=session_id, + auto_approve_permissions=_auto_approve(chat_params), + ) + try: + await client.start() + if model != "default": + await client.set_model(model) + + prompt = _prompt_from_messages(messages) + if system_prompt: + prompt = f"{system_prompt}\n\n{prompt}" if prompt else system_prompt + + images = [ + {"data": image.base64, "mimeType": image.mime_type} for image in attachments.images + ] + prompt_task = asyncio.create_task(client.prompt(prompt, images=images)) + try: + async for event in acp_event_stream(client): + params = event.get("params") if isinstance(event.get("params"), dict) else {} + text = acp_text_from_update(params) + if text: + yield AgentTextDelta(text) + tool = acp_tool_from_update(params) + if tool: + yield AgentToolUpdate(**tool) + if prompt_task.done(): + try: + next_event = await asyncio.wait_for(client.events.get(), timeout=0.25) + except asyncio.TimeoutError: + break + next_params = ( + next_event.get("params") + if isinstance(next_event.get("params"), dict) + else {} + ) + next_text = acp_text_from_update(next_params) + if next_text: + yield AgentTextDelta(next_text) + next_tool = acp_tool_from_update(next_params) + if next_tool: + yield AgentToolUpdate(**next_tool) + await prompt_task + finally: + if not prompt_task.done(): + prompt_task.cancel() + with suppress(asyncio.CancelledError): + await prompt_task + + yield AgentDone( + resume_state={ + "profile_id": profile["id"], + "session_id": client.session_id, + "workspace": workspace, + "model": model, + } + ) + except asyncio.CancelledError: + await client.cancel() + raise + except Exception as exc: # noqa: BLE001 - surfaced in chat. + yield AgentError(str(exc)) + finally: + await client.close()