motif64

m64_af70aa90034a / cli_shim.py

421 lines, 17.3 KBraw
1"""CLI shim — gives a command-line agent harness a small HTTP API, from inside2its sandbox.34opencode ships an HTTP server; hermes, pi and openclaw are driven here through5their own non-interactive CLI instead, one process per prompt. That keeps each6session in its own working directory and home, relies only on each tool's most7stable interface (the documented one-shot mode + its "continue" flag), and needs8nothing but the Python stdlib.910Copied from gx10 ~/code/vlmtest/agents/shim/cli_shim.py. In the m64 capsule it listens on11$SHIM_HOST:$SHIM_PORT (127.0.0.1:4096): only the agent gateway in the same container calls it.1213  GET    /health14  POST   /sessions                 {id, directory}   create home + harness config15  GET    /sessions/{id}            {busy}16  DELETE /sessions/{id}17  POST   /sessions/{id}/prompt     {text}            blocks; {text, tools, exit_code, ...}18  GET    /sessions/{id}/messages   transcript19  GET    /sessions/{id}/events     SSE: raw harness output lines + turn start/end20  POST   /sessions/{id}/abort      kill the running turn21"""22import json23import os24import queue25import shutil26import signal27import subprocess28import threading29import time30from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer31from pathlib import Path3233HARNESS = os.environ["AGENT_HARNESS"]34MODEL = os.environ["AGENT_MODEL"]35LLM_BASE = os.environ.get("LLM_BASE_URL", "http://llm:9000/v1")36HOST = os.environ.get("SHIM_HOST", "127.0.0.1")37PORT = int(os.environ.get("SHIM_PORT", "4096"))38HOMES = Path(os.environ.get("SHIM_HOMES", "/work/.homes"))39# 0 = no limit: a turn runs until the harness finishes it (the caller can still40# POST /sessions/{id}/abort). Long agentic tasks outlast any fixed cap.41TURN_TIMEOUT = int(os.environ.get("TURN_TIMEOUT", "0"))42# The LLM's max-model-len; harnesses budget their context against it.43CONTEXT = int(os.environ.get("AGENT_CONTEXT", "131072"))44MAX_OUT = min(16384, CONTEXT // 8)45# Every agent LLM is a vision model; a harness told "text" only refuses to pass46# images on even though the server takes them.47INPUT = ["text", "image"] if os.environ.get("AGENT_VISION", "1") == "1" else ["text"]484950# ── Harness adapters ──────────────────────────────────────────────────────────51# Each: setup(home, directory) writes config; command(...) -> (argv, env);52# parse(lines) -> (text, tools).5354class Pi:55    binary = "pi"5657    def setup(self, home: Path, directory: str) -> None:58        agent_dir = home / "pi-agent"59        agent_dir.mkdir(parents=True, exist_ok=True)60        (agent_dir / "models.json").write_text(json.dumps({"providers": {"gx10": {61            "baseUrl": LLM_BASE, "api": "openai-completions", "apiKey": "sk-local",62            # vLLM rejects the `developer` role and reasoning_effort.63            "compat": {"supportsDeveloperRole": False, "supportsReasoningEffort": False},64            "models": [{"id": MODEL, "reasoning": True, "input": INPUT, "contextWindow": CONTEXT,65                        "maxTokens": MAX_OUT}]}}}, indent=2))66        (agent_dir / "settings.json").write_text(json.dumps(67            {"defaultProvider": "gx10", "defaultModel": MODEL, "quietStartup": True}))6869    def command(self, home: Path, directory: str, text: str, first: bool, sid: str):70        argv = ["pi", "-p", "--mode", "json", "--provider", "gx10", "--model", MODEL]71        if not first:72            argv.append("--continue")73        argv.append(text)74        env = {"PI_CODING_AGENT_DIR": str(home / "pi-agent"), "PI_OFFLINE": "1",75               "PI_TELEMETRY": "0"}76        return argv, env7778    def parse(self, lines: list[str]):79        text, tools, open_calls = "", [], {}80        for line in lines:81            try:82                ev = json.loads(line)83            except ValueError:84                continue85            t = ev.get("type")86            if t == "tool_execution_start":87                call = {"tool": ev.get("toolName"), "status": "running", "input": ev.get("args"),88                        "output": ""}89                open_calls[ev.get("toolCallId")] = call90                tools.append(call)91            elif t == "tool_execution_end":92                call = open_calls.get(ev.get("toolCallId"))93                if call:94                    call["status"] = "error" if ev.get("isError") else "completed"95                    call["output"] = _content_text(ev.get("result"))[:4000]96            elif t == "message_end" and (ev.get("message") or {}).get("role") == "assistant":97                t_ = _content_text((ev["message"] or {}).get("content"))98                if t_.strip():99                    text = t_100        return text, tools101102103class Hermes:104    binary = "hermes"105106    def setup(self, home: Path, directory: str) -> None:107        h = home / "hermes"108        h.mkdir(parents=True, exist_ok=True)109        (h / "config.yaml").write_text(110            "model:\n"111            f'  default: "{MODEL}"\n'112            '  provider: "custom"\n'113            f'  base_url: "{LLM_BASE}"\n'114            '  api_key: "sk-local"\n'115            '  api_mode: "chat_completions"\n'116            # Its terminal tool otherwise starts in HOME, not the session directory.117            "terminal:\n"118            f'  cwd: "{directory}"\n')119120    def command(self, home: Path, directory: str, text: str, first: bool, sid: str):121        argv = ["hermes", "-z", text, "--provider", "custom", "-m", MODEL, "--yolo",122                "--in", directory]123        if not first:124            argv.append("--continue")125        return argv, {"HERMES_HOME": str(home / "hermes")}126127    def parse(self, lines: list[str]):128        # -z prints only the final response.129        return "\n".join(lines).strip(), []130131132class OpenClaw:133    binary = "openclaw"134135    def setup(self, home: Path, directory: str) -> None:136        state = home / "openclaw"137        state.mkdir(parents=True, exist_ok=True)138        (state / "openclaw.json").write_text(json.dumps({139            "models": {"providers": {"vllm": {140                "baseUrl": LLM_BASE, "apiKey": "sk-local", "api": "openai-completions",141                "timeoutSeconds": 900,142                "models": [{"id": MODEL, "name": MODEL, "reasoning": True, "input": INPUT,143                            "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},144                            "contextWindow": CONTEXT, "maxTokens": MAX_OUT}]}}},145            "agents": {"defaults": {"model": {"primary": f"vllm/{MODEL}"},146                                    "workspace": directory}},147            **json.loads(os.environ.get("OPENCLAW_EXTRA_CONFIG", "{}")),148        }, indent=2))149150    def command(self, home: Path, directory: str, text: str, first: bool, sid: str):151        state = home / "openclaw"152        argv = ["openclaw", "agent", "--local", "--session-id", sid, "--message", text, "--json"]153        return argv, {"OPENCLAW_STATE_DIR": str(state),154                      "OPENCLAW_CONFIG_PATH": str(state / "openclaw.json")}155156    def parse(self, lines: list[str]):157        raw = "\n".join(lines)158        start = raw.find("{")159        try:160            doc = json.loads(raw[start:]) if start >= 0 else {}161        except ValueError:162            return raw.strip(), []163        payloads = doc.get("payloads") or (doc.get("result") or {}).get("payloads") or []164        text = "\n".join(p.get("text", "") for p in payloads if isinstance(p, dict)).strip()165        return text or raw.strip(), []166167168class Dsh:169    """DeepSeek Harness (`dsh --profile headless`). The LLM route is a --patch overlay170    on the shipped headless profile: one pi-ai openai-completions provider at the171    gateway, set as the default model. Approvals off via DSH_PERMISSION_MODE (the172    container is the sandbox). Everything else stays the profile's own default."""173    binary = "dsh"174175    def setup(self, home: Path, directory: str) -> None:176        d = home / "dsh"177        d.mkdir(parents=True, exist_ok=True)178        (d / "gx10.patch.yml").write_text(179            "- id: llm-pi-ai\n"180            "  config:\n"181            "    providers:\n"182            "      gx10:\n"183            "        api: openai-completions\n"184            f"        baseURL: {LLM_BASE}\n"185            "        apiKeyEnv: GX10_LLM_KEY\n"186            "        models:\n"187            f"          - id: {MODEL}\n"188            f"            contextWindow: {CONTEXT}\n"189            f"            input: [{', '.join(INPUT)}]\n"190            "- id: agent-default-model\n"191            "  config:\n"192            "    provider: gx10\n"193            f"    model: {MODEL}\n")194195    def command(self, home: Path, directory: str, text: str, first: bool, sid: str):196        d = home / "dsh"197        argv = ["dsh", "--profile", "headless", "--patch", str(d / "gx10.patch.yml"), "--json"]198        if not first:199            # Follow-ups adopt this session's persisted dsh Session (newest under DSH_HOME).200            ids = sorted((p for p in (d / "home" / "sessions").rglob("session-*")),201                         key=lambda p: p.stat().st_mtime)202            if ids:203                argv += ["--session-id", ids[-1].name.split(".")[0]]204        argv.append(text)205        # The gateway holds any real key; the route only needs a non-empty credential.206        return argv, {"DSH_HOME": str(d / "home"), "GX10_LLM_KEY": "sk-local",207                      "DSH_PERMISSION_MODE": "danger-full-access"}208209    def parse(self, lines: list[str]):210        text, tools, calls = "", [], {}211        for line in lines:212            try:213                ev = json.loads(line)214            except ValueError:215                continue216            t = ev.get("type")217            if t == "tool_call":218                call = {"tool": ev.get("tool"), "status": "running", "input": ev.get("input"), "output": ""}219                calls[ev.get("callId")] = call220                tools.append(call)221            elif t == "tool_result":222                call = calls.get(ev.get("callId"))223                if call:224                    r = ev.get("result")225                    call["status"] = ev.get("status") or "completed"226                    call["output"] = (r if isinstance(r, str) else _content_text(r))[:4000]227            elif t == "final":228                text = ev.get("text") or text229        return text, tools230231232ADAPTERS = {"pi": Pi, "hermes": Hermes, "openclaw": OpenClaw, "dsh": Dsh}233adapter = ADAPTERS[HARNESS]()234235236def _content_text(content) -> str:237    if isinstance(content, str):238        return content239    if isinstance(content, dict):240        return _content_text(content.get("content"))241    if isinstance(content, list):242        return "".join(c.get("text", "") for c in content if isinstance(c, dict)243                       and c.get("type") in (None, "text"))244    return ""245246247# ── Sessions ──────────────────────────────────────────────────────────────────248249class Session:250    def __init__(self, sid: str, directory: str):251        self.id, self.directory = sid, directory252        self.home = HOMES / sid253        self.proc: subprocess.Popen | None = None254        self.turns = 0255        self.subscribers: list[queue.Queue] = []256        self.lock = threading.Lock()257        self.transcript_path = self.home / "transcript.json"258259    def emit(self, ev: dict) -> None:260        for q in list(self.subscribers):261            q.put(ev)262263    def transcript(self) -> list:264        try:265            return json.loads(self.transcript_path.read_text())266        except Exception:267            return []268269    def record(self, entry: dict) -> None:270        t = self.transcript()271        t.append(entry)272        self.transcript_path.write_text(json.dumps(t, indent=1))273274    def prompt(self, text: str) -> dict:275        if not self.lock.acquire(blocking=False):276            return {"error": "session busy", "status": 409}277        try:278            argv, extra_env = adapter.command(self.home, self.directory, text,279                                              self.turns == 0, self.id)280            env = {**os.environ, "HOME": str(self.home), **extra_env}281            self.record({"role": "user", "text": text, "time": time.time()})282            self.emit({"type": "turn.start", "text": text})283            t0 = time.time()284            self.proc = subprocess.Popen(argv, cwd=self.directory, env=env, text=True,285                                         stdout=subprocess.PIPE, stderr=subprocess.PIPE,286                                         start_new_session=True)287            err_lines: list[str] = []288            threading.Thread(target=lambda: err_lines.extend(self.proc.stderr), daemon=True).start()289            lines = []290            timer = threading.Timer(TURN_TIMEOUT, self.abort) if TURN_TIMEOUT > 0 else None291            if timer:292                timer.start()293            for line in self.proc.stdout:294                line = line.rstrip("\n")295                lines.append(line)296                self.emit({"type": "output", "line": line})297            code = self.proc.wait()298            if timer:299                timer.cancel()300            reply, tools = adapter.parse(lines)301            out = {"role": "assistant", "text": reply, "tools": tools, "exit_code": code,302                   "elapsed_s": round(time.time() - t0, 1), "time": time.time()}303            if code != 0:304                out["error"] = "".join(err_lines)[-2000:] or f"exit {code}"305            self.turns += 1306            self.record(out)307            self.emit({"type": "turn.end", **out})308            return out309        finally:310            self.proc = None311            self.lock.release()312313    def abort(self) -> None:314        p = self.proc315        if p and p.poll() is None:316            os.killpg(p.pid, signal.SIGTERM)317318319SESSIONS: dict[str, Session] = {}320321322class H(BaseHTTPRequestHandler):323    protocol_version = "HTTP/1.1"324325    def log_message(self, *a):326        pass327328    def _send(self, code: int, obj) -> None:329        body = json.dumps(obj).encode()330        self.send_response(code)331        self.send_header("Content-Type", "application/json")332        self.send_header("Content-Length", str(len(body)))333        self.end_headers()334        self.wfile.write(body)335336    def _body(self) -> dict:337        n = int(self.headers.get("Content-Length") or 0)338        return json.loads(self.rfile.read(n) or b"{}") if n else {}339340    def _session(self, sid: str) -> Session | None:341        s = SESSIONS.get(sid)342        if not s:343            self._send(404, {"error": f"unknown session {sid}"})344        return s345346    def do_GET(self):347        parts = self.path.split("?")[0].strip("/").split("/")348        if parts == ["health"]:349            ok = shutil.which(adapter.binary) is not None350            return self._send(200 if ok else 503, {"ok": ok, "harness": HARNESS})351        if len(parts) >= 2 and parts[0] == "sessions":352            s = self._session(parts[1])353            if not s:354                return355            if len(parts) == 2:356                return self._send(200, {"id": s.id, "busy": s.proc is not None, "turns": s.turns})357            if parts[2] == "messages":358                return self._send(200, {"messages": s.transcript()})359            if parts[2] == "events":360                return self._events(s)361        self._send(404, {"error": "not found"})362363    def _events(self, s: Session) -> None:364        q: queue.Queue = queue.Queue()365        s.subscribers.append(q)366        self.send_response(200)367        self.send_header("Content-Type", "text/event-stream")368        self.send_header("Cache-Control", "no-cache")369        self.end_headers()370        try:371            self.wfile.write(b'data: {"type": "server.connected"}\n\n')372            self.wfile.flush()373            while True:374                try:375                    ev = q.get(timeout=15)376                    self.wfile.write(f"data: {json.dumps(ev)}\n\n".encode())377                except queue.Empty:378                    self.wfile.write(b": keepalive\n\n")379                self.wfile.flush()380        except (BrokenPipeError, ConnectionResetError):381            pass382        finally:383            s.subscribers.remove(q)384385    def do_POST(self):386        parts = self.path.split("?")[0].strip("/").split("/")387        body = self._body()388        if parts == ["sessions"]:389            sid, directory = body["id"], body["directory"]390            s = Session(sid, directory)391            s.home.mkdir(parents=True, exist_ok=True)392            adapter.setup(s.home, directory)393            SESSIONS[sid] = s394            return self._send(201, {"id": sid})395        if len(parts) == 3 and parts[0] == "sessions":396            s = self._session(parts[1])397            if not s:398                return399            if parts[2] == "prompt":400                out = s.prompt(body.get("text", ""))401                return self._send(out.pop("status", 200) if "status" in out else 200, out)402            if parts[2] == "abort":403                s.abort()404                return self._send(200, {"aborted": s.id})405        self._send(404, {"error": "not found"})406407    def do_DELETE(self):408        parts = self.path.strip("/").split("/")409        if len(parts) == 2 and parts[0] == "sessions":410            s = SESSIONS.pop(parts[1], None)411            if s:412                s.abort()413                shutil.rmtree(s.home, ignore_errors=True)414            return self._send(200, {"deleted": parts[1]})415        self._send(404, {"error": "not found"})416417418if __name__ == "__main__":419    HOMES.mkdir(parents=True, exist_ok=True)420    print(f"[cli-shim] {HARNESS} ({MODEL}) on {HOST}:{PORT}", flush=True)421    ThreadingHTTPServer((HOST, PORT), H).serve_forever()