Skip to content

The platform for continuously improving AI agents.

7.9 KB
Raw Blame
from __future__ import annotations

import ast
import asyncio
import contextlib
import json
import os
import shutil
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import httpx
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client
from typer.testing import CliRunner

AGENTS = Path(__file__).parent / "agents"
SDK = Path(__file__).resolve().parents[2] / "overmind"


@dataclass
class SampleAgent:
    repo: Path
    truth: dict[str, Any]

    @property
    def toml(self) -> Path:
        return self.repo / "overmind.toml"

    @property
    def analysis(self) -> Path:
        return self.repo / "overmind_capabilities.json"

    @classmethod
    def copy(cls, name: str, into: Path) -> SampleAgent:
        repo = into / name
        shutil.copytree(
            AGENTS / name,
            repo,
            ignore=shutil.ignore_patterns(
                "__pycache__", "truth.json", "overmind_capabilities.json"
            ),
        )
        truth = json.loads((AGENTS / name / "truth.json").read_text())
        git = ["git", "-c", "user.name=journey", "-c", "[email protected]"]
        subprocess.run([*git, "init", "-q", "-b", "main"], cwd=repo, check=True)
        subprocess.run([*git, "add", "-A"], cwd=repo, check=True)
        subprocess.run([*git, "commit", "-q", "-m", "support desk"], cwd=repo, check=True)
        return cls(repo=repo, truth=truth)

    def commit(self) -> str:
        return subprocess.run(
            ["git", "rev-parse", "HEAD"], cwd=self.repo, check=True, capture_output=True, text=True
        ).stdout.strip()

    def scan_output(self, *, without: tuple[str, ...] = ()) -> None:
        data = json.loads((AGENTS / self.repo.name / "overmind_capabilities.json").read_text())
        data["capabilities"] = [c for c in data["capabilities"] if c["slug_hint"] not in without]
        self._check_anchor_lines(data)
        self.analysis.write_text(json.dumps(data))

    def _check_anchor_lines(self, data: dict[str, Any]) -> None:
        for capability in data["capabilities"]:
            for anchor in capability["capability_card"].get("anchors") or []:
                path, _, lines = anchor["file"].partition("#")
                tree = ast.parse((self.repo / path).read_text())
                name = anchor["qualname"].rsplit(".", 1)[-1]
                fn = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == name)
                start = min([fn.lineno] + [d.lineno for d in fn.decorator_list])
                assert lines == f"L{start}-L{fn.end_lineno}", f"{anchor['qualname']} moved: {lines}"

    def run(self, *tickets: str, api_url: str, llm_url: str, llm_key: str = "sk-fake") -> list[str]:
        env = {
            **os.environ,
            "PYTHONPATH": os.pathsep.join([str(SDK), str(self.repo)]),
            "OPENAI_BASE_URL": llm_url,
            "OPENAI_API_KEY": llm_key,
            "OVERMIND_API_URL": api_url,
            "OVERMIND_ANALYTICS_ENABLED": "false",
            "LITELLM_LOCAL_MODEL_COST_MAP": "True",
        }
        env.pop("OVERMIND_API_KEY", None)
        result = subprocess.run(
            [sys.executable, "-m", "support_desk", *tickets],
            cwd=self.repo,
            env=env,
            capture_output=True,
            text=True,
            timeout=120,
        )
        if result.returncode != 0:
            raise AssertionError(f"support_desk exited {result.returncode}:\n{result.stderr}")
        return result.stdout.splitlines()


class CliSurface:
    def __init__(self, api_url: str, api_key: str) -> None:
        self.api_url = api_url
        self.api_key = api_key

    def run(self, *args: str, cwd: Path | None = None) -> str:
        from overmind.__main__ import app

        with contextlib.chdir(cwd or Path.cwd()):
            result = CliRunner().invoke(
                app,
                list(args),
                catch_exceptions=False,
                env={"OVERMIND_API_URL": self.api_url, "OVERMIND_API_KEY": ""},
            )
        if result.exit_code != 0:
            raise AssertionError(
                f"overmind {' '.join(args)} exited {result.exit_code}:\n{result.output}"
            )
        return result.output

    def scan(self, agent: SampleAgent, *, without: tuple[str, ...] = ()) -> None:
        from overmind.config import dump, load
        from overmind.utils import convert_json_to_toml

        self.run("chassis", "--root", str(agent.repo))
        agent.scan_output(without=without)
        convert_json_to_toml(agent.analysis, agent.toml)
        config = load(agent.toml)
        config.base_url = self.api_url
        dump(config, agent.toml)
        agent.analysis.unlink()

    def sync(self, agent: SampleAgent) -> str:
        return self.run(
            "sync",
            "up",
            "--api-key",
            self.api_key,
            "--api-url",
            self.api_url,
            "--path",
            str(agent.toml),
        )

    def project_key(self, agent: SampleAgent) -> str:
        from overmind.config import load

        return load(agent.toml).api_key


class McpSurface:
    def __init__(self, api_url: str, api_key: str) -> None:
        self.url = f"{api_url}/api/mcp/"
        self.api_key = api_key

    async def _session(self, action):
        client = httpx.AsyncClient(headers={"X-Api-Key": self.api_key}, timeout=120)
        async with (
            client,
            streamable_http_client(self.url, http_client=client) as (read, write, _),
            ClientSession(read, write) as session,
        ):
            initialized = await session.initialize()
            return await action(session, initialized)

    def read(self, uri: str) -> dict[str, Any]:
        async def action(session: ClientSession, _initialized):
            return await session.read_resource(uri)

        from mcp.shared.exceptions import McpError

        try:
            result = asyncio.run(self._session(action))
        except* McpError as group:
            raise LookupError(str(group.exceptions[0])) from None
        return json.loads(result.contents[0].text)

    def discover(self) -> dict[str, Any]:
        async def action(session: ClientSession, initialized):
            tools = await session.list_tools()
            return {
                "version": initialized.serverInfo.version,
                "tools": [tool.name for tool in tools.tools],
            }

        return asyncio.run(self._session(action))

    def call_result(self, tool: str, arguments: dict[str, Any] | None = None):
        async def action(session: ClientSession, _initialized):
            return await session.call_tool(tool, arguments or {})

        return asyncio.run(self._session(action))

    def call(self, tool: str, arguments: dict[str, Any] | None = None) -> dict[str, Any]:
        result = self.call_result(tool, arguments)
        if result.isError:
            raise AssertionError(f"MCP {tool} failed: {result.content}")
        return result.structuredContent or json.loads(result.content[0].text)

    def capability(self, slug: str) -> dict[str, Any]:
        return self.read(f"overmind://capabilities/{slug}")

    def project(self) -> dict[str, Any]:
        return self.read("overmind://project/current")


class RestSurface:
    def __init__(self, api_url: str, api_key: str) -> None:
        self.api_url = api_url
        self.api_key = api_key

    def request(self, method: str, path: str, **kwargs) -> Any:
        import requests

        response = requests.request(
            method,
            f"{self.api_url}{path}",
            headers={"X-Api-Key": self.api_key, **kwargs.pop("headers", {})},
            timeout=30,
            **kwargs,
        )
        if response.status_code >= 400:
            raise AssertionError(
                f"{method} {path} -> {response.status_code}: {response.text[:500]}"
            )
        return response.json() if response.content else None