From c70c3c32cf4c25eebcba83787b775772320dde0a Mon Sep 17 00:00:00 2001 From: Hermes Agent Date: Fri, 30 Oct 2026 19:05:47 +0200 Subject: [PATCH 1/2] Add Hermes and OpenCode CLI agent adapters Implement OpenBot runtime CLI agent adapters for Hermes Agent (hermes chat --format stream-json) and OpenCode (opencode run --format json), mirroring the existing Claude Code adapter contract in base.py: - hermes.py / opencode.py: provider/label/binary/path_setting / install_dirs / argv / parser / not_found, StreamParser feed/finish/usage_so_far, system prompt threaded via child stdin, every output line JSON (non-JSON dropped at debug), CLIs forced into JSON output mode. - session_id_re overridden per adapter (default rejects OpenCode's ses_... ids); status_argv=() and min_version=(0,0,0) for both. - Conservative permission mapping with WHY comments: hermes EDIT -> -t file, opencode EDIT -> allow edit; READ_ONLY never auto-approves writes. - Register both adapters in ADAPTERS; add unit tests for argv construction and stream parsing (recorded event lines). - base.py extended with Turn.cwd, adapter.combine(), adapter.turn_env(), env merged into child env. - schemas.py: add hermes/opencode to Provider literal + MODEL_OPTIONAL. - config.py: add hermes_path / opencode_path settings. - conftest.py: pin LOG_FILE=nul before openbot.main import so the import-time configure_logging does not crash in file-creation-blocked sandboxes. Ruff clean; 59/59 cli_agents tests pass; full suite 840 passed with 7 pre-existing environmental failures (file/SQLite creation blocked), none in the adapter code. --- backend/openbot/api/schemas.py | 4 +- backend/openbot/config.py | 2 + .../openbot/runtime/cli_agents/__init__.py | 4 +- backend/openbot/runtime/cli_agents/base.py | 17 +- backend/openbot/runtime/cli_agents/hermes.py | 148 +++++++++++++++ .../openbot/runtime/cli_agents/opencode.py | 174 ++++++++++++++++++ backend/tests/conftest.py | 7 + backend/tests/fixtures/hermes_turn.jsonl | 5 + backend/tests/fixtures/opencode_turn.jsonl | 5 + backend/tests/test_cli_agents.py | 123 +++++++++++++ 10 files changed, 484 insertions(+), 5 deletions(-) create mode 100644 backend/openbot/runtime/cli_agents/hermes.py create mode 100644 backend/openbot/runtime/cli_agents/opencode.py create mode 100644 backend/tests/fixtures/hermes_turn.jsonl create mode 100644 backend/tests/fixtures/opencode_turn.jsonl diff --git a/backend/openbot/api/schemas.py b/backend/openbot/api/schemas.py index faf85b9d..232b957f 100644 --- a/backend/openbot/api/schemas.py +++ b/backend/openbot/api/schemas.py @@ -8,9 +8,9 @@ from openbot.bot_icons import DEFAULT_BOT_ICON, validate_bot_icon -Provider = Literal["auto", "openai", "anthropic", "openrouter", "xai", "ollama", "claude-code"] +Provider = Literal["auto", "openai", "anthropic", "openrouter", "xai", "ollama", "claude-code", "hermes", "opencode"] # Providers whose model may be left empty: auto picks one, a CLI then uses its own default. -MODEL_OPTIONAL = ("auto", "claude-code") +MODEL_OPTIONAL = ("auto", "claude-code", "hermes", "opencode") HANDLE_RE = r"^[a-z0-9_-]{2,32}$" Handle = Annotated[str, Field(pattern=HANDLE_RE)] # ~3.5 MB of decoded image bytes (base64 inflates by 4/3). diff --git a/backend/openbot/config.py b/backend/openbot/config.py index 21d77f84..5e6f0be7 100644 --- a/backend/openbot/config.py +++ b/backend/openbot/config.py @@ -66,6 +66,8 @@ class Settings(BaseSettings): # its usual install locations unless its *_PATH names the executable; a run is stopped after the # timeout (a bot can set its own in model_settings.timeout_seconds). claude_code_path: str | None = None + hermes_path: str | None = None + opencode_path: str | None = None cli_agent_timeout: int = 1800 max_concurrent_runs: int = 4 diff --git a/backend/openbot/runtime/cli_agents/__init__.py b/backend/openbot/runtime/cli_agents/__init__.py index 8fb5bd69..b871b4df 100644 --- a/backend/openbot/runtime/cli_agents/__init__.py +++ b/backend/openbot/runtime/cli_agents/__init__.py @@ -6,8 +6,10 @@ """ from openbot.runtime.cli_agents.base import CliAdapter, CliAgentError from openbot.runtime.cli_agents.claude_code import ClaudeCode +from openbot.runtime.cli_agents.hermes import Hermes +from openbot.runtime.cli_agents.opencode import OpenCode -ADAPTERS: dict[str, CliAdapter] = {a.provider: a for a in (ClaudeCode(),)} +ADAPTERS: dict[str, CliAdapter] = {a.provider: a for a in (ClaudeCode(), Hermes(), OpenCode())} def adapter_for(provider: str | None) -> CliAdapter | None: diff --git a/backend/openbot/runtime/cli_agents/base.py b/backend/openbot/runtime/cli_agents/base.py index 342fcd0b..4be28a6f 100644 --- a/backend/openbot/runtime/cli_agents/base.py +++ b/backend/openbot/runtime/cli_agents/base.py @@ -81,6 +81,7 @@ class Turn: session_id: str | None model: str permission: str + cwd: str = "" @dataclass @@ -133,6 +134,16 @@ def install_dirs(self, *, home: str, env: Mapping[str, str], win: bool) -> list[ """Where the CLI's installers put it, beyond PATH: full paths to the executable.""" return [] + def combine(self, prompt: str, system_prompt: str) -> str: + """The stdin complete prompt this CLI should see. A CLI with no separate system-prompt slot + prefixes the system prompt here; the default keeps the real prompt on stdin untouched.""" + return prompt + + def turn_env(self, turn: Turn) -> dict[str, str]: + """Environment added for this one invocation only (a per-turn permission or config pointer). + Never a place for credentials; the whole turn env comes from child_env().""" + return {} + @abstractmethod def argv(self, executable: str, turn: Turn) -> list[str]: ... @@ -381,7 +392,9 @@ async def _turn(adapter: CliAdapter, executable: str, *, cwd: str, env: dict[str with os.fdopen(fd, "w", encoding="utf-8") as f: f.write(system_prompt) argv = adapter.argv(executable, Turn(system_prompt_file=prompt_file, session_id=session_id, model=model, - permission=permission)) + permission=permission, cwd=cwd)) + env = {**env, **adapter.turn_env(Turn(system_prompt_file=prompt_file, session_id=session_id, model=model, + permission=permission, cwd=cwd))} parser = adapter.parser() stderr_task: asyncio.Task | None = None try: @@ -391,7 +404,7 @@ async def _turn(adapter: CliAdapter, executable: str, *, cwd: str, env: dict[str try: async with asyncio.timeout(timeout): try: - tree.proc.stdin.write(prompt.encode("utf-8")) + tree.proc.stdin.write(adapter.combine(prompt, system_prompt).encode("utf-8")) await tree.proc.stdin.drain() tree.proc.stdin.close() except (BrokenPipeError, ConnectionResetError): diff --git a/backend/openbot/runtime/cli_agents/hermes.py b/backend/openbot/runtime/cli_agents/hermes.py new file mode 100644 index 00000000..045b1efb --- /dev/null +++ b/backend/openbot/runtime/cli_agents/hermes.py @@ -0,0 +1,148 @@ +"""Hermes: `hermes chat --format stream-json --query-file -` (one JSON object per stdout line).""" +from __future__ import annotations + +import ntpath +import posixpath +import re +from collections.abc import Mapping +from typing import Any + +from openbot.runtime.cli_agents.base import ( + EDIT, + READ_ONLY, + CliAdapter, + CliAgentError, + StreamParser, + Turn, + TurnResult, + UnknownSession, +) + +# `-t` takes hermes toolset names only (a bare tool name fails with invalid_params). There is no +# read-only file toolset, so those are the closest read-only toolsets: web search, image analysis, +# todo planning and session search — no file tools at all. EDIT runs exactly the `file` toolset +# (read/write/patch/search), mirroring Claude's file tools; both keep terminal off. --yolo is not mapped. +_PERMISSION_TOOLSETS = {READ_ONLY: "search,vision,todo,session_search", EDIT: "file"} +# A session id is a hex string: "local-" without the CLI and "." under a gateway, or an +# operator-named session. Only the shape that would be re-readable on the command line counts. +_UNKNOWN_SESSION = re.compile(r"No session found matching|session not found", re.IGNORECASE) + + +def _n(d: dict, key: str) -> int: + v = d.get(key) + return int(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else 0 + + +def usage_of(result: dict) -> dict[str, int | float]: + """The result envelope counts this invocation: `tokens` already excludes cache reads.""" + tokens = result.get("tokens") if isinstance(result.get("tokens"), dict) else {} + prompt = _n(tokens, "input") + _n(tokens, "cache_read") + _n(tokens, "cache_write") + output = _n(tokens, "output") + return {"prompt_tokens": prompt, "completion_tokens": output, "cache_read_tokens": _n(tokens, "cache_read"), + "cache_write_tokens": _n(tokens, "cache_write"), "reasoning_tokens": 0, + "total_tokens": prompt + output, "model_calls": 1, "cost_usd": 0.0} + + +class HermesStream(StreamParser): + """system/init (once the session id might still be empty), tool_use, tool_result, the full final + text, then one result envelope. Subagent activity is not in the stream; the session id comes with + the result, which also carries the error on failure.""" + + def __init__(self, session_id_re: re.Pattern[str]) -> None: + self._session_id_re = session_id_re + self.session_id: str | None = None + self.result: dict | None = None + self.texts: list[str] = [] + self._tool_names: dict[str, str] = {} + + def feed(self, event: dict) -> list[tuple[str, Any]]: + out: list[tuple[str, Any]] = [] + kind = event.get("type") + if kind == "system" and event.get("subtype") == "init": + # model / session_id arrive empty on a CLI one-shot; their presence would win anyway. + out.append(("init", {k: event[k] for k in ("model", "session_id") + if isinstance(event.get(k), str) and event[k]})) + elif kind == "tool_use": + call_id, name = str(event.get("tool_call_id", "")), str(event.get("name", "tool")) + self._tool_names[call_id] = name + out.append(("tool_call", {"id": call_id, "name": name, "args": event.get("input") or {}})) + elif kind == "tool_result": + call_id = str(event.get("tool_call_id", "")) + out.append(("tool_result", {"tool_call_id": call_id, "name": self._tool_names.get(call_id, "tool"), + "status": "error" if event.get("is_error") else "success", + "content": str(event.get("output") or "")})) + elif kind == "text": + text = str(event.get("text", "")) + if text.strip(): + self.texts.append(text.strip()) + out.append(("text", text)) + elif kind == "result": + self.result = event + sid = event.get("session_id") + if isinstance(sid, str) and sid and sid != self.session_id and self._session_id_re.match(sid): + self.session_id = sid + out.append(("session", sid)) + return out + + def usage_so_far(self) -> dict[str, int | float] | None: + return usage_of(self.result) if self.result else None + + def finish(self, *, exit_code: int, stderr: str, resumed: bool, baseline: dict | None) -> TurnResult: + result = self.result + if result is None: + if resumed and _UNKNOWN_SESSION.search(stderr): + raise UnknownSession + detail = stderr.strip()[-1000:] + raise CliAgentError(f"error: hermes exited with code {exit_code} without a result" + + (f": {detail}" if detail else "")) + error = str(result.get("error") or "") + code = _n(result, "exit_code") + if error or code or exit_code: + blob = f"{error} {result.get('text') or ''} {stderr}" + if resumed and _UNKNOWN_SESSION.search(blob): + raise UnknownSession + detail = (error or str(result.get("text") or "") or stderr.strip())[-1000:] + raise CliAgentError(f"error: hermes run failed ({code or exit_code})" + (f": {detail}" if detail else ""), + usage=usage_of(result)) + text = str(result.get("text") or "") + return TurnResult(text=text or (self.texts[-1] if self.texts else ""), usage=usage_of(result), + session_id=self.session_id) + + +class Hermes(CliAdapter): + provider = "hermes" + label = "Hermes" + binary = "hermes" + path_setting = "hermes_path" + install_hint = "Run `hermes` once in a terminal and finish sign-in, then restart OpenBot." + status_argv = () # `hermes auth status` wants a provider name; its exit code is no login check. + login_hint = "Run `hermes` in a terminal and finish sign-in." + session_id_re = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_:.:-]{2,127}$") + + def install_dirs(self, *, home: str, env: Mapping[str, str], win: bool) -> list[str]: + p = ntpath if win else posixpath + if not win: + return [p.join(home, ".local", "bin", "hermes"), "/usr/local/bin/hermes", "/opt/homebrew/bin/hermes"] + found = [p.join(home, ".hermes", "bin", "hermes.exe"), p.join(home, ".local", "bin", "hermes.exe")] + if env.get("APPDATA"): + found.append(p.join(env["APPDATA"], "npm", "hermes.cmd")) + return found + + def argv(self, executable: str, turn: Turn) -> list[str]: + # The prompt is read from stdin; the system prompt has no separate slot and is prefixed there. + argv = [executable, "chat", "--format", "stream-json", "--query-file", "-"] + if turn.cwd: + argv += ["--in", turn.cwd] # a gateway services this turn with the same directory + argv += ["-t", _PERMISSION_TOOLSETS[turn.permission]] + if turn.model: + argv += ["--model", turn.model] + if turn.session_id: + argv += ["--resume", turn.session_id] + return argv + + def parser(self) -> HermesStream: + return HermesStream(self.session_id_re) + + def combine(self, prompt: str, system_prompt: str) -> str: + stripped = system_prompt.strip() + return f"{stripped}\n\n{prompt}" if stripped else prompt diff --git a/backend/openbot/runtime/cli_agents/opencode.py b/backend/openbot/runtime/cli_agents/opencode.py new file mode 100644 index 00000000..d29466de --- /dev/null +++ b/backend/openbot/runtime/cli_agents/opencode.py @@ -0,0 +1,174 @@ +"""OpenCode: `opencode run --format json` (one JSON object per stdout line).""" +from __future__ import annotations + +import json +import ntpath +import posixpath +import re +from collections.abc import Mapping +from typing import Any + +from openbot.runtime.cli_agents.base import ( + EDIT, + READ_ONLY, + CliAdapter, + CliAgentError, + StreamParser, + Turn, + TurnResult, + UnknownSession, +) + +# In non-interactive `run` a permission request is never asked: it is auto-rejected (and the model is +# told so). --auto would allow everything including running commands, so the permission levels are set +# with OPENCODE_PERMISSION instead, which merges after the user's own config. Denies are explicit so an +# allow rule elsewhere cannot widen the bot's reach; external_directory stays readable (the Read tool is +# the point of read-only) and lsp is diagnostics. +_COMMON = {"read": "allow", "glob": "allow", "grep": "allow", "list": "allow", "lsp": "allow", + "external_directory": "allow", "edit": "deny", "bash": "deny", "task": "deny", + "webfetch": "deny", "websearch": "deny", "skill": "deny"} +_PERMISSIONS = {READ_ONLY: _COMMON, EDIT: {**_COMMON, "edit": "allow"}} +# Ancient versions refused --session (Session not found); 2.x creates the session if it is gone. +_UNKNOWN_SESSION = re.compile(r"session not found", re.IGNORECASE) + + +def _n(value: Any) -> int: + return int(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else 0 + + +def _f(value: Any) -> float: + return float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else 0.0 + + +def _result_text(state: dict) -> str: + out = state.get("output") + if isinstance(out, str): + return out + blocks = (state.get("metadata") or {}).get("content") + if isinstance(blocks, list): + return "\n".join(str(b.get("text", "")) for b in blocks if isinstance(b, dict) and b.get("type") == "text") + return "" if out is None else json.dumps(out, default=str) + + +def usage_of(steps: int, tokens: dict, cost: float) -> dict[str, int | float]: + """Usage of the finished steps. `--format json` reports usage per step in `step_finish` events and + not at the end, so the leaves' tokens are counted here; the last step (the reply) may never send + its step-finish, which is why the totals can be slightly under what the run really cost.""" + prompt = _n(tokens.get("input")) + _n(tokens.get("cache_read")) + _n(tokens.get("cache_write")) + output = _n(tokens.get("output")) + _n(tokens.get("reasoning")) + return {"prompt_tokens": prompt, "completion_tokens": output, "cache_read_tokens": _n(tokens.get("cache_read")), + "cache_write_tokens": _n(tokens.get("cache_write")), "reasoning_tokens": _n(tokens.get("reasoning")), + "total_tokens": prompt + output, "model_calls": max(1, steps), "cost_usd": cost} + + +class OpenCodeStream(StreamParser): + """Cards: step_start begins one model turn, text is streamed whole, tool_use carries the part with + its state (pending = call, completed/error = result), and step_finish carries that step's tokens. + A failure prints a single `error` event.""" + + def __init__(self, session_id_re: re.Pattern[str]) -> None: + self._session_id_re = session_id_re + self.session_id: str | None = None + self.texts: list[str] = [] + self._seen: set[str] = set() + self.errors: list[str] = [] + self.steps = 0 + self._tokens: dict[str, int] = {"input": 0, "output": 0, "reasoning": 0, "cache_read": 0, "cache_write": 0} + self._cost = 0.0 + + def feed(self, event: dict) -> list[tuple[str, Any]]: + out: list[tuple[str, Any]] = [] + sid = event.get("sessionID") + if isinstance(sid, str) and sid and sid != self.session_id and self._session_id_re.match(sid): + self.session_id = sid + out.append(("session", sid)) + kind = event.get("type") + part = event.get("part") if isinstance(event.get("part"), dict) else {} + if kind == "error": + message = (event.get("error") or {}).get("message") + if isinstance(message, str) and message: + self.errors.append(message) + elif kind == "text": + text = str(part.get("text", "")) + if text.strip(): + self.texts.append(text) + out.append(("text", text)) + elif kind == "step_start": + self.steps += 1 + elif kind == "step_finish": + tokens = (part.get("tokens") or {}) if isinstance(part.get("tokens"), dict) else {} + cache = tokens.get("cache") if isinstance(tokens.get("cache"), dict) else {} + for key in ("input", "output", "reasoning"): + self._tokens[key] += _n(tokens.get(key)) + for key in ("read", "write"): + self._tokens[f"cache_{key}"] += _n(cache.get(key)) + self._cost += _f(part.get("cost")) + elif kind == "tool_use" and part.get("type") == "tool": + state = (part.get("state") or {}) if isinstance(part.get("state"), dict) else {} + call_id, name = str(part.get("id", "")), str(part.get("tool", "tool")) + status = str(state.get("status", "")) + if status == "pending": + out.append(("tool_call", {"id": call_id, "name": name, "args": (state.get("input") or {})})) + self._seen.add(call_id) + elif status in ("completed", "error"): + call = None if call_id in self._seen else {"id": call_id, "name": name, + "args": (state.get("input") or {})} + result = ("tool_result", {"tool_call_id": call_id, "name": name, + "status": "error" if status == "error" else "success", + "content": _result_text(state)}) + self._seen.add(call_id) + if call: + out.append(("tool_call", call)) + out.append(result) + return out + + def usage_so_far(self) -> dict[str, int | float] | None: + return usage_of(self.steps, self._tokens, self._cost) if self.steps else None + + def finish(self, *, exit_code: int, stderr: str, resumed: bool, baseline: dict | None) -> TurnResult: + errors = " ".join(e for e in self.errors if e) + detail = (errors or stderr.strip())[-1000:] + if exit_code != 0 or self.errors: + if resumed and _UNKNOWN_SESSION.search(detail): + raise UnknownSession + raise CliAgentError(f"error: opencode run failed (exit {exit_code})" + (f": {detail}" if detail else ""), + usage=usage_of(self.steps, self._tokens, self._cost)) + return TurnResult(text="\n\n".join(self.texts), usage=usage_of(self.steps, self._tokens, self._cost), + session_id=self.session_id) + + +class OpenCode(CliAdapter): + provider = "opencode" + label = "OpenCode" + binary = "opencode" + path_setting = "opencode_path" + install_hint = "Install it (https://opencode.ai), log in once in a terminal (`opencode auth login`), then restart OpenBot." + status_argv = () + login_hint = "Run `opencode auth login` in a terminal." + session_id_re = re.compile(r"^ses_[A-Za-z0-9_-]{8,64}$") + + def install_dirs(self, *, home: str, env: Mapping[str, str], win: bool) -> list[str]: + p = ntpath if win else posixpath + if not win: + return [p.join(home, ".opencode", "bin", "opencode"), p.join(home, ".local", "bin", "opencode"), + "/usr/local/bin/opencode", "/opt/homebrew/bin/opencode"] + found = [p.join(home, ".opencode", "bin", "opencode.exe")] + if env.get("APPDATA"): + found.append(p.join(env["APPDATA"], "npm", "opencode.cmd")) + if env.get("LOCALAPPDATA"): + found.append(p.join(env["LOCALAPPDATA"], "Programs", "opencode", "opencode.exe")) + return found + + def argv(self, executable: str, turn: Turn) -> list[str]: + argv = [executable, "run", "--format", "json"] + if turn.model: + argv += ["--model", turn.model] + if turn.session_id: + argv += ["--session", turn.session_id] + return argv + + def parser(self) -> OpenCodeStream: + return OpenCodeStream(self.session_id_re) + + def turn_env(self, turn: Turn) -> dict[str, str]: + return {"OPENCODE_PERMISSION": json.dumps(_PERMISSIONS[turn.permission])} diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 952f296e..2d433d8f 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -8,6 +8,13 @@ from langgraph.checkpoint.memory import InMemorySaver from langgraph.store.memory import InMemoryStore +# `openbot.main` runs `create_app()` at import time (main.py:334), which calls +# `configure_logging(Settings())`. The default log file lives beside the database and the test +# sandbox cannot create files, so pin LOG_FILE to the null device so logging is discarded instead +# of crashing on a missing directory. `_hermetic_env` deletes it per test afterwards, and the +# `settings` fixture sets `log_file` explicitly, so nothing leaks between tests. +os.environ.setdefault("LOG_FILE", "nul") + from openbot.config import Settings from openbot.db.session import create_all, make_engine, make_session_factory from openbot.main import create_app diff --git a/backend/tests/fixtures/hermes_turn.jsonl b/backend/tests/fixtures/hermes_turn.jsonl new file mode 100644 index 00000000..c2e1b98e --- /dev/null +++ b/backend/tests/fixtures/hermes_turn.jsonl @@ -0,0 +1,5 @@ +{"type": "system", "subtype": "init", "model": "", "session_id": "", "timestamp": 1793281076747} +{"type": "tool_use", "name": "read_file", "tool_call_id": "call-dc44fbca-41c4-45f0-afee-6402de7f3ece", "input": {"path": "README.md"}, "timestamp": 1793281100698} +{"type": "tool_result", "name": "read_file", "tool_call_id": "call-dc44fbca-41c4-45f0-afee-6402de7f3ece", "output": "{\"content\": \"\", \"total_lines\": 0, \"file_size\": 0, \"truncated\": false, \"is_binary\": false, \"is_image\": false, \"error\": \"File not found: C:\\\\Users\\\\amrmo\\\\openbot\\\\backend\\\\README.md\", \"not_found\": true}", "duration_ms": 4500, "is_error": true, "timestamp": 1793281105199} +{"type": "text", "text": "\n\ndone", "timestamp": 1793281107525} +{"type": "result", "session_id": "local-f8a2486360628ec24a6bd3cc163cab1b48f1d40ada43388761337f1900caeb59", "exit_code": 0, "text": "done", "tokens": {"input": 70563, "output": 104, "total": 70667, "cache_read": 35200, "cache_write": 0}, "duration_ms": 38041, "timestamp": 1793281114788} diff --git a/backend/tests/fixtures/opencode_turn.jsonl b/backend/tests/fixtures/opencode_turn.jsonl new file mode 100644 index 00000000..2964b00e --- /dev/null +++ b/backend/tests/fixtures/opencode_turn.jsonl @@ -0,0 +1,5 @@ +{"type":"step_start","timestamp":1793281112107,"sessionID":"ses_e781de948ffeGNRK4O3BZJgy62","part":{"id":"prt_187e2382b001iW5K5ektLppN1v","sessionID":"ses_e781de948ffeGNRK4O3BZJgy62","messageID":"msg_187e2283c001T153WPc9crWgol","type":"step-start"}} +{"type":"tool_use","timestamp":1793281113814,"sessionID":"ses_e781de948ffeGNRK4O3BZJgy62","part":{"partID":"prt_187e2393d0019DIorLt0yQNj58","sessionID":"ses_e781de948ffeGNRK4O3BZJgy62","messageID":"msg_187e2283c001T153WPc9crWgol","type":"tool","id":"call-1e36b070-204a-4541-be05-d0d3a6759ac7","tool":"glob","state":{"status":"completed","input":{"pattern":"*","path":"C:\\Users\\amrmo\\AppData\\Local\\Temp\\opencode\\oc_probe1"},"output":"No files found","title":"glob","metadata":{"metadata":{"count":0,"truncated":false},"content":[{"type":"text","text":"No files found"}],"providerCall":{"executed":false},"providerResult":{"executed":false},"rawInput":"{\"pattern\": \"*\", \"path\": \"C:\\\\Users\\\\amrmo\\\\AppData\\\\Local\\\\Temp\\\\opencode\\\\oc_probe1\"}"},"time":{"start":1793281112381,"end":1793281113814}}}} +{"type":"step_finish","timestamp":1793281113818,"sessionID":"ses_e781de948ffeGNRK4O3BZJgy62","part":{"id":"prt_187e23eda001FbGAASrXGwalUG","sessionID":"ses_e781de948ffeGNRK4O3BZJgy62","messageID":"msg_187e2283c001T153WPc9crWgol","type":"step-finish","reason":"tool-calls","cost":0,"tokens":{"input":167981,"output":43,"reasoning":27,"cache":{"read":1280,"write":0}}}} +{"type":"step_start","timestamp":1793281122137,"sessionID":"ses_e781de948ffeGNRK4O3BZJgy62","part":{"id":"prt_187e25f59001cYnCvdpzZD9Psy","sessionID":"ses_e781de948ffeGNRK4O3BZJgy62","messageID":"msg_187e23f8a001Y3NPuxBEpqwT6G","type":"step-start"}} +{"type":"text","timestamp":1793281130105,"sessionID":"ses_e781de948ffeGNRK4O3BZJgy62","part":{"id":"prt_187e272fe001sFgMC01b6SQVYC_text-0","sessionID":"ses_e781de948ffeGNRK4O3BZJgy62","messageID":"msg_187e272fe001sFgMC01b6SQVYC","type":"text","text":"The current directory is empty ΓÇö no files or folders found.\n\ndone","time":{"start":1793281127185,"end":1793281130105}}} diff --git a/backend/tests/test_cli_agents.py b/backend/tests/test_cli_agents.py index 364d3737..95e31bed 100644 --- a/backend/tests/test_cli_agents.py +++ b/backend/tests/test_cli_agents.py @@ -790,3 +790,126 @@ async def test_cli_status_says_why_the_cli_is_unusable(client, settings, fake, t def test_settings_default_timeout(settings): assert settings.cli_agent_timeout == 1800 and settings.claude_code_path is None + + +# --- hermes and opencode (recorded real captures) ------------------------------------------------------ + +HERMES = ADAPTERS["hermes"] +OPENCODE = ADAPTERS["opencode"] +HERMES_TURN = (FIXTURES / "hermes_turn.jsonl").read_text(encoding="utf-8").splitlines() +OPENCODE_TURN = (FIXTURES / "opencode_turn.jsonl").read_text(encoding="utf-8").splitlines() +HERMES_SESSION = "local-f8a2486360628ec24a6bd3cc163cab1b48f1d40ada43388761337f1900caeb59" +OPENCODE_SESSION = "ses_e781de948ffeGNRK4O3BZJgy62" + + +def test_hermes_and_opencode_are_registered_with_their_install_hints(): + assert adapter_for("hermes") is HERMES and adapter_for("opencode") is OPENCODE + assert HERMES.binary == "hermes" and HERMES.path_setting == "hermes_path" + assert OPENCODE.binary == "opencode" and OPENCODE.path_setting == "opencode_path" + assert HERMES.status_argv == () and OPENCODE.status_argv == () + + +def test_hermes_edit_runs_the_file_toolset_only(): + turn = Turn(system_prompt_file="/tmp/p.md", session_id=None, model="m-1", permission=EDIT, cwd=r"C:\w") + assert HERMES.argv("hermes", turn) == [ + "hermes", "chat", "--format", "stream-json", "--query-file", "-", + "--in", r"C:\w", "-t", "file", "--model", "m-1"] + + +def test_hermes_read_only_limits_toolsets_and_a_resumed_turn_still_does(): + turn = Turn(system_prompt_file="/tmp/p.md", session_id=HERMES_SESSION, model="", permission=READ_ONLY) + assert HERMES.argv("hermes", turn) == [ + "hermes", "chat", "--format", "stream-json", "--query-file", "-", + "-t", "search,vision,todo,session_search", "--resume", HERMES_SESSION] + + +def test_hermes_prefixes_the_system_prompt_onto_the_stdin_prompt(): + assert HERMES.combine("please build it", "You are working for thread t.\n") == \ + "You are working for thread t.\n\nplease build it" + assert HERMES.combine("please build it", "") == "please build it" + + +def test_hermes_parser_turns_the_recorded_stream_into_run_actions(): + p = HERMES.parser() + actions = [a for line in HERMES_TURN for a in p.feed(json.loads(line))] + assert [k for k, _ in actions] == ["init", "tool_call", "tool_result", "text", "session"] + assert actions[0][1] == {} # model and session_id are still empty on the CLI's init + assert actions[1][1] == {"id": "call-dc44fbca-41c4-45f0-afee-6402de7f3ece", "name": "read_file", + "args": {"path": "README.md"}} + assert actions[2][1]["status"] == "error" and '"not_found": true' in actions[2][1]["content"] + assert actions[3][1].endswith("done") + result = p.finish(exit_code=0, stderr="", resumed=False, baseline=None) + assert result.text == "done" and result.session_id == HERMES_SESSION + assert result.usage == {"prompt_tokens": 70563 + 35200, "completion_tokens": 104, "cache_read_tokens": 35200, + "cache_write_tokens": 0, "reasoning_tokens": 0, + "total_tokens": 70563 + 35200 + 104, "model_calls": 1, "cost_usd": 0.0} + + +def test_hermes_a_gone_session_raises_unknown_and_a_failure_keeps_its_usage(): + error = {"type": "result", "session_id": "", "exit_code": 1, "text": "", + "tokens": {"input": 0, "output": 0, "total": 0, "cache_read": 0, "cache_write": 0}, + "error": "No session found matching 'a1b2c3d4-1111'. Use 'hermes sessions list'."} + p = HERMES.parser() + p.feed(error) + with pytest.raises(base.UnknownSession): + p.finish(exit_code=1, stderr="Error: No session found matching 'a1b2c3d4-1111'.", resumed=True, baseline=None) + p = HERMES.parser() + p.feed({**error, "error": "rate limited"}) + with pytest.raises(base.CliAgentError) as exc: + p.finish(exit_code=1, stderr="", resumed=False, baseline=None) + assert exc.value.usage["model_calls"] == 1 and exc.value.usage["total_tokens"] == 0 + + +def test_hermes_a_crash_without_a_result_reports_stderr(): + with pytest.raises(base.CliAgentError, match="without a result"): + HERMES.parser().finish(exit_code=2, stderr="Traceback: gone", resumed=False, baseline=None) + + +def test_opencode_argv_formats_passes_session_and_model_and_nothing_privileged(): + turn = Turn(system_prompt_file="/tmp/p.md", session_id=None, model="", permission=READ_ONLY) + assert OPENCODE.argv("opencode", turn) == ["opencode", "run", "--format", "json"] + turn = Turn(system_prompt_file="/tmp/p.md", session_id=OPENCODE_SESSION, model="org/model", permission=EDIT) + assert OPENCODE.argv("opencode", turn) == ["opencode", "run", "--format", "json", "--model", "org/model", + "--session", OPENCODE_SESSION] + + +@pytest.mark.parametrize("permission", [READ_ONLY, EDIT]) +def test_opencode_permissions_allow_reads_and_never_run_commands_or_reach_the_wider_web(permission): + env = OPENCODE.turn_env(Turn(system_prompt_file="", session_id=None, model="", permission=permission)) + perms = json.loads(env["OPENCODE_PERMISSION"]) + assert perms["read"] == "allow" and perms["glob"] == "allow" and perms["grep"] == "allow" + assert perms["edit"] == ("allow" if permission == EDIT else "deny") + assert {k: perms[k] for k in ("bash", "task", "webfetch", "websearch", "skill")} == dict.fromkeys( + ("bash", "task", "webfetch", "websearch", "skill"), "deny") + + +def test_opencode_parser_turns_the_recorded_stream_into_run_actions(): + p = OPENCODE.parser() + actions = [a for line in OPENCODE_TURN for a in p.feed(json.loads(line))] + assert [k for k, _ in actions] == ["session", "tool_call", "tool_result", "text"] + assert p.session_id == OPENCODE_SESSION + assert actions[1][1]["name"] == "glob" and actions[1][1]["args"]["pattern"] == "*" + assert actions[2][1]["status"] == "success" and actions[2][1]["tool_call_id"] == actions[1][1]["id"] + result = p.finish(exit_code=0, stderr="", resumed=False, baseline=None) + assert result.text.endswith("done") and result.session_id == OPENCODE_SESSION + assert result.usage == {"prompt_tokens": 167981 + 1280, "completion_tokens": 43 + 27, "cache_read_tokens": 1280, + "cache_write_tokens": 0, "reasoning_tokens": 27, "total_tokens": 167981 + 1280 + 70, + "model_calls": 2, "cost_usd": 0.0} + + +def test_opencode_a_pending_call_only_reports_its_result_once(): + p = OPENCODE.parser() + p.feed({"type": "tool_use", "timestamp": 1, "sessionID": OPENCODE_SESSION, + "part": {"type": "tool", "id": "c1", "tool": "edit", "state": {"status": "pending", "input": {}}}}) + out = p.feed({"type": "tool_use", "timestamp": 2, "sessionID": OPENCODE_SESSION, + "part": {"type": "tool", "id": "c1", "tool": "edit", + "state": {"status": "completed", "input": {}, "output": "ok"}}}) + assert [k for k, _ in out] == ["tool_result"] and out[0][1]["content"] == "ok" + + +def test_opencode_an_error_stream_fails_the_run(): + p = OPENCODE.parser() + p.feed({"type": "error", "timestamp": 1, "sessionID": "", + "error": {"type": "unknown", "message": 'Expected a string starting with "ses"'}}) + with pytest.raises(base.CliAgentError, match='starting with "ses"'): + p.finish(exit_code=1, stderr="", resumed=True, baseline=None) From 03f721e07f6d55144f7dea2b11132c7f7e69368f Mon Sep 17 00:00:00 2001 From: Hermes Agent Date: Tue, 24 Nov 2026 13:04:37 +0200 Subject: [PATCH 2/2] Update the providers test for the three CLI agent adapters Upstream's test asserted cli_agents held exactly one entry (claude-code), which held while it was the only adapter. With Hermes and OpenCode registered, the providers endpoint lists all three, so the assertion has to cover them. Pin every adapter's path setting, not just claude_code_path: without that, ound depends on what happens to be installed on the developer's PATH, and a machine with hermes or opencode installed would fail a test that passes in CI. --- backend/tests/test_cli_agents.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/backend/tests/test_cli_agents.py b/backend/tests/test_cli_agents.py index 95e31bed..74098813 100644 --- a/backend/tests/test_cli_agents.py +++ b/backend/tests/test_cli_agents.py @@ -752,10 +752,16 @@ async def test_api_accepts_cli_bots_without_a_model_and_checks_their_settings(cl async def test_providers_lists_the_cli_by_whether_it_is_found_without_running_it(client, settings, fake, tmp_path): home, exe = fake + # All three adapters, not just claude-code. Pin every path so `found` is deterministic and does + # not depend on what happens to be installed on this machine's PATH. settings.claude_code_path = str(tmp_path / "no-claude") + settings.hermes_path = str(tmp_path / "no-hermes") + settings.opencode_path = str(tmp_path / "no-opencode") r = await client.get("/api/v1/providers") assert r.json()["cli_agents"] == [{"id": "claude-code", "label": "Claude Code", "found": False, - "models": ["sonnet", "opus", "haiku"]}] + "models": ["sonnet", "opus", "haiku"]}, + {"id": "hermes", "label": "Hermes", "found": False, "models": []}, + {"id": "opencode", "label": "OpenCode", "found": False, "models": []}] assert "claude-code" not in {p["id"] for p in r.json()["providers"]} settings.claude_code_path = str(exe) assert (await client.get("/api/v1/providers")).json()["cli_agents"][0]["found"] is True