Skip to content

The platform for continuously improving AI agents.

9.2 KB
Raw Blame
"""The container engine a research executor runs on, as the Docker Engine API on a unix socket.

A started container holds the research image's runner. The OpenHands SDK inside that image is
not installed here, so the stand-in keeps only what the platform observes of it: the runner's
wire contract (bootstrap, the event journal, inbox acknowledgements, the metered model relay
and native tool dispatch) and when its turn ends: after finish, an accepted wait, a reply
without tool calls or an unread user message. ``run_started`` runs each started container to
its exit, as the executor would between two ticks of the agent's workflow."""

from __future__ import annotations

import json
import threading
import uuid
from contextlib import contextmanager
from datetime import UTC, datetime
from http.server import BaseHTTPRequestHandler
from socketserver import ThreadingUnixStreamServer
from tempfile import TemporaryDirectory
from urllib.parse import parse_qs, urlsplit

import httpx

from agent_runtime.runtime_transport import RuntimeClient

RELEASE = "sha256:" + "e" * 64
IMAGE = {
    "Id": RELEASE,
    "Architecture": "amd64",
    "Os": "linux",
    "RootFS": {"Layers": ["dependencies", "runtime"]},
    "Config": {"User": "10001:10001", "Entrypoint": ["python"]},
}
HISTORY = [
    {"CreatedBy": 'ENTRYPOINT ["python"]', "Size": 0},
    {"CreatedBy": "COPY agent_runtime /opt/runtime/agent_runtime # buildkit", "Size": 10},
    {"CreatedBy": "RUN pip install --require-hashes", "Size": 100},
]
PAUSING = {"wait", "ask_user", "request_access"}
MAX_ITERATIONS = 24


class ResearchEngine:
    def __init__(self) -> None:
        self.containers: dict[str, dict] = {}
        self.started: list[str] = []
        self.journals: dict[str, dict] = {}
        self.lock = threading.Lock()

    @contextmanager
    def serve(self):
        engine = self

        class Handler(BaseHTTPRequestHandler):
            def reply(self, status, body=None):
                data = json.dumps(body).encode() if body is not None else b""
                self.send_response(status)
                self.send_header("Content-Length", str(len(data)))
                self.end_headers()
                self.wfile.write(data)

            def do_GET(self):
                parts = urlsplit(self.path).path.split("/")
                if parts[1] == "images":
                    return self.reply(200, IMAGE if parts[3] == "json" else HISTORY)
                with engine.lock:
                    found = engine.containers.get(parts[2])
                self.reply(200 if found else 404, found)

            def do_POST(self):
                parsed = urlsplit(self.path)
                length = int(self.headers.get("Content-Length", 0))
                body = json.loads(self.rfile.read(length) or b"{}")
                with engine.lock:
                    if parsed.path == "/containers/create":
                        name = parse_qs(parsed.query)["name"][0]
                        engine.containers[name] = {
                            "Image": body["Image"],
                            "Config": {
                                "Labels": body["Labels"],
                                "User": body["User"],
                                "Env": body["Env"],
                            },
                            "HostConfig": body["HostConfig"],
                            "Mounts": [
                                {
                                    "Type": "volume",
                                    "Name": mount["Source"],
                                    "Destination": mount["Target"],
                                }
                                for mount in body["HostConfig"]["Mounts"]
                            ],
                            "State": {"Running": False, "Status": "created", "ExitCode": 0},
                        }
                        return self.reply(201, {"Id": name})
                    name, operation = parsed.path.split("/")[2:4]
                    container = engine.containers[name]
                    if operation == "start":
                        container["State"] = {"Running": True, "Status": "running", "ExitCode": 0}
                        engine.started.append(name)
                    else:
                        container["State"] = {"Running": False, "Status": "exited", "ExitCode": 0}
                self.reply(204)

            def log_message(self, *_):
                pass

        with TemporaryDirectory(prefix="engine-", dir="/tmp") as directory:
            socket = directory + "/docker.sock"
            server = ThreadingUnixStreamServer(socket, Handler)
            thread = threading.Thread(target=server.serve_forever, daemon=True)
            thread.start()
            try:
                yield socket
            finally:
                server.shutdown()
                server.server_close()
                thread.join()

    def run_started(self) -> list[str]:
        """Run every started container to its exit; returns the agents whose executor exited."""
        exited = []
        while True:
            with self.lock:
                if not self.started:
                    return exited
                name = self.started.pop(0)
                container = self.containers[name]
                if not container["State"]["Running"]:
                    continue
                environment = dict(item.split("=", 1) for item in container["Config"]["Env"])
            code = self.runner(environment)
            with self.lock:
                container["State"] = {"Running": False, "Status": "exited", "ExitCode": code}
            exited.append(container["Config"]["Labels"]["overmind.agent"])

    def runner(self, environment: dict[str, str]) -> int:
        client = RuntimeClient(
            environment["RESEARCH_API_URL"], environment["RESEARCH_RUNTIME_TOKEN"]
        )
        config = client.post("bootstrap")
        journal = self.journals.setdefault(
            config["conversation_id"], {"last": None, "messages": []}
        )
        sequence = config["projected_sequence"]

        def project(**event) -> str:
            nonlocal sequence
            event = {
                "id": str(uuid.uuid4()),
                "parent_id": journal["last"],
                "timestamp": datetime.now(UTC).isoformat(),
                **event,
            }
            client.post("events", {"sequence": sequence, "event": event})
            sequence += 1
            journal["last"] = event["id"]
            return event["id"]

        if sequence == 0:
            project(kind="system")
            journal["messages"].append({"role": "system", "content": config["prompt"]})
        journal["messages"].append({"role": "user", "content": json.dumps(config["context"])})
        for message in config["messages"]:
            event = project(kind="message", role="user", text=message["text"], sender=message["id"])
            client.post("messages", {"message_id": message["id"], "event_id": event})
            journal["messages"].append({"role": "user", "content": message["text"]})
        tools = [{"type": "function", "function": definition} for definition in config["tools"]]
        for _ in range(MAX_ITERATIONS):
            response = httpx.post(
                f"{config['base_url']}/chat/completions",
                json={"model": config["model"], "messages": journal["messages"], "tools": tools},
                headers={"Authorization": f"Bearer {config['api_key']}"},
                timeout=60,
            )
            response.raise_for_status()
            reply = response.json()["choices"][0]["message"]
            calls = reply.get("tool_calls") or []
            journal["messages"].append(
                {"role": "assistant", "content": reply.get("content"), "tool_calls": calls}
                if calls
                else {"role": "assistant", "content": reply.get("content") or ""}
            )
            if not calls:
                project(kind="message", role="assistant", text=reply.get("content") or "")
                return 0
            for call in calls:
                tool, arguments = (
                    call["function"]["name"],
                    json.loads(call["function"]["arguments"]),
                )
                action = project(
                    kind="action", tool=tool, tool_call_id=call["id"], arguments=arguments
                )
                result = client.post(
                    "tools", {"action_id": action, "tool": tool, "arguments": arguments}
                )
                project(kind="observation", tool=tool, action_id=action, observation=result)
                journal["messages"].append(
                    {"role": "tool", "tool_call_id": call["id"], "content": json.dumps(result)}
                )
                data = result.get("data") or {}
                if (
                    tool == "finish"
                    or data.get("reason") == "unread_user_message"
                    or (
                        (
                            tool in PAUSING
                            or (tool == "eval_set" and arguments.get("operation") == "draft")
                        )
                        and result.get("accepted")
                        and data.get("running") is not False
                    )
                ):
                    return 0
        return 0