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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agent-runtimes): run society agents on Hermes and OpenClaw
rubenluetke10-beepe8e4107095b2
diff --git a/docs/agent-runtimes.md b/docs/agent-runtimes.mdindex c903402b20..58cacb8940 100644--- a/docs/agent-runtimes.md+++ b/docs/agent-runtimes.md@@ -47,6 +47,12 @@ replayed during `session/load` is swallowed because the chat already shows it.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" andretries fresh with the transcript in front.+- **Session restore and the key:** Hermes rebuilds a reopened session from the+ stored `custom` provider and base URL, without the named provider's+ `key_env`. Jarvis therefore also writes `model.base_url` and passes the key+ under the name that path reads (`OPENAI_API_KEY`, `OPENROUTER_API_KEY`, or+ `<VENDOR>_API_KEY` derived from the host), in that one process' environment+ only. A keyless local server gets Hermes' `no-key-required` placeholder.- **Tool search:** Hermes defers MCP schemas behind its own `tool_search` bydefault. Jarvis keeps that native behaviour; tests switch it off(`tools.tool_search: false`) so a scripted model sees the tools.@@ -93,3 +99,28 @@ OpenAI-compatible model), so no paid key is involved. Verified 2026-10-06 withHermes 0.20.6 and OpenClaw 2026.9.8 on Windows: new session, an MCP tool callwith the right session header, resume in a new process, unknown-sessionhandling.++`scripts/spikes/agent_runtimes_e2e.py hermes|openclaw` runs the same fake+model through Jarvis' own drivers (profile and config writing, process+environment, the OpenClaw Gateway supervisor): two turns in one conversation,+no key written into the runtime's folder, no process left behind.++## Code map++| Piece | Where |+|---|---|+| ACP turn client (transport-free) | `jarvis/agent_runtimes/acp.py` |+| Shared types, child environment, persona text | `jarvis/agent_runtimes/base.py` |+| Jarvis provider → runtime endpoint and key | `jarvis/agent_runtimes/model_map.py` |+| Hermes driver | `jarvis/agent_runtimes/hermes.py` |+| OpenClaw driver and Gateway supervisor | `jarvis/agent_runtimes/openclaw.py` |+| Turn planning for the chat | `jarvis/agent_chat/runner_acp.py` |+| Process, pump, rollover, approvals (shared with every CLI seat) | `jarvis/agent_chat/runner_cli.py` |+| The agent's `runtime` field | `jarvis/society/roster.py`, `society_schema.sql` |++## Routines++A routine run keeps its owner's runtime when the run's model can drive it+(a pinned subscription seat runs on Jarvis' own runtime instead). On OpenClaw+each run gets its own Gateway session key, so a run never resets the agent's+main conversation.diff --git a/jarvis/agent_chat/runner_acp.py b/jarvis/agent_chat/runner_acp.pynew file mode 100644index 0000000000..bc659560c1--- /dev/null+++ b/jarvis/agent_chat/runner_acp.py@@ -0,0 +1,137 @@+"""Plan a society turn on an external agent runtime (Hermes, OpenClaw).++The CLI runner (``runner_cli``) owns the process for every CLI seat — spawn,+containment, cancellation, rollover, resume-lost retries, approvals — and+these runtimes are just one more seat to it. This module answers the part+that differs: which agent the chat belongs to, which model route and Jarvis+tools that agent gets, and which process to start (from the runtime's+driver in ``jarvis.agent_runtimes``). The turn itself is driven over ACP by+``jarvis.agent_runtimes.acp.AcpTurn``, handed to the runner on the plan.+"""++from __future__ import annotations++import asyncio+import logging+from pathlib import Path+from typing import Any++from jarvis.agent_runtimes import RUNNER_RUNTIMES, driver+from jarvis.agent_runtimes.acp import AcpTurn+from jarvis.agent_runtimes.base import RuntimeTurn, RuntimeUnavailable+from jarvis.agent_runtimes.model_map import RouteUnavailable, route_for++log = logging.getLogger(__name__)++#: Society capability ids whose explicit denial switches the runtime's own+#: matching tools off as well.+_NATIVE_GROUPS: dict[str, str] = {"core:shell": "shell", "core:browser": "web"}+++def supports_runner(runner: str) -> bool:+ return runner in RUNNER_RUNTIMES+++def _agent_id(session_id: str) -> str:+ parts = session_id.split(":", 2)+ return parts[1] if len(parts) > 1 and parts[0] == "society" else ""+++async def _agent(agent_id: str) -> Any:+ from jarvis.society.runtime import current_runtime++ runtime = current_runtime()+ if runtime is None or not agent_id:+ return None+ return await runtime.roster.get(agent_id)+++def _config() -> Any:+ from jarvis.society.runtime import current_runtime++ runtime = current_runtime()+ cfg = runtime.config() if runtime is not None else None+ if cfg is not None:+ return cfg+ from jarvis.core.config import load_config++ return load_config()+++def _denied_native(agent: Any, plan_mode: bool) -> frozenset[str]:+ denied = {group for cap, group in _NATIVE_GROUPS.items() if cap in (agent.denies or [])}+ if plan_mode:+ denied.add("shell")+ return frozenset(denied)+++async def plan_runtime_turn(+ handle: Any,+ runner: str,+ *,+ prompt: str,+ cwd: Path,+ resume: str | None,+ identity: Any | None,+) -> Any:+ """The ``CliPlan`` for one turn on ``runner``; raises ``CliUnavailable``."""+ from jarvis import __version__+ from jarvis.agent_chat import jarvis_harness+ from jarvis.agent_chat.runner_cli import (+ _PLAN_PREAMBLE,+ CliPlan,+ CliUnavailable,+ _with_identity,+ )++ session = handle.session+ runtime_name = RUNNER_RUNTIMES[runner]+ agent_id = _agent_id(session.session_id)+ agent = await _agent(agent_id)+ if agent is None:+ raise CliUnavailable(f"{runtime_name.title()} runs society agents only.")+ try:+ route = await asyncio.to_thread(route_for, _config(), session.provider, session.model)+ except RouteUnavailable as exc:+ raise CliUnavailable(str(exc)) from exc+ plan_mode = session.permission_mode in ("plan", "read-only")+ tools = not getattr(handle, "tools_disabled", False)+ turn = RuntimeTurn(+ agent_id=agent.agent_id,+ agent_name=agent.name,+ session_id=session.session_id,+ workspace=cwd,+ route=route,+ resume=resume,+ auto_approve=session.permission_mode == "bypass",+ mcp_url=jarvis_harness.endpoint() if tools else None,+ control_key=jarvis_harness.control_key() if tools else None,+ denied_native=_denied_native(agent, plan_mode),+ )+ runtime = driver(runtime_name)+ try:+ launch = await runtime.launch(turn)+ except RuntimeUnavailable as exc:+ raise CliUnavailable(str(exc)) from exc+ text = _PLAN_PREAMBLE + prompt if plan_mode else prompt+ acp = AcpTurn(+ turn_id=handle.turn_id,+ cwd=str(launch.cwd),+ prompt_text=_with_identity(text, identity, resume),+ resume=launch.acp_resume,+ mcp_servers=launch.mcp_servers,+ auto_allow=turn.auto_approve,+ client_version=__version__,+ report_session=launch.vendor_session,+ )+ finished = getattr(runtime, "turn_finished", None)+ return CliPlan(+ argv=launch.argv,+ env=launch.env,+ stdin_text=None,+ shape="acp",+ vendor_session=None,+ keep_stdin=True,+ acp=acp,+ after_turn=(lambda: finished(agent.agent_id)) if callable(finished) else None,+ )diff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.pyindex b5868e6909..061c961560 100644--- a/jarvis/agent_chat/runner_cli.py+++ b/jarvis/agent_chat/runner_cli.py@@ -386,6 +386,12 @@ class CliPlan:#: is over with the working folder and the wall-clock start, and answers#: the id the CLI's own store gave the conversation (or None).discover: Callable[[Path, float], str | None] | None = None+ #: An Agent Client Protocol turn (Hermes, OpenClaw — ``runner_acp``): the+ #: pump hands every stdout object to it instead of a ``_SHAPES`` translator,+ #: and it writes its own requests on stdin.+ acp: Any | None = None+ #: Called once the process is gone (a runtime releasing its Gateway).+ after_turn: Callable[[], None] | None = Nonedef claude_control_init() -> str:@@ -1291,7 +1297,9 @@ _CLAUDE_CODE_RUNNERS: Final[frozenset[str]] = frozenset({"claude-cli", "glm-cli"def supports_cli_runner(runner: str) -> bool:- return runner in _PLANNERS+ from jarvis.agent_chat.runner_acp import supports_runner++ return runner in _PLANNERS or supports_runner(runner)# ------------------------------------------------------------ translation@@ -2890,7 +2898,8 @@ async def _run_cli_once(chat_ref = approval_ref(session.session_id)cwd = _resolved_cwd(session.cwd or Path.home())effort = normalize_effort(session.provider, session.effort)- planner = _PLANNERS[runner]+ # ``None`` = an external agent runtime, planned asynchronously (runner_acp).+ planner = _PLANNERS.get(runner)status = "done"error_text: str | None = Noneusage: dict[str, int] = {}@@ -2939,15 +2948,28 @@ async def _run_cli_once(# Resolve the installed CLI's effort ladder off the event loop so# newly available models keep the required model/effort pairing.await asyncio.to_thread(read_agy_models, required_model=session.model)- plan: CliPlan = planner(- prompt=planned_prompt,- cwd=cwd,- model=session.model,- effort=effort,- permission_mode=session.permission_mode,- resume=resume,- identity=identity,- )+ plan: CliPlan+ if planner is None:+ from jarvis.agent_chat.runner_acp import plan_runtime_turn++ plan = await plan_runtime_turn(+ handle,+ runner,+ prompt=planned_prompt,+ cwd=cwd,+ resume=resume,+ identity=identity,+ )+ else:+ plan = planner(+ prompt=planned_prompt,+ cwd=cwd,+ model=session.model,+ effort=effort,+ permission_mode=session.permission_mode,+ resume=resume,+ identity=identity,+ )if getattr(handle, "tools_disabled", False):from .native_control import disable_cli_tools@@ -2994,6 +3016,7 @@ async def _run_cli_once(if placement is None and (getattr(handle, "goal_turn", False)or (session.surface == "society" and session.permission_mode == "plan")+ or plan.acp is not None):from jarvis.core.process_tree import make_process_tree@@ -3032,7 +3055,7 @@ async def _run_cli_once(cwd=str(cwd),env=plan.env,stdin=asyncio.subprocess.PIPE- if plan.stdin_text is not None+ if plan.stdin_text is not None or plan.acp is not Noneelse asyncio.subprocess.DEVNULL,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,@@ -3047,8 +3070,12 @@ async def _run_cli_once(tree.close()return _Outcome("error", f"Could not start {runner}: {exc}", {}, None, None)- make_state, translate = _SHAPES[plan.shape]- state: Any = make_state(handle.turn_id, vendor_session)+ if plan.acp is not None:+ state: Any = plan.acp+ translate: Any = None+ else:+ make_state, translate = _SHAPES[plan.shape]+ state = make_state(handle.turn_id, vendor_session)# Lines that are not the CLI's JSON — a banner, a warning, the whole# answer of a plain-text CLI — shown as they come, and kept as the answer# of last resort when the stream said nothing else.@@ -3091,10 +3118,19 @@ async def _run_cli_once(try:obj = json.loads(line)except ValueError:- await _say_plain(line)+ if plan.acp is None:+ await _say_plain(line)+ else:+ log.debug("agent chat %s: non-ACP stdout line skipped", handle.turn_id)continueif not isinstance(obj, dict):continue+ if plan.acp is not None:+ await plan.acp.on_message(obj, acp_io)+ if plan.acp.saw_result:+ # The prompt answered; closing stdin lets the runtime exit.+ _close_stdin()+ continueif plan.control_init is not None:if obj.get("type") == "control_request":await _answer_control_request(obj)@@ -3192,6 +3228,9 @@ async def _run_cli_once(if plan.control_init is not None:proc.stdin.write(plan.control_init.encode("utf-8"))await proc.stdin.drain()+ if plan.acp is not None:+ proc.stdin.write(plan.acp.opening_frame().encode("utf-8"))+ await proc.stdin.drain()if plan.stdin_text is not None:proc.stdin.write(plan.stdin_text.encode("utf-8"))await proc.stdin.drain()@@ -3206,6 +3245,27 @@ async def _run_cli_once(await handle.cancel.wait()_kill(proc)+ class _AcpIO:+ """What an ACP turn needs from this process: stdin, the chat, the card."""++ async def write(self, frame: dict[str, Any]) -> None:+ from jarvis.agent_runtimes.acp import frame_line++ await _write_stdin(frame_line(frame))++ async def emit(self, event: dict[str, Any]) -> None:+ await handle.emit(event)++ async def ask(self, call_id: str, name: str, args: dict[str, Any], summary: str) -> str:+ decision = await handle.request_approval(call_id, name, args, summary)+ if decision in {"allow", "allow_always"} and bridge is not None:+ # A Jarvis tool the runtime just asked about reaches the+ # executor's own gate over MCP next; the person answered once.+ bridge.note_cli_approval(chat_ref, name)+ return str(decision)++ acp_io = _AcpIO()+pump = asyncio.create_task(_pump_stdout())drain = asyncio.create_task(_drain_stderr())feeder = asyncio.create_task(_feed_stdin())@@ -3237,6 +3297,8 @@ async def _run_cli_once(await asyncio.wait_for(proc.wait(), timeout=5)except TimeoutError:log.warning("Agent CLI did not reap after cancellation")+ if plan.after_turn is not None:+ plan.after_turn()if handle.cancel.is_set():status = "cancelled"diff --git a/jarvis/agent_runtimes/__init__.py b/jarvis/agent_runtimes/__init__.pyindex e69de29bb2..14f88b78c5 100644--- a/jarvis/agent_runtimes/__init__.py+++ b/jarvis/agent_runtimes/__init__.py@@ -0,0 +1,53 @@+"""External agent runtimes for society agents: Hermes and OpenClaw.++See ``docs/agent-runtimes.md``. Drivers are created lazily — importing this+package starts nothing and touches no binary (AP-26).+"""++from __future__ import annotations++from typing import Any, Final++#: Chat runner -> runtime name (``society.events.AgentRuntime`` values).+RUNNER_RUNTIMES: Final[dict[str, str]] = {+ "hermes-cli": "hermes",+ "openclaw-cli": "openclaw",+}++#: The runtimes an agent can be switched to, in display order.+RUNTIME_NAMES: Final[tuple[str, ...]] = ("hermes", "openclaw")++_DRIVERS: dict[str, Any] = {}+++def driver(name: str) -> Any:+ """The driver singleton for ``name`` (``hermes`` / ``openclaw``)."""+ found = _DRIVERS.get(name)+ if found is not None:+ return found+ if name == "hermes":+ from jarvis.agent_runtimes.hermes import HermesRuntime++ found = HermesRuntime()+ elif name == "openclaw":+ from jarvis.agent_runtimes.openclaw import OpenClawRuntime++ found = OpenClawRuntime()+ else:+ raise KeyError(f"unknown agent runtime {name!r}")+ _DRIVERS[name] = found+ return found+++def started_drivers() -> list[Any]:+ """Drivers that exist already (their background processes may be running)."""+ return list(_DRIVERS.values())+++async def stop_all() -> None:+ """Stop every runtime's background processes (app shutdown)."""+ for found in started_drivers():+ await found.stop()+++__all__ = ["RUNNER_RUNTIMES", "RUNTIME_NAMES", "driver", "started_drivers", "stop_all"]diff --git a/jarvis/agent_runtimes/acp.py b/jarvis/agent_runtimes/acp.pyindex b5a6a6482f..63bb0b8ba7 100644--- a/jarvis/agent_runtimes/acp.py+++ b/jarvis/agent_runtimes/acp.py@@ -145,6 +145,9 @@ class AcpTurn:auto_allow: bool = Falseclient_name: str = "personal-jarvis"client_version: str = ""+ #: What the chat stores as its vendor session instead of the ACP session+ #: id (OpenClaw addresses the conversation by a fixed session key).+ report_session: str | None = None# --- fields the CLI runner reads after the turn ---vendor_session: str | None = None@@ -163,6 +166,7 @@ class AcpTurn:agent_version: str = ""can_load: bool = False+ _acp_session: str = field(default="", init=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)@@ -258,16 +262,17 @@ class AcpTurn:self._fail(f"ACP session/new failed: {_error_text(error or {})}")returnres = 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._acp_session = str(res.get("sessionId") or self.resume or "")+ if not self._acp_session:self._fail("ACP session/new returned no session id")return+ self.vendor_session = self.report_session or self._acp_sessionawait io.write(_request(_PROMPT_ID,"session/prompt",{- "sessionId": self.vendor_session,+ "sessionId": self._acp_session,"prompt": [{"type": "text", "text": self.prompt_text}],},)@@ -314,6 +319,10 @@ class AcpTurn: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)+ if call_id not in self.emitted_tool_ids and not self.auto_allow:+ # The approval card sits on a tool row; give it one.+ await self._flush_text(io)+ await self._tool_start(call | {"toolCallId": call_id}, io)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]diff --git a/jarvis/agent_runtimes/base.py b/jarvis/agent_runtimes/base.pynew file mode 100644index 0000000000..e19489d807--- /dev/null+++ b/jarvis/agent_runtimes/base.py@@ -0,0 +1,314 @@+"""Shared pieces of the external agent runtimes (``docs/agent-runtimes.md``).++A runtime module (``hermes``, ``openclaw``) answers three questions:++* :meth:`AgentRuntimeDriver.detect` — is it installed, which version, is that+ version new enough? Read from ``--version`` only; never a model call.+* :meth:`AgentRuntimeDriver.launch` — the process to start for one chat turn+ and how to address the agent's conversation in it (a :class:`RuntimeLaunch`).+* :meth:`AgentRuntimeDriver.install_command` / ``update_command`` — the+ runtime's own official installer and updater, run only when the person asks.++Everything a runtime writes lives under ``user_data_dir()/agent_runtimes/``;+the person's own Hermes or OpenClaw setup is never read or changed.+"""++from __future__ import annotations++import json+import logging+import os+import re+import shutil+import subprocess+import sys+import time+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Final, Protocol++from jarvis.agent_runtimes.acp import McpServer+from jarvis.agent_runtimes.model_map import ModelRoute++log = logging.getLogger(__name__)++#: Inherited environment a runtime process may see. Everything else — above+#: all every other provider's key — stays out, so a runtime cannot fall back+#: to a credential the person did not pick for this agent.+_ENV_ALLOWLIST: Final[frozenset[str]] = frozenset(+ name.upper()+ for name in (+ "PATH",+ "PATHEXT",+ "SystemRoot",+ "SystemDrive",+ "WINDIR",+ "COMSPEC",+ "TEMP",+ "TMP",+ "TMPDIR",+ "USERPROFILE",+ "USER",+ "LOGNAME",+ "USERNAME",+ "HOMEDRIVE",+ "HOMEPATH",+ "HOME",+ "LOCALAPPDATA",+ "APPDATA",+ "ProgramData",+ "ProgramFiles",+ "ProgramFiles(x86)",+ "ProgramW6432",+ "NUMBER_OF_PROCESSORS",+ "PROCESSOR_ARCHITECTURE",+ "OS",+ "XDG_CONFIG_HOME",+ "XDG_DATA_HOME",+ "XDG_CACHE_HOME",+ "XDG_RUNTIME_DIR",+ "LANG",+ "LC_ALL",+ "LC_CTYPE",+ "TERM",+ "TZ",+ "SSL_CERT_FILE",+ "SSL_CERT_DIR",+ "REQUESTS_CA_BUNDLE",+ "NODE_EXTRA_CA_CERTS",+ "HTTP_PROXY",+ "HTTPS_PROXY",+ "NO_PROXY",+ "ALL_PROXY",+ )+)++_VERSION_RE: Final[re.Pattern[str]] = re.compile(r"(\d+)\.(\d+)\.(\d+)")++#: How long a ``detect()`` answer is reused. Installs and updates clear it.+_DETECT_TTL_S: Final[float] = 300.0+++class RuntimeUnavailable(Exception):+ """The runtime cannot run this turn; the message is shown in the chat."""+++@dataclass(frozen=True, slots=True)+class RuntimeStatus:+ """What ``GET /api/agent-runtimes`` reports for one runtime."""++ runtime: str+ label: str+ installed: bool+ version: str = ""+ minimum_version: str = ""+ #: Installed and new enough to run a turn.+ ready: bool = False+ #: Why it is not ready, in plain words ("" when ready).+ problem: str = ""+ #: The official install/update command, for display.+ install_hint: str = ""++ def to_dict(self) -> dict[str, Any]:+ return {+ "runtime": self.runtime,+ "label": self.label,+ "installed": self.installed,+ "version": self.version,+ "minimum_version": self.minimum_version,+ "ready": self.ready,+ "problem": self.problem,+ "install_hint": self.install_hint,+ }+++@dataclass(slots=True)+class RuntimeTurn:+ """What a runtime needs to start one turn of one agent."""++ agent_id: str+ agent_name: str+ #: The chat session id (``society:<agent_id>``), sent as the MCP header.+ session_id: str+ workspace: Path+ route: ModelRoute+ #: ``None`` on a fresh conversation (first turn, rollover, lost session).+ resume: str | None+ #: The chat's stance: ``bypass`` lets the runtime act without asking.+ auto_approve: bool+ #: The Jarvis MCP endpoint and the control key that opens it (``None``+ #: when the web server has not bound yet — the turn runs without tools).+ mcp_url: str | None = None+ control_key: str | None = None+ #: Native capability groups this agent may not use (``"shell"``, ``"web"``).+ denied_native: frozenset[str] = frozenset()+++@dataclass(slots=True)+class RuntimeLaunch:+ """The process for one turn and how the ACP client addresses the session."""++ argv: list[str]+ env: dict[str, str]+ cwd: Path+ #: Passed to ``session/new`` / ``session/load`` (runtimes that accept them).+ mcp_servers: list[McpServer] = field(default_factory=list)+ #: The id ``session/load`` reopens; ``None`` = open a new ACP session.+ acp_resume: str | None = None+ #: What the chat stores as its vendor session after the turn. ``None`` =+ #: whatever id the ACP session reported.+ vendor_session: str | None = None+++class AgentRuntimeDriver(Protocol):+ name: str+ label: str++ def detect(self, *, refresh: bool = False) -> RuntimeStatus: ...++ async def launch(self, turn: RuntimeTurn) -> RuntimeLaunch: ...++ def install_command(self) -> list[str] | None: ...++ def update_command(self) -> list[str] | None: ...++ async def stop(self, agent_id: str | None = None) -> None:+ """Stop background processes (all agents when ``agent_id`` is None)."""+ ...+++# ------------------------------------------------------------------ helpers+++def runtimes_root() -> Path:+ from jarvis.core.paths import user_data_dir++ return user_data_dir() / "agent_runtimes"+++def agent_home(runtime: str, agent_id: str) -> Path:+ """The runtime's own state folder for one agent (created on demand)."""+ safe = re.sub(r"[^A-Za-z0-9_.-]", "_", agent_id) or "agent"+ home = runtimes_root() / runtime / safe+ home.mkdir(parents=True, exist_ok=True)+ return home+++def child_env(extra: dict[str, str] | None = None) -> dict[str, str]:+ """A minimal environment for a runtime process, plus ``extra``."""+ env = {k: v for k, v in os.environ.items() if k.upper() in _ENV_ALLOWLIST}+ env["PYTHONIOENCODING"] = "utf-8"+ env["PYTHONUTF8"] = "1"+ if extra:+ env.update(extra)+ return env+++def write_if_changed(path: Path, text: str) -> bool:+ """Write UTF-8 text when it differs; True when the file changed."""+ try:+ if path.read_text(encoding="utf-8") == text:+ return False+ except OSError:+ pass+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp = path.with_suffix(path.suffix + ".tmp")+ tmp.write_text(text, encoding="utf-8")+ os.replace(tmp, path)+ return True+++def write_json_if_changed(path: Path, data: dict[str, Any]) -> bool:+ return write_if_changed(path, json.dumps(data, indent=2, ensure_ascii=False) + "\n")+++def parse_version(text: str) -> tuple[int, int, int] | None:+ match = _VERSION_RE.search(text or "")+ if not match:+ return None+ return int(match.group(1)), int(match.group(2)), int(match.group(3))+++def format_version(version: tuple[int, int, int]) -> str:+ return ".".join(str(part) for part in version)+++def run_version(argv: list[str], *, timeout_s: float = 30.0) -> str:+ """``<binary> --version`` output, or "" when it cannot run."""+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++ try:+ done = subprocess.run( # noqa: S603 — argv is a resolved runtime binary+ argv,+ capture_output=True,+ timeout=timeout_s,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ env=child_env(),+ check=False,+ )+ except (OSError, subprocess.TimeoutExpired) as exc:+ log.info("agent runtimes: %s failed: %s", argv[:2], exc)+ return ""+ out = (done.stdout or b"") + b"\n" + (done.stderr or b"")+ return out.decode("utf-8", errors="replace").strip()+++def first_existing(candidates: list[Path]) -> Path | None:+ for candidate in candidates:+ try:+ if candidate.is_file():+ return candidate+ except OSError:+ continue+ return None+++def which(*names: str) -> str | None:+ for name in names:+ found = shutil.which(name)+ if found:+ return found+ return None+++def is_windows() -> bool:+ return sys.platform == "win32"+++class DetectCache:+ """Remembers a ``detect()`` answer for a few minutes (it spawns a process)."""++ def __init__(self) -> None:+ self._value: RuntimeStatus | None = None+ self._at = 0.0++ def get(self) -> RuntimeStatus | None:+ if self._value is not None and time.monotonic() - self._at < _DETECT_TTL_S:+ return self._value+ return None++ def put(self, value: RuntimeStatus) -> RuntimeStatus:+ self._value = value+ self._at = time.monotonic()+ return value++ def clear(self) -> None:+ self._value = None+++def persona_text(agent_name: str) -> str:+ """The runtime's own persona file: defer to the Jarvis briefing.++ Both runtimes inject a persona file (Hermes ``SOUL.md``, OpenClaw's+ workspace files) into every system prompt. Left at their defaults the+ agent would introduce itself as Hermes or OpenClaw; this one line makes+ the Jarvis identity block in the conversation authoritative instead.+ """+ name = agent_name.strip() or "this agent"+ return (+ f"You are {name}, an agent in the person's Personal Jarvis app. Your identity, "+ "standing instructions, memory and skills arrive from Jarvis in "+ "<jarvis_identity> and <jarvis_turn_context> blocks; follow them over any "+ "default persona. Jarvis' own tools (memory notes, routines, teammates, "+ "approvals, the visible browser) are on the `jarvis` MCP server.\n"+ )diff --git a/jarvis/agent_runtimes/hermes.py b/jarvis/agent_runtimes/hermes.pynew file mode 100644index 0000000000..7ced97be8e--- /dev/null+++ b/jarvis/agent_runtimes/hermes.py@@ -0,0 +1,276 @@+"""Hermes Agent as a society agent runtime (``docs/agent-runtimes.md``).++One turn = one ``hermes acp`` process with ``HERMES_HOME`` pointed at the+agent's own profile folder. Jarvis writes that profile's ``config.yaml``+(JSON, which is valid YAML) and ``SOUL.md`` before every turn and hands the+Jarvis MCP server over per session; the profile keeps Hermes' own session+store, so ``session/load`` reopens the agent's one conversation.++Hermes' self-learning extras (memory nudges, background review, curator,+skill-creation nudges, title generation) are switched off: Jarvis owns+memory and skills for every runtime, and nothing the person did not start may+spend their key. A key Hermes does not know is ignored by Hermes, so a renamed+option degrades to Hermes' default instead of breaking the turn.+"""++from __future__ import annotations++import asyncio+import os+import re+from pathlib import Path+from typing import Any, Final+from urllib.parse import urlsplit++from jarvis.agent_runtimes.acp import McpServer+from jarvis.agent_runtimes.base import (+ DetectCache,+ RuntimeLaunch,+ RuntimeStatus,+ RuntimeTurn,+ RuntimeUnavailable,+ agent_home,+ child_env,+ first_existing,+ format_version,+ is_windows,+ parse_version,+ persona_text,+ run_version,+ which,+ write_if_changed,+ write_json_if_changed,+)+from jarvis.agent_runtimes.model_map import KEY_ENV_VAR, RUNTIME_PROVIDER_NAME++NAME: Final[str] = "hermes"+LABEL: Final[str] = "Hermes"++#: Oldest release verified to persist ACP sessions and accept per-session MCP+#: servers (spike 2026-10-06). Older installs are offered an update.+MINIMUM_VERSION: Final[tuple[int, int, int]] = (0, 20, 6)++_INSTALL_URL_PS1: Final[str] = "https://hermes-agent.nousresearch.com/install.ps1"+_INSTALL_URL_SH: Final[str] = "https://hermes-agent.nousresearch.com/install.sh"+++def _binary() -> str | None:+ found = which("hermes", "hermes.exe", "hermes.cmd")+ if found:+ return found+ home = Path.home()+ candidates = [home / ".local" / "bin" / "hermes", home / ".hermes" / "bin" / "hermes"]+ local = os.environ.get("LOCALAPPDATA")+ if local:+ candidates.insert(0, Path(local) / "hermes" / "bin" / "hermes.exe")+ found_path = first_existing(candidates)+ return str(found_path) if found_path else None+++def _install_hint() -> str:+ if is_windows():+ return f"iex (irm {_INSTALL_URL_PS1})"+ return f"curl -fsSL {_INSTALL_URL_SH} | bash"+++class HermesRuntime:+ name = NAME+ label = LABEL++ def __init__(self) -> None:+ self._detect = DetectCache()++ # ----------------------------------------------------------- detection++ def detect(self, *, refresh: bool = False) -> RuntimeStatus:+ if refresh:+ self._detect.clear()+ cached = self._detect.get()+ if cached is not None:+ return cached+ minimum = format_version(MINIMUM_VERSION)+ binary = _binary()+ if binary is None:+ return self._detect.put(+ RuntimeStatus(+ NAME,+ LABEL,+ installed=False,+ minimum_version=minimum,+ problem="Hermes is not installed.",+ install_hint=_install_hint(),+ )+ )+ version = parse_version(run_version([binary, "--version"]))+ if version is None:+ return self._detect.put(+ RuntimeStatus(+ NAME,+ LABEL,+ installed=True,+ minimum_version=minimum,+ problem="Hermes is installed but did not report its version.",+ install_hint=_install_hint(),+ )+ )+ ready = version >= MINIMUM_VERSION+ return self._detect.put(+ RuntimeStatus(+ NAME,+ LABEL,+ installed=True,+ version=format_version(version),+ minimum_version=minimum,+ ready=ready,+ problem="" if ready else f"Hermes {minimum} or newer is needed. Update it.",+ install_hint=_install_hint(),+ )+ )++ def install_command(self) -> list[str] | None:+ if is_windows():+ script = (+ f"& ([scriptblock]::Create((irm {_INSTALL_URL_PS1}))) -SkipSetup -NonInteractive"+ )+ return ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script]+ return [+ "bash",+ "-c",+ f"curl -fsSL {_INSTALL_URL_SH} | bash -s -- --skip-setup --non-interactive",+ ]++ def update_command(self) -> list[str] | None:+ binary = _binary()+ return [binary, "update", "--yes"] if binary else None++ async def stop(self, agent_id: str | None = None) -> None:+ """Hermes runs one process per turn; nothing stays behind between turns."""+ return++ # -------------------------------------------------------------- launch++ def config_for(self, turn: RuntimeTurn) -> dict[str, Any]:+ route = turn.route+ provider: dict[str, Any] = {+ "api": route.base_url,+ "transport": route.transport,+ "default_model": route.model,+ }+ model: dict[str, Any] = {+ "provider": f"custom:{RUNTIME_PROVIDER_NAME}",+ "default": route.model,+ # Session restore rebuilds the agent from the stored endpoint and+ # reads the key next to a matching ``model.base_url``.+ "base_url": route.base_url,+ }+ if route.api_key:+ provider["key_env"] = KEY_ENV_VAR+ else:+ # A keyless local server: Hermes' own placeholder, not a secret.+ model["api_key"] = "no-key-required"+ config: dict[str, Any] = {+ "model": model,+ "providers": {RUNTIME_PROVIDER_NAME: provider},+ "terminal": {"cwd": str(turn.workspace)},+ # Jarvis owns memory and skills on every runtime.+ "memory": {+ "memory_enabled": False,+ "user_profile_enabled": False,+ "nudge_interval": 0,+ },+ "skills": {"creation_nudge_interval": 0, "project_discovery": False},+ "curator": {"enabled": False},+ "auxiliary": {+ "background_review": {"enabled": False},+ "title_generation": {"enabled": False},+ },+ # "manual" asks over ACP (the chat's approval card); never the+ # "smart" guardian, which spends model calls of its own.+ "approvals": {"mode": "off" if turn.auto_approve else "manual"},+ }+ disabled = sorted(_disabled_toolsets(turn.denied_native))+ if disabled:+ config["agent"] = {"disabled_toolsets": disabled}+ return config++ async def launch(self, turn: RuntimeTurn) -> RuntimeLaunch:+ status = await asyncio.to_thread(self.detect)+ if not status.ready:+ raise RuntimeUnavailable(status.problem or "Hermes is not ready.")+ binary = _binary()+ if binary is None:+ raise RuntimeUnavailable("Hermes is not installed.")+ home = await asyncio.to_thread(agent_home, NAME, turn.agent_id)+ await asyncio.to_thread(self._write_profile, home, turn)+ env = child_env(+ {+ "HERMES_HOME": str(home),+ # Only the Jarvis server handed over per session; none from config.+ "HERMES_ACP_SKIP_CONFIGURED_MCP": "1",+ **turn.route.env(),+ **_restore_key_aliases(turn.route.base_url, turn.route.api_key),+ }+ )+ servers: list[McpServer] = []+ if turn.mcp_url and turn.control_key:+ from jarvis.agent_chat.jarvis_harness import HEADER_NAME++ servers.append(+ McpServer(+ name="jarvis",+ url=turn.mcp_url,+ headers={+ # Travels inside the ACP frame on stdin, never on argv.+ "Authorization": f"Bearer {turn.control_key}",+ HEADER_NAME: turn.session_id,+ },+ )+ )+ return RuntimeLaunch(+ argv=[binary, "acp"],+ env=env,+ cwd=turn.workspace,+ mcp_servers=servers,+ acp_resume=turn.resume,+ )++ def _write_profile(self, home: Path, turn: RuntimeTurn) -> None:+ write_json_if_changed(home / "config.yaml", self.config_for(turn))+ write_if_changed(home / "SOUL.md", persona_text(turn.agent_name))+++def _restore_key_aliases(base_url: str, api_key: str | None) -> dict[str, str]:+ """The key again under the name Hermes' session restore looks for.++ A reopened ACP session is rebuilt from the stored ``custom`` provider and+ base URL, without the named provider's ``key_env``; that path reads+ ``OPENAI_API_KEY`` / ``OPENROUTER_API_KEY`` for those hosts and+ ``<VENDOR>_API_KEY`` derived from any other host. The process environment+ holds only this agent's key, so the alias reaches nothing else. Without+ it Jarvis still recovers (a fresh session with the transcript in front),+ but Hermes' own context of the conversation would be lost.+ """+ if not api_key:+ return {}+ host = (urlsplit(base_url).hostname or "").lower()+ if not host or host[-1].isdigit() or "." not in host:+ return {}+ if host == "openai.com" or host.endswith(".openai.com"):+ return {"OPENAI_API_KEY": api_key}+ if host == "openrouter.ai" or host.endswith(".openrouter.ai"):+ return {"OPENROUTER_API_KEY": api_key}+ labels = [label for label in host.split(".") if label not in ("api", "www")]+ if len(labels) < 2:+ return {}+ vendor = re.sub(r"[^A-Za-z0-9]", "_", labels[-2]).upper()+ return {f"{vendor}_API_KEY": api_key}+++def _disabled_toolsets(denied: frozenset[str]) -> set[str]:+ """Hermes toolsets an agent's Jarvis grants rule out."""+ out: set[str] = set()+ if "shell" in denied:+ out.update({"terminal", "code_execution"})+ if "web" in denied:+ out.update({"web", "browser"})+ return outdiff --git a/jarvis/agent_runtimes/model_map.py b/jarvis/agent_runtimes/model_map.pynew file mode 100644index 0000000000..f0f279fa02--- /dev/null+++ b/jarvis/agent_runtimes/model_map.py@@ -0,0 +1,143 @@+"""Map a society agent's Jarvis provider + model onto an external runtime.++Hermes and OpenClaw both accept any OpenAI-compatible endpoint and any+Anthropic Messages endpoint as a named custom provider, with the key read+from an environment variable. That one shape is the most basic and longest+stable configuration either project has, so every supported Jarvis provider+is expressed through it: the endpoint comes from+``jarvis.core.config.resolve_provider_endpoint`` (overrides and the team+proxy included) and the key travels only in the runtime process' environment+as :data:`KEY_ENV_VAR` — never in a file (AP-12).++Subscription seats (Claude Code, Codex, …) are not offered: driving those+logins from another vendor's agent loop is not a path Jarvis can keep+working across updates, and Hermes would bill a Claude Max login as paid+extra usage. Vertex needs service-account auth neither runtime receives here.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Final, Literal++Transport = Literal["chat_completions", "anthropic_messages"]++#: The environment variable both runtimes read the model key from.+KEY_ENV_VAR: Final[str] = "JARVIS_RUNTIME_API_KEY"++#: The provider name Jarvis registers inside the runtime's config.+RUNTIME_PROVIDER_NAME: Final[str] = "jarvis"+++@dataclass(frozen=True, slots=True)+class _Endpoint:+ transport: Transport+ #: Vendor default base URL; ``None`` = the person must configure one.+ default_base_url: str | None+ keyless: bool = False+ #: Appended to a configured server root (local servers store the root).+ path_suffix: str = ""+++#: Jarvis provider id (``agent_chat.catalog`` / ``core.config``) -> endpoint.+_ENDPOINTS: Final[dict[str, _Endpoint]] = {+ "claude-api": _Endpoint("anthropic_messages", "https://api.anthropic.com"),+ "openai": _Endpoint("chat_completions", "https://api.openai.com/v1"),+ "grok": _Endpoint("chat_completions", "https://api.x.ai/v1"),+ "openrouter": _Endpoint("chat_completions", "https://openrouter.ai/api/v1"),+ "nvidia": _Endpoint("chat_completions", "https://integrate.api.nvidia.com/v1"),+ "gemini": _Endpoint(+ "chat_completions", "https://generativelanguage.googleapis.com/v1beta/openai"+ ),+ "ollama": _Endpoint("chat_completions", None, keyless=True, path_suffix="/v1"),+ "local-openai": _Endpoint("chat_completions", None, keyless=True, path_suffix="/v1"),+}+++class RouteUnavailable(Exception):+ """The agent's model cannot run on the runtime; the message is user-facing."""+++@dataclass(frozen=True, slots=True)+class ModelRoute:+ """Everything a runtime config needs to reach the agent's model."""++ provider: str+ model: str+ base_url: str+ transport: Transport+ #: ``None`` for a keyless local server.+ api_key: str | None++ def env(self) -> dict[str, str]:+ """The child environment that carries the key (empty when keyless)."""+ return {KEY_ENV_VAR: self.api_key} if self.api_key else {}+++def supported_providers() -> frozenset[str]:+ """Jarvis providers an external runtime can run on (no secrets read)."""+ return frozenset(_ENDPOINTS)+++def supports(provider: str) -> bool:+ return provider in _ENDPOINTS+++def _default_model(config: Any, provider: str) -> str:+ providers = getattr(getattr(config, "brain", None), "providers", None) or {}+ configured = str(getattr(providers.get(provider), "model", "") or "")+ if configured:+ return configured+ from jarvis.brain.manager import get_tier_default_model++ return get_tier_default_model("router", provider) or ""+++def _local_root(provider: str, configured: str | None) -> str | None:+ if provider == "ollama":+ from jarvis.plugins.brain.ollama import default_server_root, normalize_server_root++ return normalize_server_root(configured or default_server_root())+ if configured:+ from jarvis.plugins.brain.ollama import normalize_server_root++ return normalize_server_root(configured)+ return None+++def route_for(config: Any, provider: str, model: str) -> ModelRoute:+ """Resolve the endpoint, key and model. Blocking (keyring): call in a thread."""+ endpoint = _ENDPOINTS.get(provider)+ if endpoint is None:+ raise RouteUnavailable(+ f"The {provider or 'selected'} seat cannot drive Hermes or OpenClaw. "+ "Pick a model that runs on an API key or a local server."+ )+ from jarvis.core.config import resolve_provider_endpoint++ resolved = resolve_provider_endpoint(+ provider, vendor_default_base_url=endpoint.default_base_url+ )+ base_url = resolved.base_url+ if endpoint.path_suffix and not resolved.via_proxy:+ root = _local_root(provider, base_url)+ base_url = f"{root}{endpoint.path_suffix}" if root else None+ if not base_url:+ raise RouteUnavailable(+ f"{provider} has no server address yet. Add it on the provider's card first."+ )+ key = (resolved.credential or "").strip() or None+ if key is None and not endpoint.keyless:+ raise RouteUnavailable(+ f"No API key is saved for {provider}. Connect it in Settings → API keys."+ )+ chosen = model.strip() or _default_model(config, provider)+ if not chosen:+ raise RouteUnavailable(f"Choose a model for {provider} first.")+ return ModelRoute(+ provider=provider,+ model=chosen,+ base_url=base_url.rstrip("/"),+ transport=endpoint.transport,+ api_key=key,+ )diff --git a/jarvis/agent_runtimes/openclaw.py b/jarvis/agent_runtimes/openclaw.pynew file mode 100644index 0000000000..edb217e6b4--- /dev/null+++ b/jarvis/agent_runtimes/openclaw.py@@ -0,0 +1,560 @@+"""OpenClaw as a society agent runtime (``docs/agent-runtimes.md``).++OpenClaw's documented embedding path is a supervised Gateway child plus its+own clients; Jarvis follows it exactly. Each agent gets its own state folder+and its own loopback Gateway (started on the agent's first turn, stopped+after :data:`IDLE_STOP_S` without one), and every turn runs the+version-matched ``openclaw acp`` bridge against it. No Gateway WebSocket+client is written here: that wire protocol requires an exact version match,+the bridge that ships with the install always has it.++The config Jarvis writes uses only long-stable keys. The model key and the+Jarvis control key reach OpenClaw as ``${ENV}`` references the Gateway+substitutes from its own environment, so neither is written to disk. A config+the installed version rejects (Gateway exit code 78) gets one+``openclaw doctor --fix`` pass, as the embedding guide prescribes.+"""++from __future__ import annotations++import asyncio+import contextlib+import hashlib+import json+import logging+import os+import secrets+import socket+import time+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Final++from jarvis.agent_runtimes.base import (+ DetectCache,+ RuntimeLaunch,+ RuntimeStatus,+ RuntimeTurn,+ RuntimeUnavailable,+ agent_home,+ child_env,+ format_version,+ is_windows,+ parse_version,+ run_version,+ which,+ write_if_changed,+ write_json_if_changed,+)+from jarvis.agent_runtimes.model_map import KEY_ENV_VAR, RUNTIME_PROVIDER_NAME++log = logging.getLogger(__name__)++NAME: Final[str] = "openclaw"+LABEL: Final[str] = "OpenClaw"++#: Oldest release verified with the embedding preset, ``openclaw acp`` against+#: an isolated Gateway and config-level MCP with ``${ENV}`` substitution.+MINIMUM_VERSION: Final[tuple[int, int, int]] = (2026, 9, 8)++#: The one conversation of an agent inside its own state folder.+SESSION_KEY: Final[str] = "agent:main:main"++#: Stop an agent's Gateway after this long without a turn.+IDLE_STOP_S: Final[float] = 15 * 60++#: How long a Gateway may take to listen (about 16 s measured on Windows).+_START_TIMEOUT_S: Final[float] = 120.0++#: ``EX_CONFIG``: the Gateway refused its configuration.+_EXIT_CONFIG: Final[int] = 78++#: The embedding preset from OpenClaw's embedding guide.+_EMBED_ENV: Final[dict[str, str]] = {+ "OPENCLAW_DISABLE_BONJOUR": "1",+ "OPENCLAW_NO_RESPAWN": "1",+ "OPENCLAW_SKIP_CHANNELS": "1",+ "OPENCLAW_EXEC_SHELL_SNAPSHOT": "0",+}++#: Native tools that duplicate a Jarvis feature (routines, messaging, other+#: devices) and would bypass Jarvis' own approvals and budgets.+_ALWAYS_DENIED: Final[tuple[str, ...]] = (+ "automations",+ "message",+ "conversations_send",+ "conversations_turn",+ "gateway",+ "nodes",+)++_CONTROL_KEY_ENV: Final[str] = "JARVIS_CONTROL_API_KEY"++_INSTALL_URL_PS1: Final[str] = "https://openclaw.ai/install.ps1"+_INSTALL_URL_SH: Final[str] = "https://openclaw.ai/install.sh"+++def _launcher() -> list[str] | None:+ """How to start the installed OpenClaw CLI.++ On Windows the npm shim is a ``.cmd`` file; running ``node openclaw.mjs``+ directly keeps cmd.exe (and its argument quoting) out of the way. The+ package's own launcher still picks OpenClaw's private Node runtime when+ the system Node is too old.+ """+ shim = which("openclaw", "openclaw.cmd", "openclaw.exe")+ if not shim:+ return None+ path = Path(shim)+ if is_windows() and path.suffix.lower() in {".cmd", ".bat", ".ps1", ""}:+ node = which("node", "node.exe")+ # A global install keeps the package beside the shim; a project+ # install keeps the shim in node_modules/.bin.+ for entry in (+ path.parent / "node_modules" / "openclaw" / "openclaw.mjs",+ path.parent.parent / "openclaw" / "openclaw.mjs",+ ):+ if entry.is_file() and node:+ return [node, str(entry)]+ return [shim]+++def _node_supported(version: tuple[int, int, int] | None) -> bool:+ """OpenClaw's engine range: Node >=24.16 <25, or >=26.1."""+ if version is None:+ return False+ return (24, 16, 0) <= version < (25, 0, 0) or version >= (26, 1, 0)+++def _private_node_present() -> bool:+ base = os.environ.get("OPENCLAW_HOME")+ root = Path(base) if base else Path.home() / ".openclaw"+ return (root / "tools" / "cli-node").is_dir()+++def _install_hint() -> str:+ if is_windows():+ return f"& ([scriptblock]::Create((iwr -useb {_INSTALL_URL_PS1}))) -NoOnboard"+ return f"curl -fsSL {_INSTALL_URL_SH} | bash -s -- --no-onboard"+++def _free_port() -> int:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:+ sock.bind(("127.0.0.1", 0))+ return int(sock.getsockname()[1])+++async def _listening(port: int) -> bool:+ try:+ _reader, writer = await asyncio.wait_for(+ asyncio.open_connection("127.0.0.1", port), timeout=2+ )+ except (OSError, TimeoutError):+ return False+ writer.close()+ with contextlib.suppress(OSError):+ await writer.wait_closed()+ return True+++@dataclass(slots=True)+class _Gateway:+ agent_id: str+ home: Path+ port: int+ env_hash: str+ proc: asyncio.subprocess.Process+ tree: Any+ log_handle: Any+ last_used: float = field(default_factory=time.monotonic)+ in_use: int = 0++ def alive(self) -> bool:+ return self.proc.returncode is None+++class OpenClawRuntime:+ name = NAME+ label = LABEL++ def __init__(self) -> None:+ self._detect = DetectCache()+ self._gateways: dict[str, _Gateway] = {}+ self._locks: dict[str, asyncio.Lock] = {}+ self._reaper: asyncio.Task[None] | None = None++ # ----------------------------------------------------------- detection++ def detect(self, *, refresh: bool = False) -> RuntimeStatus:+ if refresh:+ self._detect.clear()+ cached = self._detect.get()+ if cached is not None:+ return cached+ minimum = format_version(MINIMUM_VERSION)+ launcher = _launcher()+ if launcher is None:+ return self._detect.put(+ RuntimeStatus(+ NAME,+ LABEL,+ installed=False,+ minimum_version=minimum,+ problem="OpenClaw is not installed.",+ install_hint=_install_hint(),+ )+ )+ version = parse_version(run_version([*launcher, "--version"]))+ problem = ""+ if version is None:+ problem = "OpenClaw is installed but did not report its version."+ elif version < MINIMUM_VERSION:+ problem = f"OpenClaw {minimum} or newer is needed. Update it."+ else:+ node = which("node", "node.exe")+ node_version = parse_version(run_version([node, "--version"])) if node else None+ if not _node_supported(node_version) and not _private_node_present():+ problem = (+ "OpenClaw needs Node.js 24.16+ or 26.1+. Run the OpenClaw "+ "installer once; it adds a suitable Node.js for OpenClaw only."+ )+ return self._detect.put(+ RuntimeStatus(+ NAME,+ LABEL,+ installed=True,+ version=format_version(version) if version else "",+ minimum_version=minimum,+ ready=not problem,+ problem=problem,+ install_hint=_install_hint(),+ )+ )++ def install_command(self) -> list[str] | None:+ if is_windows():+ script = (+ f"& ([scriptblock]::Create((iwr -useb {_INSTALL_URL_PS1}))) -NoOnboard"+ )+ return ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script]+ return ["bash", "-c", f"curl -fsSL {_INSTALL_URL_SH} | bash -s -- --no-onboard"]++ def update_command(self) -> list[str] | None:+ launcher = _launcher()+ # No restart: Jarvis supervises its own Gateways and the person's own+ # Gateway service is theirs to restart.+ return [*launcher, "update", "--yes", "--no-restart"] if launcher else None++ # -------------------------------------------------------------- config++ def config_for(self, turn: RuntimeTurn, *, port: int, token: str) -> dict[str, Any]:+ route = turn.route+ provider: dict[str, Any] = {+ "baseUrl": route.base_url,+ # A keyless local server still needs a non-empty value.+ "apiKey": f"${{{KEY_ENV_VAR}}}" if route.api_key else "local",+ "api": (+ "anthropic-messages"+ if route.transport == "anthropic_messages"+ else "openai-completions"+ ),+ "models": [+ {+ "id": route.model,+ "name": route.model,+ "input": ["text"],+ "contextWindow": 128_000,+ "maxTokens": 8_192,+ }+ ],+ }+ denied = list(_ALWAYS_DENIED)+ if "web" in turn.denied_native:+ denied += ["browser", "web_search", "web_fetch"]+ if "shell" in turn.denied_native:+ exec_mode = "deny"+ else:+ exec_mode = "full" if turn.auto_approve else "ask"+ config: dict[str, Any] = {+ "gateway": {+ "mode": "local",+ "port": port,+ "bind": "loopback",+ "auth": {"mode": "token", "token": token},+ },+ "models": {"mode": "replace", "providers": {RUNTIME_PROVIDER_NAME: provider}},+ "agents": {+ "defaults": {+ "model": {"primary": f"{RUNTIME_PROVIDER_NAME}/{route.model}"},+ "workspace": str(turn.workspace),+ # Nothing the person did not start may spend their key.+ "heartbeat": {"every": "0m"},+ # The identity comes from Jarvis; no persona files are+ # written into, or read from, the agent's workspace.+ "skipBootstrap": True,+ "contextInjection": "never",+ }+ },+ "session": {"reset": {"mode": "none"}},+ "tools": {"deny": denied, "exec": {"mode": exec_mode}},+ }+ if turn.mcp_url and turn.control_key:+ from jarvis.agent_chat.jarvis_harness import HEADER_NAME++ config["mcp"] = {+ "servers": {+ "jarvis": {+ "url": turn.mcp_url,+ "transport": "streamable-http",+ "headers": {+ "Authorization": f"Bearer ${{{_CONTROL_KEY_ENV}}}",+ # The agent's canonical chat: one config for every+ # session of this Gateway, so a routine run never+ # rewrites it under a running chat turn.+ HEADER_NAME: f"society:{turn.agent_id}",+ },+ }+ }+ }+ return config++ # -------------------------------------------------------------- launch++ async def launch(self, turn: RuntimeTurn) -> RuntimeLaunch:+ status = await asyncio.to_thread(self.detect)+ if not status.ready:+ raise RuntimeUnavailable(status.problem or "OpenClaw is not ready.")+ launcher = _launcher()+ if launcher is None:+ raise RuntimeUnavailable("OpenClaw is not installed.")+ home = await asyncio.to_thread(agent_home, NAME, turn.agent_id)+ token = await asyncio.to_thread(_gateway_token, home)+ gateway_env = child_env(+ {+ **_EMBED_ENV,+ **_state_env(home),+ **turn.route.env(),+ **({_CONTROL_KEY_ENV: turn.control_key} if turn.control_key else {}),+ }+ )+ port = await self._ensure_gateway(turn, home, token, launcher, gateway_env)+ argv = [+ *launcher,+ "acp",+ "--url",+ f"ws://127.0.0.1:{port}",+ "--token-file",+ str(home / "gateway.token"),+ "--session",+ session_key(turn.agent_id, turn.session_id),+ ]+ if turn.resume is None:+ # A fresh conversation (first turn, rollover): the Jarvis identity+ # and recent transcript lead the prompt, so the old one must go.+ argv.append("--reset-session")+ return RuntimeLaunch(+ argv=argv,+ env=child_env({**_EMBED_ENV, **_state_env(home)}),+ cwd=turn.workspace,+ acp_resume=None,+ vendor_session=session_key(turn.agent_id, turn.session_id),+ )++ def turn_finished(self, agent_id: str) -> None:+ gateway = self._gateways.get(agent_id)+ if gateway is not None:+ gateway.in_use = max(0, gateway.in_use - 1)+ gateway.last_used = time.monotonic()++ async def _ensure_gateway(+ self,+ turn: RuntimeTurn,+ home: Path,+ token: str,+ launcher: list[str],+ env: dict[str, str],+ ) -> int:+ lock = self._locks.setdefault(turn.agent_id, asyncio.Lock())+ async with lock:+ env_hash = hashlib.sha256(+ json.dumps(sorted(env.items())).encode("utf-8")+ ).hexdigest()+ current = self._gateways.get(turn.agent_id)+ if current is not None and (not current.alive() or current.env_hash != env_hash):+ # A new key or control key needs a new process environment.+ await self._stop_gateway(current)+ current = None+ port = current.port if current is not None else _free_port()+ config = self.config_for(turn, port=port, token=token)+ await asyncio.to_thread(write_json_if_changed, home / "openclaw.json", config)+ if current is None:+ current = await self._start_gateway(+ turn.agent_id, home, port, env_hash, launcher, env+ )+ self._gateways[turn.agent_id] = current+ current.in_use += 1+ current.last_used = time.monotonic()+ self._ensure_reaper()+ return current.port++ async def _start_gateway(+ self,+ agent_id: str,+ home: Path,+ port: int,+ env_hash: str,+ launcher: list[str],+ env: dict[str, str],+ *,+ repaired: bool = False,+ ) -> _Gateway:+ from jarvis.core.process_tree import make_process_tree+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++ log_path = home / "gateway.log"+ handle = log_path.open("ab")+ tree = make_process_tree(f"openclaw-gateway-{agent_id}")+ try:+ proc = await asyncio.create_subprocess_exec(+ *launcher,+ "gateway",+ "run",+ "--port",+ str(port),+ "--allow-unconfigured",+ cwd=str(home),+ env=env,+ stdin=asyncio.subprocess.DEVNULL,+ stdout=handle,+ stderr=handle,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ start_new_session=os.name != "nt",+ )+ except (OSError, ValueError) as exc:+ handle.close()+ tree.close()+ raise RuntimeUnavailable(f"OpenClaw could not start: {exc}") from exc+ tree.assign(proc.pid)+ gateway = _Gateway(agent_id, home, port, env_hash, proc, tree, handle)+ log.info("agent runtimes: OpenClaw gateway for %s starting on %s", agent_id, port)+ deadline = time.monotonic() + _START_TIMEOUT_S+ while time.monotonic() < deadline:+ if proc.returncode is not None:+ break+ if await _listening(port):+ return gateway+ await asyncio.sleep(0.5)+ returncode = proc.returncode+ await self._stop_gateway(gateway)+ if returncode == _EXIT_CONFIG and not repaired:+ log.warning("agent runtimes: OpenClaw rejected its config; running doctor --fix")+ await _run_doctor(launcher, env, home)+ return await self._start_gateway(+ agent_id, home, port, env_hash, launcher, env, repaired=True+ )+ tail = _log_tail(log_path)+ if returncode is None:+ raise RuntimeUnavailable("OpenClaw did not start within two minutes." + tail)+ raise RuntimeUnavailable(f"OpenClaw stopped while starting (exit {returncode})." + tail)++ async def _stop_gateway(self, gateway: _Gateway) -> None:+ self._gateways.pop(gateway.agent_id, None)+ if gateway.proc.returncode is None:+ with contextlib.suppress(ProcessLookupError, OSError):+ gateway.proc.terminate()+ try:+ await asyncio.wait_for(gateway.proc.wait(), timeout=10)+ except TimeoutError:+ log.info("agent runtimes: OpenClaw gateway %s ignored terminate", gateway.port)+ # Closing the container reaps whatever the Gateway started (MCP servers,+ # exec children), including a Gateway that ignored terminate.+ gateway.tree.close()+ with contextlib.suppress(OSError):+ gateway.log_handle.close()++ def _ensure_reaper(self) -> None:+ if self._reaper is None or self._reaper.done():+ self._reaper = asyncio.get_running_loop().create_task(self._reap_idle())++ async def _reap_idle(self) -> None:+ while self._gateways:+ await asyncio.sleep(60)+ now = time.monotonic()+ for gateway in list(self._gateways.values()):+ idle = now - gateway.last_used+ if not gateway.alive() or (gateway.in_use == 0 and idle > IDLE_STOP_S):+ log.info("agent runtimes: stopping idle OpenClaw gateway %s", gateway.agent_id)+ await self._stop_gateway(gateway)++ async def stop(self, agent_id: str | None = None) -> None:+ targets = [+ gateway+ for gateway in list(self._gateways.values())+ if agent_id is None or gateway.agent_id == agent_id+ ]+ for gateway in targets:+ await self._stop_gateway(gateway)+++def session_key(agent_id: str, chat_session_id: str) -> str:+ """The Gateway session for a chat: the agent's one conversation, or a+ separate one per routine run so a run never resets the main chat."""+ if chat_session_id == f"society:{agent_id}":+ return SESSION_KEY+ digest = hashlib.sha256(chat_session_id.encode("utf-8")).hexdigest()[:16]+ return f"agent:main:run-{digest}"+++def _state_env(home: Path) -> dict[str, str]:+ return {+ "OPENCLAW_STATE_DIR": str(home / "state"),+ "OPENCLAW_CONFIG_PATH": str(home / "openclaw.json"),+ }+++def _gateway_token(home: Path) -> str:+ """The agent's loopback Gateway token, minted once and kept in its folder."""+ path = home / "gateway.token"+ try:+ token = path.read_text(encoding="utf-8").strip()+ if token:+ return token+ except OSError:+ pass+ token = secrets.token_urlsafe(32)+ write_if_changed(path, token)+ with contextlib.suppress(OSError):+ path.chmod(0o600)+ (home / "state").mkdir(parents=True, exist_ok=True)+ return token+++async def _run_doctor(launcher: list[str], env: dict[str, str], home: Path) -> None:+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++ try:+ proc = await asyncio.create_subprocess_exec(+ *launcher,+ "doctor",+ "--fix",+ "--yes",+ "--non-interactive",+ cwd=str(home),+ env=env,+ stdin=asyncio.subprocess.DEVNULL,+ stdout=asyncio.subprocess.DEVNULL,+ stderr=asyncio.subprocess.DEVNULL,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ await asyncio.wait_for(proc.wait(), timeout=120)+ except (OSError, TimeoutError) as exc:+ log.warning("agent runtimes: openclaw doctor --fix failed: %s", exc)+++def _log_tail(path: Path, lines: int = 6) -> str:+ try:+ text = path.read_text(encoding="utf-8", errors="replace")+ except OSError:+ return ""+ tail = [line for line in text.splitlines() if line.strip()][-lines:]+ return ("\n" + "\n".join(tail)) if tail else ""diff --git a/jarvis/society/routine_runner.py b/jarvis/society/routine_runner.pyindex 05a23d3c96..676ab51de1 100644--- a/jarvis/society/routine_runner.py+++ b/jarvis/society/routine_runner.py@@ -126,6 +126,17 @@ async def _seat_for_run(runtime: Any, agent: Any, task_id: str) -> tuple[str, streturn provider, model, effort, account_id+def _run_runtime(agent: Any, provider: str) -> str:+ """The run keeps its owner's runtime when the run's model can drive it;+ a pinned subscription seat runs on Jarvis' own runtime instead."""+ runtime = str(getattr(agent, "runtime", "") or "jarvis")+ if runtime == "jarvis":+ return ""+ from jarvis.agent_runtimes.model_map import supports++ return runtime if supports(provider) else ""++async def run_owned_routine(runtime: Any,task_id: str,@@ -153,6 +164,7 @@ async def run_owned_routine(cwd=_workspace(cfg, agent),permission_mode="bypass",title=f"{agent.name} · Routine {task_id}",+ runtime=_run_runtime(agent, provider),)# Persist the link before starting work, including runs that fail or are cancelled.task_store, _ = runtime.task_services()diff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.pyindex 85ac30ba7c..1618af0d07 100644--- a/jarvis/society/runtime.py+++ b/jarvis/society/runtime.py@@ -457,6 +457,10 @@ class SocietyRuntime:cleanup.callback(unsubscribe)setattr(self, attribute, None)cleanup.push_async_callback(self.coding_supervision.close)+ # Hermes / OpenClaw agents: their Gateways must not outlive the app.+ from jarvis.agent_runtimes import stop_all as stop_agent_runtimes++ cleanup.push_async_callback(stop_agent_runtimes)tasks: set[asyncio.Task[Any]] = set(self._watchers)for task in (self._starting_task, self._context_start_task, self._delivery_task):diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.pyindex 02f8deff7f..894d826473 100644--- a/jarvis/ui/web/society_routes.py+++ b/jarvis/ui/web/society_routes.py@@ -86,6 +86,15 @@ def _validated_chat_runner(from jarvis.agent_chat.service import resolve_runnerchosen_runtime = str(runtime if runtime is not None else agent.runtime)+ if chosen_runtime not in ("", "jarvis"):+ from jarvis.agent_runtimes.model_map import supports++ if not supports(provider):+ raise HTTPException(+ 422,+ "Hermes and OpenClaw run on an API key or a local model. "+ "Pick one of those for this agent first.",+ )runner = resolve_runner(provider, surface="society", runtime=chosen_runtime)mode = approval_mode if approval_mode is not None else (str(agent.approval_mode) if agent.approval_mode is not None else ""@@ -322,6 +331,15 @@ async def create_agent(body: CreateAgentBody, request: Request) -> dict[str, Anyfields = inherit_creator_fields(fields, creator)requested_mode = str(fields.get("approval_mode") or "bypass")provider = str(fields.get("provider") or body.provider)+ if str(fields.get("runtime") or "jarvis") != "jarvis":+ from jarvis.agent_runtimes.model_map import supports++ if not supports(provider):+ raise HTTPException(+ 422,+ "Hermes and OpenClaw run on an API key or a local model. "+ "Pick one of those for this agent first.",+ )if provider:from jarvis.agent_chat.permissions import society_mode_supportedfrom jarvis.agent_chat.service import resolve_runnerdiff --git a/scripts/spikes/agent_runtimes_e2e.py b/scripts/spikes/agent_runtimes_e2e.pynew file mode 100644index 0000000000..59ef9ef1dd--- /dev/null+++ b/scripts/spikes/agent_runtimes_e2e.py@@ -0,0 +1,146 @@+"""Smoke: the real runtime drivers launch real Hermes / OpenClaw turns.++Unlike ``agent_runtimes_probe.py`` this goes through Jarvis' own drivers+(``jarvis.agent_runtimes.hermes`` / ``openclaw``): profile and config+writing, process environment, the OpenClaw Gateway supervisor, and the ACP+turn. The model is ``tests/fakes/fake_openai_server.py``; no paid key.+All runtime state lands in a temporary folder.++ python scripts/spikes/agent_runtimes_e2e.py hermes+ python scripts/spikes/agent_runtimes_e2e.py openclaw+"""++from __future__ import annotations++import asyncio+import json+import sys+import tempfile+import uuid+from pathlib import Path+from typing import Any++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT))++from jarvis.agent_runtimes import base, driver # noqa: E402+from jarvis.agent_runtimes.acp import AcpTurn, frame_line # noqa: E402+from jarvis.agent_runtimes.base import RuntimeTurn # noqa: E402+from jarvis.agent_runtimes.model_map import ModelRoute # noqa: E402+from tests.fakes.fake_openai_server import MODEL_ID, FakeOpenAIServer # noqa: E402+++_STDERR = Path(tempfile.gettempdir()) / "jarvis-runtime-e2e-stderr.log"+++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:+ 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)++ async def ask(self, call_id: str, name: str, args: dict[str, Any], summary: str) -> str:+ return "allow"+++async def _run(name: str, turn: RuntimeTurn, text: str) -> tuple[AcpTurn, _IO]:+ runtime = driver(name)+ launch = await runtime.launch(turn)+ acp = AcpTurn(+ turn_id="e2e",+ cwd=str(launch.cwd),+ prompt_text=text,+ resume=launch.acp_resume,+ mcp_servers=launch.mcp_servers,+ auto_allow=True,+ report_session=launch.vendor_session,+ )+ proc = await asyncio.create_subprocess_exec(+ *launch.argv,+ cwd=str(launch.cwd),+ env=launch.env,+ stdin=asyncio.subprocess.PIPE,+ stdout=asyncio.subprocess.PIPE,+ stderr=_STDERR.open("ab"),+ limit=16 * 1024 * 1024,+ )+ io = _IO(proc)+ assert proc.stdin is not None and proc.stdout is not None+ proc.stdin.write(acp.opening_frame().encode("utf-8"))+ await proc.stdin.drain()++ async def pump() -> None:+ assert proc.stdout is not None and proc.stdin is not None+ while raw := await proc.stdout.readline():+ try:+ obj = json.loads(raw)+ except ValueError:+ continue+ if isinstance(obj, dict):+ await acp.on_message(obj, io)+ if acp.saw_result and not proc.stdin.is_closing():+ proc.stdin.close()++ await asyncio.wait_for(pump(), timeout=180)+ await asyncio.wait_for(proc.wait(), timeout=30)+ finished = getattr(runtime, "turn_finished", None)+ if callable(finished):+ finished(turn.agent_id)+ return acp, io+++async def main(name: str) -> int:+ tmp = Path(tempfile.mkdtemp(prefix=f"jarvis-{name}-e2e-"))+ base.runtimes_root = lambda: tmp / "agent_runtimes" # keep the real data dir clean+ workspace = tmp / "workspace"+ workspace.mkdir()+ status = driver(name).detect(refresh=True)+ print("detect:", status.to_dict())+ if not status.ready:+ return 2+ with FakeOpenAIServer() as server:+ key = "sk-e2e-" + uuid.uuid4().hex+ route = ModelRoute("local-openai", MODEL_ID, server.base_url, "chat_completions", None)+ turn = RuntimeTurn(+ agent_id="e2e-agent",+ agent_name="Probe",+ session_id="society:e2e-agent",+ workspace=workspace,+ route=route,+ resume=None,+ auto_approve=True,+ )+ first, io1 = await _run(name, turn, "first message")+ print("turn 1:", first.status, first.error, repr(first.result_text[:80]))+ print(" vendor session:", first.vendor_session)+ turn.resume = first.vendor_session+ second, io2 = await _run(name, turn, "second message")+ print("turn 2:", second.status, second.error, repr(second.result_text[:80]))+ history = len(server.requests[-1].get("messages", [])) if server.requests else 0+ print(" model saw", history, "messages on turn 2")+ home = tmp / "agent_runtimes" / name / "e2e-agent"+ written = sorted(p.name for p in home.iterdir())+ print(" runtime home:", written)+ secret_leak = [+ str(p.relative_to(home))+ for p in home.rglob("*")+ if p.is_file()+ and p.stat().st_size < 5_000_000+ and key in p.read_text(encoding="utf-8", errors="replace")+ ]+ print(" key written to disk:", secret_leak)+ await driver(name).stop()+ ok = first.status == "done" and second.status == "done" and history > 2 and not secret_leak+ print("RESULT:", "PASS" if ok else "FAIL")+ return 0 if ok else 1+++if __name__ == "__main__":+ sys.exit(asyncio.run(main(sys.argv[1] if len(sys.argv) > 1 else "hermes")))diff --git a/tests/fakes/fake_acp_agent.py b/tests/fakes/fake_acp_agent.pynew file mode 100644index 0000000000..5f0404c356--- /dev/null+++ b/tests/fakes/fake_acp_agent.py@@ -0,0 +1,192 @@+"""A scripted Agent Client Protocol agent on stdio, for runtime tests.++Run as ``python tests/fakes/fake_acp_agent.py``. It speaks just enough ACP+(``initialize``, ``session/new``, ``session/load``, ``session/prompt``) for+the CLI runner's ACP path, the way Hermes and OpenClaw do, without a model.++Environment:++* ``FAKE_ACP_STORE`` — JSON file holding known session ids and their prompt+ history, so ``session/load`` works across processes like a real runtime.+* ``FAKE_ACP_LOG`` — optional file every received frame is appended to.++What a prompt does depends on its text:++* contains ``TOOL`` — one ``tool_call`` named ``mcp_jarvis_society_memory_recall``+ then its completed ``tool_call_update``, then text;+* contains ``ASK`` — a ``session/request_permission`` first; the answer's+ option id is echoed in the reply;+* contains ``FAIL`` — the prompt request answers a JSON-RPC error;+* otherwise — ``echo: <text>`` streamed in two chunks plus a thought.++``session/load`` of an unknown id answers ``{}`` (Hermes' behaviour).+"""++from __future__ import annotations++import json+import os+import sys+import uuid+from pathlib import Path+from typing import Any+++def _store_path() -> Path | None:+ raw = os.environ.get("FAKE_ACP_STORE")+ return Path(raw) if raw else None+++def _load_store() -> dict[str, list[str]]:+ path = _store_path()+ if path is None or not path.is_file():+ return {}+ return json.loads(path.read_text(encoding="utf-8"))+++def _save_store(store: dict[str, list[str]]) -> None:+ path = _store_path()+ if path is not None:+ path.write_text(json.dumps(store), encoding="utf-8")+++def _send(frame: dict[str, Any]) -> None:+ sys.stdout.write(json.dumps(frame) + "\n")+ sys.stdout.flush()+++def _update(session_id: str, update: dict[str, Any]) -> None:+ _send(+ {+ "jsonrpc": "2.0",+ "method": "session/update",+ "params": {"sessionId": session_id, "update": update},+ }+ )+++def _text(session_id: str, text: str, kind: str = "agent_message_chunk") -> None:+ _update(session_id, {"sessionUpdate": kind, "content": {"type": "text", "text": text}})+++def _read() -> dict[str, Any] | None:+ line = sys.stdin.readline()+ if not line:+ return None+ log = os.environ.get("FAKE_ACP_LOG")+ if log:+ with open(log, "a", encoding="utf-8") as handle:+ handle.write(line)+ return json.loads(line)+++def _prompt(rid: Any, session_id: str, text: str, store: dict[str, list[str]]) -> None:+ store.setdefault(session_id, []).append(text)+ _save_store(store)+ if "FAIL" in text:+ _send({"jsonrpc": "2.0", "id": rid, "error": {"code": -32000, "message": "model down"}})+ return+ if "ASK" in text:+ _send(+ {+ "jsonrpc": "2.0",+ "id": "perm-1",+ "method": "session/request_permission",+ "params": {+ "sessionId": session_id,+ "toolCall": {"toolCallId": "tc-ask", "title": "terminal", "kind": "execute"},+ "options": [+ {"optionId": "yes", "name": "Allow", "kind": "allow_once"},+ {"optionId": "always", "name": "Always", "kind": "allow_always"},+ {"optionId": "no", "name": "Deny", "kind": "reject_once"},+ ],+ },+ }+ )+ answer = _read() or {}+ outcome = (answer.get("result") or {}).get("outcome") or {}+ _text(session_id, f"permission: {outcome.get('optionId') or outcome.get('outcome')}")+ elif "TOOL" in text:+ _update(+ session_id,+ {+ "sessionUpdate": "tool_call",+ "toolCallId": "tc-1",+ "title": "mcp_jarvis_society_memory_recall",+ "kind": "other",+ "status": "in_progress",+ "rawInput": {"query": "hi"},+ },+ )+ _update(+ session_id,+ {+ "sessionUpdate": "tool_call_update",+ "toolCallId": "tc-1",+ "status": "completed",+ "content": [{"type": "content", "content": {"type": "text", "text": "recalled"}}],+ },+ )+ _text(session_id, "used the tool")+ else:+ _text(session_id, "thinking", kind="agent_thought_chunk")+ _text(session_id, "echo: ")+ _text(session_id, text[-80:])+ _update(session_id, {"sessionUpdate": "usage_update", "used": 12, "size": 1000})+ _send(+ {+ "jsonrpc": "2.0",+ "id": rid,+ "result": {+ "stopReason": "end_turn",+ "usage": {"inputTokens": 11, "outputTokens": 7, "totalTokens": 18},+ },+ }+ )+++def main() -> int:+ store = _load_store()+ while True:+ frame = _read()+ if frame is None:+ return 0+ method = frame.get("method")+ rid = frame.get("id")+ params = frame.get("params") or {}+ if method == "initialize":+ _send(+ {+ "jsonrpc": "2.0",+ "id": rid,+ "result": {+ "protocolVersion": 1,+ "agentInfo": {"name": "fake-acp", "version": "1.0.0"},+ "agentCapabilities": {"loadSession": True},+ },+ }+ )+ elif method == "session/new":+ session_id = uuid.uuid4().hex+ store[session_id] = []+ _save_store(store)+ _send({"jsonrpc": "2.0", "id": rid, "result": {"sessionId": session_id}})+ elif method == "session/load":+ session_id = str(params.get("sessionId"))+ if session_id not in store:+ _send({"jsonrpc": "2.0", "id": rid, "result": {}})+ continue+ for old in store[session_id]:+ _text(session_id, old, kind="user_message_chunk")+ _text(session_id, "replayed answer")+ _send({"jsonrpc": "2.0", "id": rid, "result": {"modes": None, "_meta": {}}})+ elif method == "session/prompt":+ blocks = params.get("prompt") or []+ text = "".join(str(b.get("text") or "") for b in blocks if isinstance(b, dict))+ _prompt(rid, str(params.get("sessionId")), text, store)+ elif rid is not None:+ _send({"jsonrpc": "2.0", "id": rid, "error": {"code": -32601, "message": "nope"}})+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/unit/agent_runtimes/__init__.py b/tests/unit/agent_runtimes/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/unit/agent_runtimes/test_acp_runner.py b/tests/unit/agent_runtimes/test_acp_runner.pynew file mode 100644index 0000000000..f5a55efec4--- /dev/null+++ b/tests/unit/agent_runtimes/test_acp_runner.py@@ -0,0 +1,179 @@+"""An ACP runtime turn through the shared CLI pump, against a scripted agent."""++from __future__ import annotations++import asyncio+import json+import os+import sys+from pathlib import Path+from typing import Any++import pytest++from jarvis.agent_chat import runner_acp+from jarvis.agent_chat import runner_cli as rc+from jarvis.agent_chat.runner_api import TurnHandle+from jarvis.agent_chat.store import AgentChatSession+from jarvis.agent_runtimes.acp import AcpTurn++_AGENT = Path(__file__).resolve().parents[2] / "fakes" / "fake_acp_agent.py"+++def _session(tmp_path: Path, *, vendor: str | None, mode: str) -> AgentChatSession:+ return AgentChatSession(+ session_id="society:hermit",+ title="Hermit",+ provider="local-openai",+ model="fake-model",+ effort="",+ cwd=str(tmp_path),+ permission_mode=mode,+ vendor_session=vendor,+ created_ms=0,+ updated_ms=0,+ message_count=0,+ preview="",+ surface="society",+ runtime="hermes",+ )+++def _turn(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ text: str,+ *,+ vendor: str | None = None,+ mode: str = "bypass",+ answer: str = "allow",+ report_session: str | None = None,+) -> tuple[str | None, list[dict[str, Any]], list[tuple[str, str]], list[str | None]]:+ resumes: list[str | None] = []++ async def fake_plan(handle: Any, runner: str, *, prompt: str, cwd: Path, resume, identity):+ resumes.append(resume)+ env = dict(os.environ)+ env["FAKE_ACP_STORE"] = str(tmp_path / "store.json")+ return rc.CliPlan(+ argv=[sys.executable, str(_AGENT)],+ env=env,+ stdin_text=None,+ shape="acp",+ vendor_session=None,+ keep_stdin=True,+ acp=AcpTurn(+ turn_id=handle.turn_id,+ cwd=str(cwd),+ prompt_text=prompt,+ resume=resume,+ auto_allow=handle.session.permission_mode == "bypass",+ report_session=report_session,+ ),+ )++ monkeypatch.setattr(runner_acp, "plan_runtime_turn", fake_plan)+ events: list[dict[str, Any]] = []+ asked: list[tuple[str, str]] = []++ async def emit(event: dict[str, Any]) -> None:+ events.append(event)++ async def ask(call_id: str, name: str, args: dict[str, Any], summary: str) -> str:+ asked.append((call_id, name))+ return answer++ handle = TurnHandle(+ session=_session(tmp_path, vendor=vendor, mode=mode),+ turn_id="t1",+ emit=emit,+ request_approval=ask,+ cancel=asyncio.Event(),+ )+ vendor_out = asyncio.run(rc.run_cli_turn(handle, text, "hermes-cli"))+ return vendor_out, events, asked, resumes+++def _finished(events: list[dict[str, Any]]) -> dict[str, Any]:+ return next(e["payload"] for e in events if e["kind"] == "turn_finished")+++def _texts(events: list[dict[str, Any]]) -> list[str]:+ return [e["payload"]["text"] for e in events if e["kind"] == "assistant_text"]+++def test_the_runtime_runners_count_as_cli_seats():+ assert rc.supports_cli_runner("hermes-cli")+ assert rc.supports_cli_runner("openclaw-cli")+++def test_a_fresh_turn_streams_text_reasoning_and_usage(monkeypatch, tmp_path):+ vendor, events, asked, _ = _turn(monkeypatch, tmp_path, "hello")+ assert vendor # the ACP session id is kept for the next turn+ assert _texts(events) == ["echo: hello"]+ kinds = [e["kind"] for e in events]+ assert "reasoning" in kinds and "text_delta" in kinds+ finished = _finished(events)+ assert finished["status"] == "done" and finished["error"] is None+ assert finished["usage"]["input_tokens"] == 11+ assert asked == []+++def test_a_resumed_turn_reopens_the_session_and_hides_the_replay(monkeypatch, tmp_path):+ first, _, _, _ = _turn(monkeypatch, tmp_path, "one")+ second, events, _, resumes = _turn(monkeypatch, tmp_path, "two", vendor=first)+ assert second == first+ assert resumes == [first]+ # The replayed history of "one" never reaches the chat a second time.+ assert _texts(events) == ["echo: two"]+ store = json.loads((tmp_path / "store.json").read_text(encoding="utf-8"))+ assert store[first] == ["one", "two"]+++def test_a_lost_session_is_retried_fresh(monkeypatch, tmp_path):+ vendor, events, _, resumes = _turn(monkeypatch, tmp_path, "again", vendor="gone-123")+ assert resumes == ["gone-123", None]+ assert vendor and vendor != "gone-123"+ assert _texts(events) == ["echo: again"]+ assert _finished(events)["status"] == "done"+++def test_a_jarvis_tool_call_reaches_the_timeline_under_its_mcp_name(monkeypatch, tmp_path):+ _, events, _, _ = _turn(monkeypatch, tmp_path, "TOOL please")+ calls = [e["payload"] for e in events if e["kind"] == "tool_call"]+ results = [e["payload"] for e in events if e["kind"] == "tool_result"]+ assert [c["name"] for c in calls] == ["mcp__jarvis__society_memory_recall"]+ assert calls[0]["input"] == {"query": "hi"}+ assert results[0]["output"] == "recalled" and results[0]["is_error"] is False+ assert _texts(events) == ["used the tool"]+++def test_ask_mode_puts_the_runtimes_permission_on_the_chat_card(monkeypatch, tmp_path):+ _, events, asked, _ = _turn(monkeypatch, tmp_path, "ASK now", mode="ask", answer="allow")+ assert asked == [("tc-ask", "terminal")]+ assert _texts(events) == ["permission: yes"]+ # The card has a tool row to sit on.+ assert any(e["kind"] == "tool_call" and e["payload"]["call_id"] == "tc-ask" for e in events)+++def test_a_denied_permission_selects_the_reject_option(monkeypatch, tmp_path):+ _, events, _, _ = _turn(monkeypatch, tmp_path, "ASK now", mode="ask", answer="deny")+ assert _texts(events) == ["permission: no"]+++def test_bypass_answers_the_runtime_without_a_card(monkeypatch, tmp_path):+ _, events, asked, _ = _turn(monkeypatch, tmp_path, "ASK now", mode="bypass")+ assert asked == []+ assert _texts(events) == ["permission: yes"]+++def test_a_prompt_error_finishes_the_turn_with_that_error(monkeypatch, tmp_path):+ _, events, _, _ = _turn(monkeypatch, tmp_path, "FAIL")+ finished = _finished(events)+ assert finished["status"] == "error"+ assert "model down" in (finished["error"] or "")+++def test_a_fixed_session_key_is_what_the_chat_keeps(monkeypatch, tmp_path):+ vendor, _, _, _ = _turn(monkeypatch, tmp_path, "hi", report_session="agent:main:main")+ assert vendor == "agent:main:main"diff --git a/tests/unit/agent_runtimes/test_runtime_configs.py b/tests/unit/agent_runtimes/test_runtime_configs.pynew file mode 100644index 0000000000..c8766bebc8--- /dev/null+++ b/tests/unit/agent_runtimes/test_runtime_configs.py@@ -0,0 +1,258 @@+"""What Jarvis writes for Hermes and OpenClaw, and how it routes models."""++from __future__ import annotations++import json+from pathlib import Path+from types import SimpleNamespace++import pytest++from jarvis.agent_runtimes import RUNNER_RUNTIMES, driver+from jarvis.agent_runtimes.base import RuntimeTurn, child_env, parse_version, persona_text+from jarvis.agent_runtimes.hermes import HermesRuntime+from jarvis.agent_runtimes.model_map import (+ KEY_ENV_VAR,+ ModelRoute,+ RouteUnavailable,+ route_for,+ supports,+)+from jarvis.agent_runtimes.openclaw import (+ SESSION_KEY,+ OpenClawRuntime,+ _node_supported,+ session_key,+)+from jarvis.core.config import override_provider_secrets++_SECRET = "sk-test-" + "123" # a fake key for assertions+_TOKEN = "gw-" + "token"+++def _route(*, key: str | None = _SECRET, transport: str = "chat_completions") -> ModelRoute:+ return ModelRoute(+ provider="openai",+ model="gpt-5.2",+ base_url="https://api.openai.com/v1",+ transport=transport, # type: ignore[arg-type]+ api_key=key,+ )+++def _turn(tmp_path: Path, **overrides) -> RuntimeTurn:+ values = {+ "agent_id": "hermit",+ "agent_name": "Hermit",+ "session_id": "society:hermit",+ "workspace": tmp_path,+ "route": _route(),+ "resume": None,+ "auto_approve": True,+ "mcp_url": "http://127.0.0.1:47820/api/control/mcp/",+ "control_key": "control-key-xyz",+ }+ values.update(overrides)+ return RuntimeTurn(**values)+++def test_runners_map_to_their_runtimes():+ assert RUNNER_RUNTIMES == {"hermes-cli": "hermes", "openclaw-cli": "openclaw"}+ assert isinstance(driver("hermes"), HermesRuntime)+ assert isinstance(driver("openclaw"), OpenClawRuntime)+ with pytest.raises(KeyError):+ driver("skynet")+++# ------------------------------------------------------------------ Hermes+++def test_hermes_config_reads_the_key_from_the_environment(tmp_path):+ config = HermesRuntime().config_for(_turn(tmp_path))+ text = json.dumps(config)+ assert _SECRET not in text and "control-key-xyz" not in text+ assert config["model"]["provider"] == "custom:jarvis"+ assert config["model"]["default"] == "gpt-5.2"+ provider = config["providers"]["jarvis"]+ assert provider["key_env"] == KEY_ENV_VAR+ assert provider["api"] == "https://api.openai.com/v1"+ assert provider["transport"] == "chat_completions"+ assert config["terminal"]["cwd"] == str(tmp_path)+++def test_hermes_self_learning_extras_stay_off(tmp_path):+ config = HermesRuntime().config_for(_turn(tmp_path))+ assert config["memory"]["memory_enabled"] is False+ assert config["memory"]["nudge_interval"] == 0+ assert config["curator"]["enabled"] is False+ assert config["auxiliary"]["background_review"]["enabled"] is False+ assert config["skills"]["creation_nudge_interval"] == 0+++def test_hermes_approvals_follow_the_chat_stance_and_never_the_guardian(tmp_path):+ runtime = HermesRuntime()+ assert runtime.config_for(_turn(tmp_path))["approvals"]["mode"] == "off"+ asked = runtime.config_for(_turn(tmp_path, auto_approve=False))+ assert asked["approvals"]["mode"] == "manual"+++def test_hermes_denied_shell_disables_its_terminal(tmp_path):+ config = HermesRuntime().config_for(_turn(tmp_path, denied_native=frozenset({"shell"})))+ assert set(config["agent"]["disabled_toolsets"]) == {"terminal", "code_execution"}+++def test_a_keyless_local_model_writes_no_key_reference(tmp_path):+ route = ModelRoute("ollama", "qwen3", "http://127.0.0.1:11434/v1", "chat_completions", None)+ config = HermesRuntime().config_for(_turn(tmp_path, route=route))+ assert "key_env" not in config["providers"]["jarvis"]+ assert route.env() == {}+++# ---------------------------------------------------------------- OpenClaw+++def test_openclaw_config_keeps_both_keys_out_of_the_file(tmp_path):+ config = OpenClawRuntime().config_for(_turn(tmp_path), port=4321, token=_TOKEN)+ text = json.dumps(config)+ assert _SECRET not in text and "control-key-xyz" not in text+ provider = config["models"]["providers"]["jarvis"]+ assert provider["apiKey"] == "${JARVIS_RUNTIME_API_KEY}"+ assert provider["api"] == "openai-completions"+ headers = config["mcp"]["servers"]["jarvis"]["headers"]+ assert headers["Authorization"] == "Bearer ${JARVIS_CONTROL_API_KEY}"+ assert headers["X-Jarvis-Chat-Session"] == "society:hermit"+++def test_openclaw_never_runs_background_turns_or_persona_files(tmp_path):+ config = OpenClawRuntime().config_for(_turn(tmp_path), port=4321, token=_TOKEN)+ defaults = config["agents"]["defaults"]+ assert defaults["heartbeat"] == {"every": "0m"}+ assert defaults["skipBootstrap"] is True+ assert defaults["contextInjection"] == "never"+ assert defaults["model"]["primary"] == "jarvis/gpt-5.2"+ assert config["session"]["reset"]["mode"] == "none"+ assert "automations" in config["tools"]["deny"]+ assert config["gateway"]["bind"] == "loopback"+++def test_openclaw_exec_mode_follows_stance_and_grants(tmp_path):+ runtime = OpenClawRuntime()+ full = runtime.config_for(_turn(tmp_path), port=1, token=_TOKEN)+ ask = runtime.config_for(_turn(tmp_path, auto_approve=False), port=1, token=_TOKEN)+ denied = runtime.config_for(+ _turn(tmp_path, denied_native=frozenset({"shell", "web"})), port=1, token=_TOKEN+ )+ assert full["tools"]["exec"]["mode"] == "full"+ assert ask["tools"]["exec"]["mode"] == "ask"+ assert denied["tools"]["exec"]["mode"] == "deny"+ assert "browser" in denied["tools"]["deny"]+++def test_openclaw_anthropic_route_uses_the_messages_adapter(tmp_path):+ route = _route(transport="anthropic_messages")+ config = OpenClawRuntime().config_for(_turn(tmp_path, route=route), port=1, token=_TOKEN)+ assert config["models"]["providers"]["jarvis"]["api"] == "anthropic-messages"+++def test_openclaw_without_tools_writes_no_mcp_server(tmp_path):+ config = OpenClawRuntime().config_for(+ _turn(tmp_path, mcp_url=None, control_key=None), port=1, token=_TOKEN+ )+ assert "mcp" not in config+++def test_a_routine_run_never_shares_the_main_conversation():+ assert session_key("hermit", "society:hermit") == SESSION_KEY+ run = session_key("hermit", "society:hermit:routine:task-1:abc")+ assert run.startswith("agent:main:run-") and run != SESSION_KEY+ assert run == session_key("hermit", "society:hermit:routine:task-1:abc")+++def test_openclaw_node_engine_range():+ assert _node_supported((24, 21, 0))+ assert _node_supported((26, 1, 0))+ assert not _node_supported((24, 13, 0))+ assert not _node_supported((25, 0, 0))+ assert not _node_supported(None)+++# ------------------------------------------------------------------ shared+++def test_child_env_drops_other_providers_keys(monkeypatch):+ monkeypatch.setenv("ANTHROPIC_API_KEY", "leak")+ monkeypatch.setenv("GITHUB_TOKEN", "leak")+ env = child_env({"EXTRA": "1"})+ assert "ANTHROPIC_API_KEY" not in env and "GITHUB_TOKEN" not in env+ assert env["EXTRA"] == "1" and env["PYTHONIOENCODING"] == "utf-8"+++def test_version_parsing_reads_both_numbering_schemes():+ assert parse_version("Hermes Agent v0.20.6 (2026.8.27)") == (0, 20, 6)+ assert parse_version("OpenClaw 2026.9.8 (fc23bc8)") == (2026, 9, 8)+ assert parse_version("garbage") is None+++def test_the_persona_defers_to_the_jarvis_identity():+ text = persona_text("Hermit")+ assert "Hermit" in text and "<jarvis_identity>" in text+++# --------------------------------------------------------------- model map+++def _cfg(**providers) -> SimpleNamespace:+ return SimpleNamespace(+ brain=SimpleNamespace(+ providers={k: SimpleNamespace(**v) for k, v in providers.items()}+ )+ )+++def test_subscription_seats_are_not_offered():+ assert supports("openai") and supports("claude-api") and supports("ollama")+ assert not supports("openai-codex") and not supports("grok-build")+ with pytest.raises(RouteUnavailable):+ route_for(_cfg(), "openai-codex", "gpt-5.5")+++def test_an_api_key_provider_routes_with_its_saved_key():+ with override_provider_secrets({"openai": _SECRET}):+ route = route_for(_cfg(), "openai", "gpt-5.2")+ assert route.base_url == "https://api.openai.com/v1"+ assert route.api_key == _SECRET and route.env() == {KEY_ENV_VAR: _SECRET}+++def test_a_missing_key_is_reported_in_plain_words():+ with override_provider_secrets({"openrouter": None}), pytest.raises(RouteUnavailable) as err:+ route_for(_cfg(), "openrouter", "some/model")+ assert "API key" in str(err.value)+++def test_claude_routes_over_the_messages_api():+ with override_provider_secrets({"claude-api": _SECRET}):+ route = route_for(_cfg(), "claude-api", "claude-sonnet-5")+ assert route.transport == "anthropic_messages"+ assert route.base_url == "https://api.anthropic.com"+++def test_hermes_restore_finds_the_key_under_its_host_name():+ from jarvis.agent_runtimes.hermes import _restore_key_aliases++ assert _restore_key_aliases("https://api.openai.com/v1", "k") == {"OPENAI_API_KEY": "k"}+ assert _restore_key_aliases("https://openrouter.ai/api/v1", "k") == {"OPENROUTER_API_KEY": "k"}+ assert _restore_key_aliases("https://api.x.ai/v1", "k") == {"X_API_KEY": "k"}+ assert _restore_key_aliases("https://api.anthropic.com", "k") == {"ANTHROPIC_API_KEY": "k"}+ assert _restore_key_aliases("https://integrate.api.nvidia.com/v1", "k") == {+ "NVIDIA_API_KEY": "k"+ }+ assert _restore_key_aliases("http://127.0.0.1:11434/v1", "k") == {}+ assert _restore_key_aliases("https://api.openai.com/v1", None) == {}+++def test_hermes_model_block_names_the_endpoint_for_session_restore(tmp_path):+ keyed = HermesRuntime().config_for(_turn(tmp_path))["model"]+ assert keyed["base_url"] == "https://api.openai.com/v1" and "api_key" not in keyed+ route = ModelRoute("ollama", "qwen3", "http://127.0.0.1:11434/v1", "chat_completions", None)+ local = HermesRuntime().config_for(_turn(tmp_path, route=route))["model"]+ assert local["api_key"] == "no-key-required"