|
| 1 | +"""Execute configured CLI agents for the clink tool and parse output.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import logging |
| 7 | +import os |
| 8 | +import shlex |
| 9 | +import tempfile |
| 10 | +import time |
| 11 | +from collections.abc import Sequence |
| 12 | +from dataclasses import dataclass |
| 13 | +from pathlib import Path |
| 14 | + |
| 15 | +from clink.constants import DEFAULT_STREAM_LIMIT |
| 16 | +from clink.models import ResolvedCLIClient, ResolvedCLIRole |
| 17 | +from clink.parsers import BaseParser, ParsedCLIResponse, ParserError, get_parser |
| 18 | + |
| 19 | +logger = logging.getLogger("clink.agent") |
| 20 | + |
| 21 | + |
| 22 | +@dataclass |
| 23 | +class AgentOutput: |
| 24 | + """Container returned by CLI agents after successful execution.""" |
| 25 | + |
| 26 | + parsed: ParsedCLIResponse |
| 27 | + sanitized_command: list[str] |
| 28 | + returncode: int |
| 29 | + stdout: str |
| 30 | + stderr: str |
| 31 | + duration_seconds: float |
| 32 | + parser_name: str |
| 33 | + output_file_content: str | None = None |
| 34 | + |
| 35 | + |
| 36 | +class CLIAgentError(RuntimeError): |
| 37 | + """Raised when a CLI agent fails (non-zero exit, timeout, parse errors).""" |
| 38 | + |
| 39 | + def __init__(self, message: str, *, returncode: int | None = None, stdout: str = "", stderr: str = "") -> None: |
| 40 | + super().__init__(message) |
| 41 | + self.returncode = returncode |
| 42 | + self.stdout = stdout |
| 43 | + self.stderr = stderr |
| 44 | + |
| 45 | + |
| 46 | +class BaseCLIAgent: |
| 47 | + """Execute a configured CLI command and parse its output.""" |
| 48 | + |
| 49 | + def __init__(self, client: ResolvedCLIClient): |
| 50 | + self.client = client |
| 51 | + self._parser: BaseParser = get_parser(client.parser) |
| 52 | + self._logger = logging.getLogger(f"clink.runner.{client.name}") |
| 53 | + |
| 54 | + async def run( |
| 55 | + self, |
| 56 | + *, |
| 57 | + role: ResolvedCLIRole, |
| 58 | + prompt: str, |
| 59 | + files: Sequence[str], |
| 60 | + images: Sequence[str], |
| 61 | + ) -> AgentOutput: |
| 62 | + # Files and images are already embedded into the prompt by the tool; they are |
| 63 | + # accepted here only to keep parity with SimpleTool callers. |
| 64 | + _ = (files, images) |
| 65 | + # The runner simply executes the configured CLI command for the selected role. |
| 66 | + command = self._build_command(role=role) |
| 67 | + env = self._build_environment() |
| 68 | + sanitized_command = list(command) |
| 69 | + |
| 70 | + cwd = str(self.client.working_dir) if self.client.working_dir else None |
| 71 | + limit = DEFAULT_STREAM_LIMIT |
| 72 | + |
| 73 | + stdout_text = "" |
| 74 | + stderr_text = "" |
| 75 | + output_file_content: str | None = None |
| 76 | + start_time = time.monotonic() |
| 77 | + |
| 78 | + output_file_path: Path | None = None |
| 79 | + command_with_output_flag = list(command) |
| 80 | + |
| 81 | + if self.client.output_to_file: |
| 82 | + fd, tmp_path = tempfile.mkstemp(prefix="clink-", suffix=".json") |
| 83 | + os.close(fd) |
| 84 | + output_file_path = Path(tmp_path) |
| 85 | + flag_template = self.client.output_to_file.flag_template |
| 86 | + try: |
| 87 | + rendered_flag = flag_template.format(path=str(output_file_path)) |
| 88 | + except KeyError as exc: # pragma: no cover - defensive |
| 89 | + raise CLIAgentError(f"Invalid output flag template '{flag_template}': missing placeholder {exc}") |
| 90 | + command_with_output_flag.extend(shlex.split(rendered_flag)) |
| 91 | + sanitized_command = list(command_with_output_flag) |
| 92 | + |
| 93 | + self._logger.debug("Executing CLI command: %s", " ".join(sanitized_command)) |
| 94 | + if cwd: |
| 95 | + self._logger.debug("Working directory: %s", cwd) |
| 96 | + |
| 97 | + try: |
| 98 | + process = await asyncio.create_subprocess_exec( |
| 99 | + *command_with_output_flag, |
| 100 | + stdin=asyncio.subprocess.PIPE, |
| 101 | + stdout=asyncio.subprocess.PIPE, |
| 102 | + stderr=asyncio.subprocess.PIPE, |
| 103 | + cwd=cwd, |
| 104 | + limit=limit, |
| 105 | + env=env, |
| 106 | + ) |
| 107 | + except FileNotFoundError as exc: |
| 108 | + raise CLIAgentError(f"Executable not found for CLI '{self.client.name}': {exc}") from exc |
| 109 | + |
| 110 | + try: |
| 111 | + stdout_bytes, stderr_bytes = await asyncio.wait_for( |
| 112 | + process.communicate(prompt.encode("utf-8")), |
| 113 | + timeout=self.client.timeout_seconds, |
| 114 | + ) |
| 115 | + except asyncio.TimeoutError as exc: |
| 116 | + process.kill() |
| 117 | + await process.communicate() |
| 118 | + raise CLIAgentError( |
| 119 | + f"CLI '{self.client.name}' timed out after {self.client.timeout_seconds} seconds", |
| 120 | + returncode=None, |
| 121 | + ) from exc |
| 122 | + |
| 123 | + duration = time.monotonic() - start_time |
| 124 | + return_code = process.returncode |
| 125 | + stdout_text = stdout_bytes.decode("utf-8", errors="replace") |
| 126 | + stderr_text = stderr_bytes.decode("utf-8", errors="replace") |
| 127 | + |
| 128 | + if output_file_path and output_file_path.exists(): |
| 129 | + output_file_content = output_file_path.read_text(encoding="utf-8", errors="replace") |
| 130 | + if self.client.output_to_file and self.client.output_to_file.cleanup: |
| 131 | + try: |
| 132 | + output_file_path.unlink() |
| 133 | + except OSError: # pragma: no cover - best effort cleanup |
| 134 | + pass |
| 135 | + |
| 136 | + if output_file_content and not stdout_text.strip(): |
| 137 | + stdout_text = output_file_content |
| 138 | + |
| 139 | + if return_code != 0: |
| 140 | + raise CLIAgentError( |
| 141 | + f"CLI '{self.client.name}' exited with status {return_code}", |
| 142 | + returncode=return_code, |
| 143 | + stdout=stdout_text, |
| 144 | + stderr=stderr_text, |
| 145 | + ) |
| 146 | + |
| 147 | + try: |
| 148 | + parsed = self._parser.parse(stdout_text, stderr_text) |
| 149 | + except ParserError as exc: |
| 150 | + raise CLIAgentError( |
| 151 | + f"Failed to parse output from CLI '{self.client.name}': {exc}", |
| 152 | + returncode=return_code, |
| 153 | + stdout=stdout_text, |
| 154 | + stderr=stderr_text, |
| 155 | + ) from exc |
| 156 | + |
| 157 | + return AgentOutput( |
| 158 | + parsed=parsed, |
| 159 | + sanitized_command=sanitized_command, |
| 160 | + returncode=return_code, |
| 161 | + stdout=stdout_text, |
| 162 | + stderr=stderr_text, |
| 163 | + duration_seconds=duration, |
| 164 | + parser_name=self._parser.name, |
| 165 | + output_file_content=output_file_content, |
| 166 | + ) |
| 167 | + |
| 168 | + def _build_command(self, *, role: ResolvedCLIRole) -> list[str]: |
| 169 | + base = list(self.client.executable) |
| 170 | + base.extend(self.client.internal_args) |
| 171 | + base.extend(self.client.config_args) |
| 172 | + base.extend(role.role_args) |
| 173 | + |
| 174 | + return base |
| 175 | + |
| 176 | + def _build_environment(self) -> dict[str, str]: |
| 177 | + env = os.environ.copy() |
| 178 | + env.update(self.client.env) |
| 179 | + return env |
0 commit comments