Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(agent-runtimes): ACP turn client and Hermes/OpenClaw spike

rubenluetke10-beep304b802e35ad
diff --git a/docs/agent-runtimes.md b/docs/agent-runtimes.md
new file mode 100644
index 0000000000..c903402b20
--- /dev/null
+++ b/docs/agent-runtimes.md
@@ -0,0 +1,95 @@
+# Agent runtimes: Hermes and OpenClaw
+
+A society agent runs on one of three runtimes:
+
+| Runtime | What executes a turn | Default |
+|---|---|---|
+| `jarvis` | Jarvis' own brain or the CLI seat the agent's model picks (Claude Code, Codex, …) | yes |
+| `hermes` | [Hermes Agent](https://github.com/NousResearch/hermes-agent) (NousResearch, MIT) | |
+| `openclaw` | [OpenClaw](https://github.com/openclaw/openclaw) (MIT) | |
+
+The runtime decides which agent loop, native tools and session store a turn
+uses. Everything that makes a Jarvis agent stays in Jarvis and is identical
+on every runtime: the one endless chat, the briefing (identity, standing
+instructions, memory head, learned skills, teammates), the memory notebooks,
+the learning loop, routines, delegation, quests, island checkpoints and
+approvals. The runtime reaches all of that through the Jarvis MCP tools.
+
+## Why ACP
+
+Both projects ship an [Agent Client Protocol](https://agentclientprotocol.com)
+server (JSON-RPC 2.0 over stdio) and document it as the interface for
+embedding hosts. Jarvis drives both through it, plus a handful of documented
+CLI commands, and never imports their internals or speaks their private wire
+formats. An upstream update keeps working as long as the protocol does;
+capabilities are read from the `initialize` answer, not from version strings.
+
+`jarvis/agent_runtimes/acp.py` is the transport-free client for one turn:
+`initialize` → `session/load` or `session/new` → `session/prompt`, translating
+`session/update` notifications into agent-chat events (`text_delta`,
+`assistant_text`, `reasoning`, `tool_call`, `tool_result`, `usage_delta`) and
+answering `session/request_permission` from the chat's approval card. History
+replayed during `session/load` is swallowed because the chat already shows it.
+
+## Hermes
+
+- **Process:** `hermes acp`, one process per turn, stdin EOF ends it (exit 0).
+- **Isolation:** one Hermes profile per agent, `HERMES_HOME` under Jarvis' data
+ directory. The user's own `~/.hermes` / default profile is never touched.
+- **Config Jarvis writes** (`config.yaml`): `model.provider` / `model.default` /
+ `model.base_url`, `terminal.cwd` = the agent workspace, Hermes' own memory
+ and skill nudges off (Jarvis owns memory and skills), and `SOUL.md` = the
+ agent's Jarvis briefing. Provider keys go into the process environment only.
+- **Jarvis tools:** passed per session in `session/new` / `session/load`
+ `mcpServers` (HTTP with headers); `HERMES_ACP_SKIP_CONFIGURED_MCP=1` keeps
+ any configured servers out. Hermes names them `mcp__jarvis__<tool>`.
+- **Sessions:** persisted in the profile's `state.db`; `session/load` restores
+ a conversation in a new process and replays it. An unknown id answers
+ `session/load` with an empty result, which Jarvis treats as "resume lost" and
+ retries fresh with the transcript in front.
+- **Tool search:** Hermes defers MCP schemas behind its own `tool_search` by
+ default. Jarvis keeps that native behaviour; tests switch it off
+ (`tools.tool_search: false`) so a scripted model sees the tools.
+
+## OpenClaw
+
+- **Process model:** the documented embedding path (`docs/gateway/embedding.md`
+ upstream): Jarvis supervises an OpenClaw Gateway child with the embedding
+ preset (`OPENCLAW_SKIP_CHANNELS=1`, `OPENCLAW_NO_RESPAWN=1`,
+ `OPENCLAW_DISABLE_BONJOUR=1`, `OPENCLAW_EXEC_SHELL_SNAPSHOT=0`) and drives
+ each turn through the version-matched `openclaw acp` bridge
+ (`--url ws://127.0.0.1:<port> --session agent:main:main`). No hand-written
+ Gateway WebSocket client: its wire protocol requires an exact version match.
+- **Isolation:** one state directory (`OPENCLAW_STATE_DIR`,
+ `OPENCLAW_CONFIG_PATH`) and one Gateway per agent, on its own loopback port,
+ started on the first turn and stopped after an idle period. Start-up is
+ about 16 s on Windows with the preset (measured with 2026.9.8). The user's
+ own `~/.openclaw` and their Gateway service are never touched.
+- **Config Jarvis writes** (`openclaw.json`, only long-stable keys):
+ `gateway.{mode,port,bind,auth}`, `models.providers.<id>` for the agent's
+ model, `agents.defaults.{model.primary,workspace,heartbeat.every:"0m"}`,
+ `session.reset.mode:"none"`, `mcp.servers.jarvis`, and `tools.deny` for
+ native tools that duplicate Jarvis features (automations, messaging).
+ A Gateway exit code 78 (invalid config) runs
+ `openclaw doctor --fix --yes --non-interactive` once, then retries.
+- **Jarvis tools:** OpenClaw rejects per-session `mcpServers`, so the Jarvis
+ server is configured in the agent's own state directory. Values such as
+ `${JARVIS_CONTROL_API_KEY}` are substituted from the Gateway's environment,
+ so no key is written to disk. OpenClaw names them `jarvis__<tool>`; Jarvis
+ normalises that to `mcp__jarvis__<tool>`.
+- **Sessions:** the fixed session key keeps one conversation across bridge
+ processes; the ACP session id changes per process and is not stored.
+- **Heartbeat:** OpenClaw runs a background model turn every 30 minutes by
+ default. Jarvis sets `heartbeat.every: "0m"` for every agent: nothing the
+ person did not start may bill a key.
+- **Node:** OpenClaw 2026.9 requires Node `>=24.16 <25 || >=26.1`. The runtime
+ manager reports an unsuitable Node instead of failing a turn.
+
+## Spike
+
+`scripts/spikes/agent_runtimes_probe.py hermes|openclaw` drives a real
+runtime against `tests/fakes/fake_openai_server.py` (a scripted
+OpenAI-compatible model), so no paid key is involved. Verified 2026-10-06 with
+Hermes 0.20.6 and OpenClaw 2026.9.8 on Windows: new session, an MCP tool call
+with the right session header, resume in a new process, unknown-session
+handling.
diff --git a/jarvis/agent_runtimes/__init__.py b/jarvis/agent_runtimes/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/jarvis/agent_runtimes/acp.py b/jarvis/agent_runtimes/acp.py
new file mode 100644
index 0000000000..b5a6a6482f
--- /dev/null
+++ b/jarvis/agent_runtimes/acp.py
@@ -0,0 +1,545 @@
+"""Client side of one Agent Client Protocol (ACP) prompt turn.
+
+ACP is JSON-RPC 2.0 over the agent process' stdio, one JSON object per line
+(https://agentclientprotocol.com). Hermes (``hermes acp``) and OpenClaw
+(``openclaw acp``) both speak it, and it is the interface their projects
+version and document for embedding hosts — which is why Jarvis drives them
+through it instead of their CLI flags or internal APIs: an upstream update
+keeps working as long as the protocol does.
+
+One :class:`AcpTurn` drives one process from handshake to the prompt's
+response:
+
+1. ``initialize`` (protocol version + client capabilities),
+2. ``session/load`` of the stored conversation, or ``session/new``,
+3. ``session/prompt`` with the turn's text,
+
+and translates every ``session/update`` notification into agent-chat events
+(``assistant_text``, ``reasoning``, ``tool_call``, ``tool_result``,
+``usage_delta``). The agent's own ``session/request_permission`` requests are
+answered from the chat's approval card. History replayed during
+``session/load`` is swallowed: the chat already shows it.
+
+The class is transport-free: the CLI runner pumps lines into
+:meth:`AcpTurn.on_message` and supplies an :class:`AcpIO` for writing frames,
+emitting events and asking the person. That keeps process ownership (job
+objects, cancellation, remote placement, rollover) in one place.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+import time
+import uuid
+from dataclasses import dataclass, field
+from typing import Any, Final, Protocol
+
+from jarvis.agent_chat.events import make_event
+
+log = logging.getLogger(__name__)
+
+#: ACP protocol major version this client speaks.
+PROTOCOL_VERSION: Final[int] = 1
+
+_INITIALIZE_ID: Final[int] = 1
+_SESSION_ID: Final[int] = 2
+_PROMPT_ID: Final[int] = 3
+
+#: Error text the CLI runner's resume-lost detection recognises
+#: (``runner_cli._RESUME_LOST_MARKERS``) so a vanished conversation is
+#: retried fresh with the transcript in front.
+RESUME_LOST_ERROR: Final[str] = "ACP session not found"
+
+#: JSON-RPC "method not found".
+_METHOD_NOT_FOUND: Final[int] = -32601
+
+#: ``mcp_<server>_<tool>`` (Hermes) and ``<server>__<tool>`` spellings of a
+#: Jarvis MCP tool, normalised to the ``mcp__jarvis__<tool>`` form the
+#: society checkpoints and quests read.
+_JARVIS_TOOL_PREFIXES: Final[tuple[str, ...]] = ("mcp_jarvis_", "jarvis__", "jarvis.")
+_IDENTIFIER: Final[re.Pattern[str]] = re.compile(r"^[A-Za-z_][\w.:-]{0,120}$")
+
+
+class AcpIO(Protocol):
+ """What a turn needs from its host."""
+
+ async def write(self, frame: dict[str, Any]) -> None: ...
+
+ async def emit(self, event: dict[str, Any]) -> None: ...
+
+ async def ask(self, call_id: str, name: str, args: dict[str, Any], summary: str) -> str:
+ """Answer ``allow`` / ``allow_always`` / ``deny`` / ``cancel``."""
+ ...
+
+
+@dataclass(slots=True)
+class McpServer:
+ """One MCP server handed to the agent with ``session/new``/``session/load``."""
+
+ name: str
+ url: str = ""
+ headers: dict[str, str] = field(default_factory=dict)
+ command: str = ""
+ args: list[str] = field(default_factory=list)
+ env: dict[str, str] = field(default_factory=dict)
+
+ def to_acp(self) -> dict[str, Any]:
+ if self.command:
+ return {
+ "name": self.name,
+ "command": self.command,
+ "args": list(self.args),
+ "env": [{"name": k, "value": v} for k, v in self.env.items()],
+ }
+ return {
+ "type": "http",
+ "name": self.name,
+ "url": self.url,
+ "headers": [{"name": k, "value": v} for k, v in self.headers.items()],
+ }
+
+
+def normalize_tool_name(name: str) -> str:
+ """Give a Jarvis MCP tool the ``mcp__jarvis__<tool>`` name Jarvis reads."""
+ if name.startswith("mcp__"):
+ return name
+ for prefix in _JARVIS_TOOL_PREFIXES:
+ if name.startswith(prefix):
+ return "mcp__jarvis__" + name[len(prefix) :]
+ return name
+
+
+def _content_text(content: Any) -> str:
+ """Text of an ACP content block, a list of them, or a tool-call content list."""
+ if content is None:
+ return ""
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ return "".join(_content_text(item) for item in content)
+ if isinstance(content, dict):
+ if content.get("type") == "text":
+ return str(content.get("text") or "")
+ if content.get("type") == "content":
+ return _content_text(content.get("content"))
+ if content.get("type") == "diff":
+ return f"edited {content.get('path') or 'a file'}"
+ if "text" in content:
+ return str(content.get("text") or "")
+ return ""
+
+
+@dataclass(slots=True)
+class AcpTurn:
+ """State of one ACP turn; mirrors the CLI runner's per-shape state fields."""
+
+ turn_id: str
+ cwd: str
+ prompt_text: str
+ resume: str | None = None
+ mcp_servers: list[McpServer] = field(default_factory=list)
+ #: Answer the agent's permission requests with "allow" without asking
+ #: (the chat's Bypass stance). Jarvis' own gates on MCP tools still apply.
+ auto_allow: bool = False
+ client_name: str = "personal-jarvis"
+ client_version: str = ""
+
+ # --- fields the CLI runner reads after the turn ---
+ vendor_session: str | None = None
+ status: str = "done"
+ error: str | None = None
+ usage: dict[str, int] = field(default_factory=dict)
+ cost_usd: float | None = None
+ emitted_text: bool = False
+ result_text: str = ""
+ saw_result: bool = False
+ stop_reason: str = ""
+ emitted_tool_ids: set[str] = field(default_factory=set)
+
+ # --- what the agent announced in ``initialize`` ---
+ agent_name: str = ""
+ agent_version: str = ""
+ can_load: bool = False
+
+ _replaying: bool = field(default=False, init=False)
+ _text_id: str = field(default="", init=False)
+ _text_parts: list[str] = field(default_factory=list, init=False)
+ _thought_parts: list[str] = field(default_factory=list, init=False)
+ _thought_started: float | None = field(default=None, init=False)
+ _tool_names: dict[str, str] = field(default_factory=dict, init=False)
+ _tool_started: dict[str, float] = field(default_factory=dict, init=False)
+ _finished_tools: set[str] = field(default_factory=set, init=False)
+
+ # ------------------------------------------------------------------ frames
+
+ def opening_frame(self) -> str:
+ """The ``initialize`` request, written as soon as the process starts."""
+ return frame_line(
+ {
+ "jsonrpc": "2.0",
+ "id": _INITIALIZE_ID,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": PROTOCOL_VERSION,
+ # No fs / terminal capability: the agent uses its own tools
+ # in its own working folder; Jarvis is not an editor.
+ "clientCapabilities": {
+ "fs": {"readTextFile": False, "writeTextFile": False},
+ "terminal": False,
+ },
+ "clientInfo": {
+ "name": self.client_name,
+ "version": self.client_version or "0",
+ },
+ },
+ }
+ )
+
+ def _session_params(self) -> dict[str, Any]:
+ return {"cwd": self.cwd, "mcpServers": [s.to_acp() for s in self.mcp_servers]}
+
+ # ---------------------------------------------------------------- dispatch
+
+ async def on_message(self, obj: dict[str, Any], io: AcpIO) -> None:
+ """Handle one JSON object read from the agent's stdout."""
+ method = obj.get("method")
+ if isinstance(method, str):
+ if "id" in obj and obj.get("id") is not None:
+ await self._on_agent_request(obj, method, io)
+ elif method == "session/update":
+ params = obj.get("params") if isinstance(obj.get("params"), dict) else {}
+ if not self._replaying:
+ await self._on_update(params, io)
+ return
+ if "id" in obj:
+ await self._on_response(obj, io)
+
+ async def _on_response(self, obj: dict[str, Any], io: AcpIO) -> None:
+ rid = obj.get("id")
+ error = obj.get("error") if isinstance(obj.get("error"), dict) else None
+ result = obj.get("result")
+ if rid == _INITIALIZE_ID:
+ if error is not None:
+ self._fail(f"ACP initialize failed: {_error_text(error)}")
+ return
+ res = result if isinstance(result, dict) else {}
+ info = res.get("agentInfo") if isinstance(res.get("agentInfo"), dict) else {}
+ self.agent_name = str(info.get("name") or "")
+ self.agent_version = str(info.get("version") or "")
+ caps = (
+ res.get("agentCapabilities")
+ if isinstance(res.get("agentCapabilities"), dict)
+ else {}
+ )
+ self.can_load = bool(caps.get("loadSession"))
+ if self.resume and self.can_load:
+ self._replaying = True
+ params = self._session_params() | {"sessionId": self.resume}
+ await io.write(_request(_SESSION_ID, "session/load", params))
+ elif self.resume:
+ # The agent cannot reopen conversations: let the runner start
+ # fresh with the transcript in front instead.
+ self._fail(f"{RESUME_LOST_ERROR}: this agent cannot load sessions")
+ else:
+ await io.write(_request(_SESSION_ID, "session/new", self._session_params()))
+ return
+ if rid == _SESSION_ID:
+ self._replaying = False
+ # Hermes answers an unknown id with an empty result ({}), the
+ # spec with null or an error; a real load always describes the
+ # session (models, modes, _meta).
+ if error is not None or (self.resume and not result):
+ if self.resume:
+ detail = _error_text(error) if error else "unknown id"
+ self._fail(f"{RESUME_LOST_ERROR}: {detail}")
+ else:
+ self._fail(f"ACP session/new failed: {_error_text(error or {})}")
+ return
+ res = result if isinstance(result, dict) else {}
+ self.vendor_session = str(res.get("sessionId") or self.resume or "") or None
+ if not self.vendor_session:
+ self._fail("ACP session/new returned no session id")
+ return
+ await io.write(
+ _request(
+ _PROMPT_ID,
+ "session/prompt",
+ {
+ "sessionId": self.vendor_session,
+ "prompt": [{"type": "text", "text": self.prompt_text}],
+ },
+ )
+ )
+ return
+ if rid == _PROMPT_ID:
+ await self._flush_thought(io)
+ await self._flush_text(io)
+ self.saw_result = True
+ if error is not None:
+ self._fail(_error_text(error))
+ return
+ res = result if isinstance(result, dict) else {}
+ self.stop_reason = str(res.get("stopReason") or "")
+ self._take_usage(res.get("usage"))
+ if self.stop_reason == "refusal" and not self.emitted_text:
+ self._fail("The model refused this request.")
+ elif self.stop_reason in {"max_tokens", "max_turn_requests"} and not self.emitted_text:
+ self._fail(f"The agent stopped early ({self.stop_reason}).")
+ return
+
+ async def _on_agent_request(self, obj: dict[str, Any], method: str, io: AcpIO) -> None:
+ rid = obj.get("id")
+ params = obj.get("params") if isinstance(obj.get("params"), dict) else {}
+ if method == "session/request_permission":
+ outcome = await self._permission(params, io)
+ await io.write({"jsonrpc": "2.0", "id": rid, "result": {"outcome": outcome}})
+ return
+ # fs/*, terminal/* and anything newer: not offered in initialize.
+ await io.write(
+ {
+ "jsonrpc": "2.0",
+ "id": rid,
+ "error": {"code": _METHOD_NOT_FOUND, "message": f"{method} is not supported"},
+ }
+ )
+
+ async def _permission(self, params: dict[str, Any], io: AcpIO) -> dict[str, Any]:
+ options = [o for o in params.get("options") or [] if isinstance(o, dict)]
+ by_kind: dict[str, str] = {}
+ for option in options:
+ kind = str(option.get("kind") or "")
+ if kind and kind not in by_kind:
+ by_kind[kind] = str(option.get("optionId") or "")
+ call = params.get("toolCall") if isinstance(params.get("toolCall"), dict) else {}
+ call_id = str(call.get("toolCallId") or uuid.uuid4().hex)
+ name = self._tool_names.get(call_id) or _tool_name(call)
+ args = call.get("rawInput") if isinstance(call.get("rawInput"), dict) else {}
+ summary = str(call.get("title") or name)[:200]
+ if self.auto_allow:
+ decision = "allow"
+ else:
+ await self._flush_text(io)
+ decision = await io.ask(call_id, name, args, summary)
+ wanted: tuple[str, ...]
+ if decision == "allow_always":
+ wanted = ("allow_always", "allow_once")
+ elif decision == "allow":
+ wanted = ("allow_once", "allow_always")
+ elif decision == "deny":
+ wanted = ("reject_once", "reject_always")
+ else:
+ return {"outcome": "cancelled"}
+ for kind in wanted:
+ if by_kind.get(kind):
+ return {"outcome": "selected", "optionId": by_kind[kind]}
+ return {"outcome": "cancelled"}
+
+ # ----------------------------------------------------------------- updates
+
+ async def _on_update(self, params: dict[str, Any], io: AcpIO) -> None:
+ update = params.get("update") if isinstance(params.get("update"), dict) else {}
+ kind = str(update.get("sessionUpdate") or "")
+ if kind == "agent_message_chunk":
+ await self._flush_thought(io)
+ text = _content_text(update.get("content"))
+ if text:
+ if not self._text_id:
+ self._text_id = f"acp-{self.turn_id}-{uuid.uuid4().hex[:8]}"
+ self._text_parts.append(text)
+ await io.emit(
+ make_event(
+ "text_delta",
+ {"turn_id": self.turn_id, "message_id": self._text_id, "text": text},
+ )
+ )
+ return
+ if kind == "agent_thought_chunk":
+ text = _content_text(update.get("content"))
+ if text:
+ if self._thought_started is None:
+ self._thought_started = time.perf_counter()
+ await io.emit(
+ make_event(
+ "reasoning_started",
+ {"turn_id": self.turn_id, "message_id": f"think-{self.turn_id}"},
+ )
+ )
+ self._thought_parts.append(text)
+ await io.emit(
+ make_event("reasoning_delta", {"turn_id": self.turn_id, "text": text})
+ )
+ return
+ if kind == "tool_call":
+ await self._flush_thought(io)
+ await self._flush_text(io)
+ await self._tool_start(update, io)
+ await self._tool_finish_if_done(update, io)
+ return
+ if kind == "tool_call_update":
+ call_id = str(update.get("toolCallId") or "")
+ if call_id and call_id not in self.emitted_tool_ids:
+ await self._flush_text(io)
+ await self._tool_start(update, io)
+ await self._tool_finish_if_done(update, io)
+ return
+ if kind == "usage_update":
+ self._take_usage(update)
+ if self.usage:
+ await io.emit(
+ make_event("usage_delta", {"turn_id": self.turn_id, "usage": dict(self.usage)})
+ )
+ return
+ # plan, available_commands_update, current_mode_update,
+ # session_info_update, user_message_chunk: nothing the timeline shows.
+
+ async def _tool_start(self, update: dict[str, Any], io: AcpIO) -> None:
+ call_id = str(update.get("toolCallId") or uuid.uuid4().hex)
+ if call_id in self.emitted_tool_ids:
+ return
+ name = normalize_tool_name(_tool_name(update))
+ args = update.get("rawInput") if isinstance(update.get("rawInput"), dict) else {}
+ self.emitted_tool_ids.add(call_id)
+ self._tool_names[call_id] = name
+ self._tool_started[call_id] = time.perf_counter()
+ await io.emit(
+ make_event(
+ "tool_call",
+ {
+ "turn_id": self.turn_id,
+ "call_id": call_id,
+ "name": name,
+ "input": args,
+ "summary": str(update.get("title") or name)[:200],
+ },
+ )
+ )
+
+ async def _tool_finish_if_done(self, update: dict[str, Any], io: AcpIO) -> None:
+ call_id = str(update.get("toolCallId") or "")
+ status = str(update.get("status") or "")
+ if status not in {"completed", "failed"} or call_id in self._finished_tools:
+ return
+ self._finished_tools.add(call_id)
+ output = _content_text(update.get("content"))
+ raw = update.get("rawOutput")
+ if not output and raw is not None:
+ output = raw if isinstance(raw, str) else json.dumps(raw, ensure_ascii=False)
+ is_error = status == "failed"
+ started = self._tool_started.get(call_id)
+ await io.emit(
+ make_event(
+ "tool_result",
+ {
+ "turn_id": self.turn_id,
+ "call_id": call_id,
+ "output": (output or ("failed" if is_error else "done"))[:20_000],
+ "is_error": is_error,
+ "duration_ms": int((time.perf_counter() - started) * 1000)
+ if started
+ else None,
+ },
+ )
+ )
+
+ async def _flush_text(self, io: AcpIO) -> None:
+ text = "".join(self._text_parts)
+ message_id = self._text_id
+ self._text_parts.clear()
+ self._text_id = ""
+ if not text.strip():
+ return
+ self.emitted_text = True
+ self.result_text = text
+ await io.emit(
+ make_event(
+ "assistant_text",
+ {"turn_id": self.turn_id, "message_id": message_id, "text": text},
+ )
+ )
+
+ async def _flush_thought(self, io: AcpIO) -> None:
+ if self._thought_started is None:
+ return
+ text = "".join(self._thought_parts)
+ duration = int((time.perf_counter() - self._thought_started) * 1000)
+ self._thought_parts.clear()
+ self._thought_started = None
+ await io.emit(
+ make_event(
+ "reasoning",
+ {
+ "turn_id": self.turn_id,
+ "message_id": f"think-{self.turn_id}",
+ "text": text,
+ "duration_ms": duration,
+ },
+ )
+ )
+
+ def _take_usage(self, raw: Any) -> None:
+ """Read ACP usage (``usage_update`` or the prompt response's ``usage``)."""
+ if not isinstance(raw, dict):
+ return
+ for theirs, ours in (
+ ("inputTokens", "input_tokens"),
+ ("outputTokens", "output_tokens"),
+ ("cachedReadTokens", "cached_input_tokens"),
+ ("cachedWriteTokens", "cache_write_input_tokens"),
+ ("thoughtTokens", "reasoning_output_tokens"),
+ ):
+ value = raw.get(theirs)
+ if isinstance(value, int | float):
+ self.usage[ours] = int(value)
+ cost = raw.get("cost")
+ if isinstance(cost, dict):
+ amount = cost.get("amount")
+ if isinstance(amount, int | float) and str(cost.get("currency") or "USD") == "USD":
+ self.cost_usd = float(amount)
+
+ def _fail(self, message: str) -> None:
+ self.status = "error"
+ self.error = message
+ self.saw_result = True
+
+
+def _tool_name(update: dict[str, Any]) -> str:
+ """Best tool name an ACP tool call carries.
+
+ ACP has no tool-name field; agents put it in ``_meta`` or use it as the
+ ``title`` for tools they do not render specially (Hermes does both for
+ MCP tools). A descriptive title falls back to the tool ``kind``.
+ """
+ meta = update.get("_meta") if isinstance(update.get("_meta"), dict) else {}
+ for key in ("toolName", "tool_name", "name"):
+ value = meta.get(key)
+ if isinstance(value, str) and value:
+ return value
+ title = str(update.get("title") or "").strip()
+ if title and _IDENTIFIER.match(title):
+ return title
+ if title:
+ head = title.split("(", 1)[0].split(":", 1)[0].strip()
+ if head and _IDENTIFIER.match(head):
+ return head
+ return str(update.get("kind") or "tool")
+
+
+def _error_text(error: dict[str, Any]) -> str:
+ message = str(error.get("message") or "error")
+ data = error.get("data")
+ if isinstance(data, str) and data:
+ return f"{message}: {data}"
+ if isinstance(data, dict) and data.get("message"):
+ return f"{message}: {data['message']}"
+ return message
+
+
+def _request(rid: int, method: str, params: dict[str, Any]) -> dict[str, Any]:
+ return {"jsonrpc": "2.0", "id": rid, "method": method, "params": params}
+
+
+def frame_line(frame: dict[str, Any]) -> str:
+ """One frame as the newline-terminated JSON line ACP expects on stdin."""
+ return json.dumps(frame, ensure_ascii=False) + "\n"
diff --git a/scripts/spikes/agent_runtimes_probe.py b/scripts/spikes/agent_runtimes_probe.py
new file mode 100644
index 0000000000..866e309845
--- /dev/null
+++ b/scripts/spikes/agent_runtimes_probe.py
@@ -0,0 +1,389 @@
+"""Spike: drive Hermes / OpenClaw over ACP against a fake model.
+
+Answers the open questions behind ``docs/agent-runtimes.md`` without a paid
+key: every model call goes to ``tests/fakes/fake_openai_server.py``.
+
+ python scripts/spikes/agent_runtimes_probe.py hermes
+ python scripts/spikes/agent_runtimes_probe.py openclaw
+
+Prints every raw ACP line plus the translated agent-chat events, then a
+summary: session id, whether ``session/load`` restored it in a NEW process,
+how an MCP tool is named in ``tool_call``, and whether stdin EOF ends the
+process.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import shutil
+import sys
+import tempfile
+import textwrap
+from pathlib import Path
+from typing import Any
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT))
+
+from jarvis.agent_runtimes.acp import AcpTurn, McpServer, frame_line # noqa: E402
+from tests.fakes.fake_openai_server import MODEL_ID, FakeOpenAIServer # noqa: E402
+
+MCP_SCRIPT = textwrap.dedent(
+ """
+ from mcp.server.fastmcp import FastMCP
+ app = FastMCP("jarvis")
+
+ @app.tool()
+ def society_memory_recall(query: str = "") -> str:
+ '''Recall the agent's own notes.'''
+ import os
+ return "recalled: " + query + " session=" + os.environ.get("PROBE_SESSION", "?")
+
+ app.run()
+ """
+)
+
+
+class _IO:
+ def __init__(self, proc: asyncio.subprocess.Process) -> None:
+ self.proc = proc
+ self.events: list[dict[str, Any]] = []
+
+ async def write(self, frame: dict[str, Any]) -> None:
+ print(">>", json.dumps(frame)[:300])
+ assert self.proc.stdin is not None
+ self.proc.stdin.write(frame_line(frame).encode("utf-8"))
+ await self.proc.stdin.drain()
+
+ async def emit(self, event: dict[str, Any]) -> None:
+ self.events.append(event)
+ if event["kind"] not in {"text_delta", "reasoning_delta"}:
+ print("EV", event["kind"], json.dumps(event["payload"])[:300])
+
+ async def ask(self, call_id: str, name: str, args: dict[str, Any], summary: str) -> str:
+ print("ASK", name, summary)
+ return "allow"
+
+
+async def run_turn(
+ argv: list[str], env: dict[str, str], cwd: Path, turn: AcpTurn, limit_s: float = 120
+) -> tuple[AcpTurn, _IO, int | None]:
+ proc = await asyncio.create_subprocess_exec(
+ *argv,
+ cwd=str(cwd),
+ env=env,
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ limit=16 * 1024 * 1024,
+ )
+ io = _IO(proc)
+ stderr_tail: list[str] = []
+
+ async def drain() -> None:
+ assert proc.stderr is not None
+ while line := await proc.stderr.readline():
+ stderr_tail.append(line.decode("utf-8", "replace").rstrip())
+ del stderr_tail[:-30]
+
+ async def pump() -> None:
+ assert proc.stdout is not None
+ while raw := await proc.stdout.readline():
+ line = raw.decode("utf-8", "replace").strip()
+ if not line:
+ continue
+ print("<<", line[:400])
+ try:
+ obj = json.loads(line)
+ except ValueError:
+ continue
+ if isinstance(obj, dict):
+ await turn.on_message(obj, io)
+ if turn.saw_result and proc.stdin and not proc.stdin.is_closing():
+ proc.stdin.close()
+
+ drainer = asyncio.create_task(drain())
+ assert proc.stdin is not None
+ proc.stdin.write(turn.opening_frame().encode("utf-8"))
+ await proc.stdin.drain()
+ try:
+ await asyncio.wait_for(pump(), timeout=limit_s)
+ rc = await asyncio.wait_for(proc.wait(), timeout=20)
+ except TimeoutError:
+ print("!! timeout; process still running =", proc.returncode is None)
+ proc.kill()
+ rc = None
+ drainer.cancel()
+ print("-- stderr tail:\n " + "\n ".join(stderr_tail[-12:]))
+ return turn, io, rc
+
+
+def hermes_home(base: Path, server: FakeOpenAIServer, workspace: Path) -> Path:
+ home = base / "hermes-home"
+ home.mkdir(parents=True, exist_ok=True)
+ (home / "config.yaml").write_text(
+ textwrap.dedent(
+ f"""
+ model:
+ default: {MODEL_ID}
+ provider: custom
+ base_url: {server.base_url}
+ api_key: fake
+ terminal:
+ cwd: {workspace.as_posix()}
+ memory:
+ memory_enabled: false
+ user_profile_enabled: false
+ skills:
+ creation_nudge_interval: 0
+ tools:
+ tool_search: false
+ """
+ ),
+ encoding="utf-8",
+ )
+ (home / "SOUL.md").write_text("You are Probe, a Jarvis agent.\n", encoding="utf-8")
+ return home
+
+
+async def probe_hermes() -> None:
+ binary = shutil.which("hermes") or str(
+ Path(os.environ.get("LOCALAPPDATA", "")) / "hermes" / "bin" / "hermes.exe"
+ )
+ base = Path(tempfile.mkdtemp(prefix="jarvis-acp-probe-"))
+ workspace = base / "workspace"
+ workspace.mkdir()
+ mcp_script = base / "mcp_stub.py"
+ mcp_script.write_text(MCP_SCRIPT, encoding="utf-8")
+ with FakeOpenAIServer() as server:
+ home = hermes_home(base, server, workspace)
+ env = dict(os.environ)
+ env.update(
+ {
+ "HERMES_HOME": str(home),
+ "HERMES_ACP_SKIP_CONFIGURED_MCP": "1",
+ "PYTHONIOENCODING": "utf-8",
+ }
+ )
+ mcp = McpServer(name="jarvis", command=sys.executable, args=[str(mcp_script)])
+ print("== turn 1: new session + MCP tool call")
+ t1, io1, rc1 = await run_turn(
+ [binary, "acp"],
+ env,
+ workspace,
+ AcpTurn(
+ turn_id="t1",
+ cwd=str(workspace),
+ prompt_text='CALL_TOOL society_memory_recall {"query": "hello"}',
+ mcp_servers=[mcp],
+ auto_allow=True,
+ ),
+ )
+ print("== turn 2: session/load in a new process")
+ t2, io2, rc2 = await run_turn(
+ [binary, "acp"],
+ env,
+ workspace,
+ AcpTurn(
+ turn_id="t2",
+ cwd=str(workspace),
+ prompt_text="second message",
+ resume=t1.vendor_session,
+ mcp_servers=[mcp],
+ auto_allow=True,
+ ),
+ )
+ print("== turn 3: unknown session id")
+ t3, _io3, _rc3 = await run_turn(
+ [binary, "acp"],
+ env,
+ workspace,
+ AcpTurn(turn_id="t3", cwd=str(workspace), prompt_text="x", resume="nope-123"),
+ )
+ print("\n== SUMMARY (hermes)")
+ print("agent:", t1.agent_name, t1.agent_version, "load:", t1.can_load)
+ print("t1 session:", t1.vendor_session, "status:", t1.status, t1.error, "rc:", rc1)
+ print("t1 tools:", [e["payload"]["name"] for e in io1.events if e["kind"] == "tool_call"])
+ print("t1 text:", t1.result_text[:120])
+ print("t2 session:", t2.vendor_session, "status:", t2.status, t2.error, "rc:", rc2)
+ print("t2 text:", t2.result_text[:120])
+ print("t2 model saw history msgs:", len(server.requests[-1].get("messages", [])))
+ print("t3 status:", t3.status, t3.error)
+ print("fake model requests:", len(server.requests))
+
+
+def _free_port() -> int:
+ import socket
+
+ with socket.socket() as sock:
+ sock.bind(("127.0.0.1", 0))
+ return int(sock.getsockname()[1])
+
+
+async def probe_openclaw() -> None:
+ """Gateway-backed ``openclaw acp`` on an isolated state dir and port.
+
+ ``OPENCLAW_ENTRY`` = path to ``openclaw.mjs`` (a fresh npm install);
+ ``OPENCLAW_NODE`` = the node binary that satisfies its engine range.
+ """
+ entry = os.environ["OPENCLAW_ENTRY"]
+ node = os.environ.get("OPENCLAW_NODE", "node")
+ base = Path(tempfile.mkdtemp(prefix="jarvis-openclaw-probe-"))
+ state = base / "state"
+ workspace = base / "workspace"
+ state.mkdir()
+ workspace.mkdir()
+ mcp_script = base / "mcp_stub.py"
+ mcp_script.write_text(MCP_SCRIPT, encoding="utf-8")
+ port = _free_port()
+ token = "probe-" + os.urandom(6).hex()
+ with FakeOpenAIServer() as server:
+ config = {
+ "gateway": {
+ "mode": "local",
+ "port": port,
+ "bind": "loopback",
+ "auth": {"mode": "token", "token": token},
+ },
+ "models": {
+ "mode": "replace",
+ "providers": {
+ "fake": {
+ "baseUrl": server.base_url,
+ "apiKey": "fake",
+ "api": "openai-completions",
+ "models": [
+ {
+ "id": MODEL_ID,
+ "name": "Fake",
+ "input": ["text"],
+ "contextWindow": 128000,
+ "maxTokens": 4096,
+ }
+ ],
+ }
+ },
+ },
+ "agents": {
+ "defaults": {
+ "model": {"primary": f"fake/{MODEL_ID}"},
+ "heartbeat": {"every": "0m"},
+ "workspace": str(workspace),
+ },
+ },
+ "tools": {"toolSearch": False},
+ "mcp": {
+ "servers": {
+ "jarvis": {
+ "command": sys.executable,
+ "args": [str(mcp_script)],
+ "env": {"PROBE_SESSION": "${JARVIS_CHAT_SESSION}"},
+ }
+ }
+ },
+ "session": {"reset": {"mode": "none"}},
+ }
+ config_path = state / "openclaw.json"
+ config_path.write_text(json.dumps(config, indent=2), encoding="utf-8")
+ env = dict(os.environ)
+ env.update(
+ {
+ "OPENCLAW_STATE_DIR": str(state),
+ "OPENCLAW_CONFIG_PATH": str(config_path),
+ "JARVIS_CHAT_SESSION": "society:probe",
+ "OPENCLAW_DISABLE_BONJOUR": "1",
+ "OPENCLAW_NO_RESPAWN": "1",
+ "OPENCLAW_SKIP_CHANNELS": "1",
+ "OPENCLAW_EXEC_SHELL_SNAPSHOT": "0",
+ }
+ )
+ gw_log = base / "gateway.log"
+ with gw_log.open("wb") as log_file:
+ gateway = await asyncio.create_subprocess_exec(
+ node,
+ entry,
+ "gateway",
+ "run",
+ "--port",
+ str(port),
+ "--allow-unconfigured",
+ cwd=str(workspace),
+ env=env,
+ stdout=log_file,
+ stderr=log_file,
+ )
+ try:
+ started = asyncio.get_running_loop().time()
+ ready = False
+ for _ in range(120):
+ await asyncio.sleep(1)
+ text = gw_log.read_text(encoding="utf-8", errors="replace")
+ if "listening" in text.lower():
+ ready = True
+ break
+ if gateway.returncode is not None:
+ break
+ elapsed = asyncio.get_running_loop().time() - started
+ print("gateway ready:", ready, "rc:", gateway.returncode, f"after {elapsed:.0f}s")
+ print("gateway log tail:\n " + "\n ".join(text.splitlines()[-15:]))
+ if not ready:
+ return
+ argv = [
+ node,
+ entry,
+ "acp",
+ "--url",
+ f"ws://127.0.0.1:{port}",
+ "--token",
+ token,
+ "--session",
+ "agent:main:main",
+ ]
+ print("== turn 1")
+ t1, io1, rc1 = await run_turn(
+ argv,
+ env,
+ workspace,
+ AcpTurn(
+ turn_id="t1",
+ cwd=str(workspace),
+ prompt_text='CALL_TOOL society_memory_recall {"query": "hi"}',
+ auto_allow=True,
+ ),
+ )
+ print("== turn 2 (same session key, new bridge process)")
+ t2, io2, rc2 = await run_turn(
+ argv,
+ env,
+ workspace,
+ AcpTurn(
+ turn_id="t2", cwd=str(workspace), prompt_text="second", auto_allow=True
+ ),
+ )
+ print("\n== SUMMARY (openclaw)")
+ print("agent:", t1.agent_name, t1.agent_version, "load:", t1.can_load)
+ print("t1 session:", t1.vendor_session, t1.status, t1.error, "rc:", rc1)
+ tools = [e["payload"]["name"] for e in io1.events if e["kind"] == "tool_call"]
+ print("t1 tools:", tools)
+ print("t1 text:", t1.result_text[:160])
+ print("t2 session:", t2.vendor_session, t2.status, t2.error, "rc:", rc2)
+ print("t2 text:", t2.result_text[:160])
+ if server.requests:
+ print("t2 history msgs:", len(server.requests[-1].get("messages", [])))
+ offered = server.requests[0].get("tools") or []
+ names = [(t.get("function") or {}).get("name") for t in offered]
+ print("tools offered:", names)
+ print("fake model requests:", len(server.requests))
+ finally:
+ gateway.terminate()
+ try:
+ await asyncio.wait_for(gateway.wait(), timeout=15)
+ except TimeoutError:
+ gateway.kill()
+
+
+if __name__ == "__main__":
+ target = sys.argv[1] if len(sys.argv) > 1 else "hermes"
+ asyncio.run(probe_hermes() if target == "hermes" else probe_openclaw())
diff --git a/tests/fakes/fake_openai_server.py b/tests/fakes/fake_openai_server.py
new file mode 100644
index 0000000000..5adf28b381
--- /dev/null
+++ b/tests/fakes/fake_openai_server.py
@@ -0,0 +1,197 @@
+"""Scripted OpenAI-compatible chat-completions server for runtime tests.
+
+External agent runtimes (Hermes, OpenClaw) accept any OpenAI-compatible
+base URL, so this stdlib-only server lets tests and the upstream canary
+drive a real runtime turn without a paid key.
+
+Behaviour, decided from the latest user message:
+
+* ``CALL_TOOL <name> <json-args>`` -> answers with one tool call to ``<name>``
+ when the request offers a tool whose name ends with ``<name>``.
+* after a ``tool`` role message -> answers ``tool done: <first 80 chars>``.
+* anything else -> answers ``pong: <message>``.
+
+Both streaming (SSE) and non-streaming responses are supported. Every
+request body is recorded on ``server.requests`` for assertions.
+"""
+
+from __future__ import annotations
+
+import json
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from typing import Any
+
+MODEL_ID = "fake-model"
+
+
+def _text_of(content: Any) -> str:
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ return " ".join(
+ str(part.get("text", "")) for part in content if isinstance(part, dict)
+ )
+ return ""
+
+
+def _decide(body: dict[str, Any]) -> dict[str, Any]:
+ """Return ``{"text": str}`` or ``{"tool": name, "args": str}``."""
+ messages = body.get("messages") or []
+ if messages and messages[-1].get("role") == "tool":
+ return {"text": "tool done: " + _text_of(messages[-1].get("content"))[:80]}
+ # The person's turn may arrive as several user messages (a runtime can
+ # append its own context block after the typed text): read them all.
+ pending: list[str] = []
+ for message in reversed(messages):
+ if message.get("role") != "user":
+ break
+ pending.insert(0, _text_of(message.get("content")).strip())
+ last_user = "\n".join(pending)
+ marker = last_user.rfind("CALL_TOOL ")
+ if marker >= 0:
+ rest = last_user[marker + len("CALL_TOOL ") :].strip().splitlines()[0]
+ name, _, args = rest.partition(" ")
+ offered = [
+ str((tool.get("function") or {}).get("name", ""))
+ for tool in body.get("tools") or []
+ ]
+ match = next((tool for tool in offered if tool.endswith(name)), "")
+ if match:
+ return {"tool": match, "args": args.strip() or "{}"}
+ return {"text": f"no tool named {name} offered"}
+ return {"text": "pong: " + last_user[-200:]}
+
+
+class _Handler(BaseHTTPRequestHandler):
+ server: FakeOpenAIServer
+
+ def log_message(self, format: str, *args: Any) -> None: # noqa: A002
+ return # keep test output quiet; requests are recorded instead
+
+ def _json(self, status: int, payload: dict[str, Any]) -> None:
+ data = json.dumps(payload).encode("utf-8")
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ def do_GET(self) -> None: # noqa: N802
+ if self.path.rstrip("/").endswith("/models"):
+ self._json(200, {"object": "list", "data": [{"id": MODEL_ID, "object": "model"}]})
+ return
+ self._json(404, {"error": {"message": "not found"}})
+
+ def do_POST(self) -> None: # noqa: N802
+ length = int(self.headers.get("Content-Length") or 0)
+ try:
+ body = json.loads(self.rfile.read(length) or b"{}")
+ except json.JSONDecodeError:
+ self._json(400, {"error": {"message": "bad json"}})
+ return
+ if not self.path.rstrip("/").endswith("/chat/completions"):
+ self._json(404, {"error": {"message": f"unsupported path {self.path}"}})
+ return
+ self.server.requests.append(body)
+ decision = _decide(body)
+ if body.get("stream"):
+ self._stream(decision)
+ else:
+ self._json(200, _completion(decision))
+
+ def _stream(self, decision: dict[str, Any]) -> None:
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream")
+ self.send_header("Cache-Control", "no-cache")
+ self.end_headers()
+ created = int(time.time())
+ if "tool" in decision:
+ delta = {
+ "role": "assistant",
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_fake_1",
+ "type": "function",
+ "function": {"name": decision["tool"], "arguments": decision["args"]},
+ }
+ ],
+ }
+ finish = "tool_calls"
+ else:
+ delta = {"role": "assistant", "content": decision["text"]}
+ finish = "stop"
+ chunks = [
+ {"choices": [{"index": 0, "delta": delta, "finish_reason": None}]},
+ {"choices": [{"index": 0, "delta": {}, "finish_reason": finish}]},
+ {
+ "choices": [],
+ "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
+ },
+ ]
+ for chunk in chunks:
+ chunk.update(
+ {
+ "id": "chatcmpl-fake",
+ "object": "chat.completion.chunk",
+ "created": created,
+ "model": MODEL_ID,
+ }
+ )
+ self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode())
+ self.wfile.write(b"data: [DONE]\n\n")
+ self.wfile.flush()
+
+
+def _completion(decision: dict[str, Any]) -> dict[str, Any]:
+ if "tool" in decision:
+ message: dict[str, Any] = {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_fake_1",
+ "type": "function",
+ "function": {"name": decision["tool"], "arguments": decision["args"]},
+ }
+ ],
+ }
+ finish = "tool_calls"
+ else:
+ message = {"role": "assistant", "content": decision["text"]}
+ finish = "stop"
+ return {
+ "id": "chatcmpl-fake",
+ "object": "chat.completion",
+ "created": int(time.time()),
+ "model": MODEL_ID,
+ "choices": [{"index": 0, "message": message, "finish_reason": finish}],
+ "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
+ }
+
+
+class FakeOpenAIServer(ThreadingHTTPServer):
+ """Run with ``with FakeOpenAIServer() as server: server.base_url``."""
+
+ daemon_threads = True
+
+ def __init__(self, host: str = "127.0.0.1", port: int = 0) -> None:
+ super().__init__((host, port), _Handler)
+ self.requests: list[dict[str, Any]] = []
+ self._thread: threading.Thread | None = None
+
+ @property
+ def base_url(self) -> str:
+ host, port = self.server_address[:2]
+ return f"http://{host}:{port}/v1"
+
+ def __enter__(self) -> FakeOpenAIServer:
+ self._thread = threading.Thread(target=self.serve_forever, daemon=True)
+ self._thread.start()
+ return self
+
+ def __exit__(self, *exc: object) -> None:
+ self.shutdown()
+ self.server_close()