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): set up and update Hermes and OpenClaw automatically

rubenluetke10-beep58d571345840
diff --git a/docs/agent-runtimes.md b/docs/agent-runtimes.md
index 5f6c847aeb..abda26eaeb 100644
--- a/docs/agent-runtimes.md
+++ b/docs/agent-runtimes.md
@@ -12,7 +12,39 @@ The runtime is chosen once, in the "new agent" dialog every plus in the
society opens (name, runtime, the companion bot that follows the agent), and
is fixed for the agent's life: the roster refuses a change, because the
agent's sessions, runtime folder and tools belong to it. The model menu of
-the agent's chat shows the runtime and offers its update when one is due.
+the agent's chat shows the runtime.
+
+## Setup and updates
+
+Nobody installs Hermes or OpenClaw by hand (`jarvis/agent_runtimes/manager.py`):
+
+- **Picking a runtime sets it up.** The dialog sends
+ `POST /api/agent-runtimes/{runtime}/ensure` as soon as Hermes or OpenClaw is
+ picked; creating the agent sends it again. `ensure` runs the project's own
+ installer when the runtime is missing (OpenClaw's also adds the Node.js it
+ needs) and its own updater when it is too old. The agent can be created
+ while that runs.
+- **A turn waits for the setup.** A turn on a runtime that is not ready posts
+ a `runtime_setup` notice in the chat and waits for the job; a setup that
+ fails ends the turn with its reason.
+- **Daily updates.** While any agent uses a runtime, the society runtime runs
+ its updater once a day (first round 10 minutes after start), only when no
+ turn of it is running. An update that leaves the runtime unable to start is
+ repaired by a fresh install with the official installer.
+- **No version numbers in the UI.** The dialog says "Ready", "Setting up…" or
+ "Sets itself up"; versions stay internal (the minimum versions gate
+ readiness).
+
+None of this calls a model, so setup and updates never spend a key.
+
+## Models
+
+An agent on Hermes or OpenClaw runs on any Jarvis provider with an API key or
+a local server (`model_map.py`); the dialog lists the ones connected right now.
+Subscription seats (Claude Code, Codex, …) are not offered. A Claude
+subscription login (`sk-ant-oat…`) saved in the Anthropic API-key slot is
+not an API key either: Anthropic's API refuses it from these runtimes
+("OAuth access token is invalid"), so `route_for` treats that slot as empty.
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
diff --git a/docs/os-parity.md b/docs/os-parity.md
index fc0a247fd3..220b4fe1b3 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -1265,7 +1265,7 @@ build: the first release with this code needs one live update per OS.
| P-41 | Medium | Dictation final pass | The dictation lane reads its final pass on the machine, in front of any configured cloud provider, through the same out-of-process worker the live preview uses (`jarvis.dictation.preview_worker`) with a stronger checkpoint (`[dictation].local_model`, default `large-v3-turbo`, `int8_float16`, beam 5). 2026-09-02 forensics: 220 of 220 dictations had run on a cloud recognizer the settings did not name, because the VOICE lane had been moved there to keep CUDA out of the desktop process, and the dictation lane inherited the move — round-trips as lag, near-empty answers on 25 s windows as "truncated window" repairs. The provider declines itself with a CROSSABLE failure (HTTP-503-shaped, `LocalEngineUnavailable`) so the configured provider is one step behind on every press and never a restart away: too little free accelerator memory (`[dictation].local_min_free_gb`, default 1.5; an UNKNOWN reading never blocks), a worker that only comes up on the CPU, a missing local runtime, a worker that died. A call abandoned at its ceiling leaves its answer in the pipe, so the next call kills that worker instead of reading it (AP-24) | `jarvis/dictation/local_final.py::LocalFinalSTT`, `jarvis/speech/pipeline.py::_dictation_local_final`, `_dictation_stt`, `jarvis/dictation/local_preview.py::_spawn_worker_model` (`compute`), `preview_worker.py` (`beam_size`, `segments`), `jarvis/hardware/detection.py::free_accelerator_gb` | Windows/Linux with an NVIDIA card and the local runtime: the final pass runs locally when ≥ 1.5 GB is free, else the cloud chain. macOS: no NVIDIA reading → the memory gate passes as unknown, and the worker's own device ladder decides; a CPU-only worker is declined for the final pass (a beam decode of a 25 s window on a CPU is slower than the cloud it would replace), so Apple Silicon stays on the configured provider until a Metal-backed runtime exists. Headless `python:3.11-slim` (no `faster-whisper`): the provider is never built and the chain is exactly what it was. Switch: `[dictation].local_engine = false`. Guards: `tests/unit/dictation/test_local_final.py`, `test_preview_worker.py` |
| P-41 | Low | CLI install / connect terminal | Pressing **Install** or **Connect** in the CLI section opens a REAL terminal window and runs the command there, because an interactive OAuth login belongs in a shell the user can see and type into. That spawn was Windows-only until 2026-08-28 (`wt` -> `pwsh` -> `powershell`), so on macOS and Linux the two buttons reported "No external terminal available" and no CLI could be installed from the app at all. macOS now goes through `osascript` to Terminal.app, Linux through the first of seven emulators that exists (Debian's `x-terminal-emulator` alternative first, so the user's own default wins), and the window is held open afterwards the way `-NoExit` holds it on Windows. One install click now carries all the way to signed in: the terminal runs the install, refreshes PATH in that same shell, and continues into the CLI's login command, stopping at the first step that fails. The chain operator differs per OS on purpose — Windows PowerShell 5.1 is a possible fallback shell and `&&` is a parser error there, so the Windows spelling nests `if ($?)` instead | `jarvis/clis/external_terminal.py` (`_spawn_windows`, `_spawn_macos`, `_spawn_linux`, `chain_commands`, `path_refresh_command`), `jarvis/ui/web/cli_routes.py::spawn_external`, `tests/unit/clis/test_install_path.py` | Windows: verified live (wt path, composed install+login command). macOS/Linux: same code path, the branch itself unverified from this machine. A box with no screen has no window to open, so there the endpoint falls back to the in-app streaming install job and the UI says so instead of claiming a terminal appeared — a headless server can still install a CLI, it just cannot run an interactive login |
| P-42 | High | Outbound sockets (every lane) | Every connection borrows an ephemeral port from a pool the OS owns, and a closed one keeps that port through TIME_WAIT. The ceiling and the linger differ per OS, and so does what gives out first: **Windows** 16 384 ports / 120 s — the tightest by far, and the port pool is what empties, which stops EVERY process on the machine from connecting (the desktop appears frozen, then heals itself when TIME_WAIT expires); **Linux** 28 232 ports / 60 s, but `RLIMIT_NOFILE` is normally the tighter of the two (1024 on a stock `python:3.11-slim`), so the backend dies of EMFILE while the desktop around it is fine; **macOS** 16 384 ports / 15 s, so it recovers fastest. BUG-215 was the Windows shape: an unjittered wake storm (one socket per pane, per window, per instance, all on one `visibilitychange`) on top of a standing per-call-client burn. The rule that follows is to cap the burst, never to widen a limit — code that fits the Windows budget fits everywhere | `jarvis/ui/web/frontend/src/lib/connectBudget.ts` (`jitteredDelay`, `spreadDelay`, `requestConnect`), `jarvis/core/http_pool.py` (`HttpClientPool`, `SyncHttpClientPool`, `default_limits`), `jarvis/core/socket_budget.py` (`read_platform_limits`, `take_census`, `SocketBudgetWatchdog`), `jarvis/realtime/local_server/supervisor.py::_port_open` (`SO_LINGER`) | Identical on all three: one shared connect budget in the frontend, pooled keep-alive clients in Python, and a watchdog armed by BOTH entry points (desktop shell and `--headless`) that reads the ceiling per platform — `netsh` on Windows (parsed as integers, because it translates its own field names), `/proc/sys/net/ipv4/ip_local_port_range` plus `RLIMIT_NOFILE` on Linux, `sysctl net.inet.ip.portrange.*` on macOS. A host that answers none of them falls back to the documented default and says the number was assumed; a host with no ceiling at all logs one line and throttles nothing, because a watchdog that cannot see must never be what stops the app working. macOS additionally refuses the system-wide socket table to an unprivileged process, so the census there counts this process only and labels the number a floor. Guards: `tests/contract/test_socket_budget.py` (all three hosts faked, plus a German and a Japanese `netsh`), `tests/unit/core/test_socket_budget_watchdog.py`, `jarvis/ui/web/frontend/src/lib/connectBudget.test.ts` |
-| P-45 | Medium | Hermes / OpenClaw agent runtimes | A society agent can run on Hermes or OpenClaw instead of Jarvis' own loop (docs/agent-runtimes.md). Both are separately installed programs driven over ACP: Hermes as one `hermes acp` process per turn on the agent's own `HERMES_HOME`, OpenClaw through `openclaw acp` against a supervised per-agent Gateway. Process containment differs per OS exactly as for every CLI seat: a Job Object on Windows, a process group on POSIX; killing the app reaps the OpenClaw Gateway on Windows (verified live), on POSIX the Gateway is also stopped by the society shutdown and the idle reaper. Install and update use each project's own installer per OS (`install.ps1` on Windows, `install.sh` on macOS/Linux, Hermes' `hermes update`, OpenClaw's `openclaw update --no-restart`) and run only on a button press. OpenClaw needs Node.js 24.16+ or 26.1+; its installer provisions a private Node.js where the system one is older | `jarvis/agent_runtimes/` (`hermes.py`, `openclaw.py`, `base.py::child_env`, `manager.py`), `jarvis/agent_chat/runner_acp.py`, `jarvis/core/process_tree.py` | Windows: both runtimes verified live 2026-10-06 (Hermes 0.20.6, OpenClaw 2026.9.8, local Ollama model, memory read and write through the Jarvis tools). macOS/Linux: the same code path, verified only by the weekly `agent-runtimes-canary.yml` workflow (latest Hermes and OpenClaw, fake model). Headless `python:3.11-slim`: nothing is installed or started unless an agent is switched to a runtime; Hermes' Linux installer needs git and curl, OpenClaw needs a supported Node.js. Guards: `tests/unit/agent_runtimes/`, `tests/unit/society/test_agent_runtime_field.py` |
+| P-45 | Medium | Hermes / OpenClaw agent runtimes | A society agent can run on Hermes or OpenClaw instead of Jarvis' own loop (docs/agent-runtimes.md). Both are separately installed programs driven over ACP: Hermes as one `hermes acp` process per turn on the agent's own `HERMES_HOME`, OpenClaw through `openclaw acp` against a supervised per-agent Gateway. Process containment differs per OS exactly as for every CLI seat: a Job Object on Windows, a process group on POSIX; killing the app reaps the OpenClaw Gateway on Windows (verified live), on POSIX the Gateway is also stopped by the society shutdown and the idle reaper. Install and update use each project's own installer per OS (`install.ps1` on Windows, `install.sh` on macOS/Linux, Hermes' `hermes update`, OpenClaw's `openclaw update --no-restart`) and run on their own: when an agent is set to a runtime that is missing or too old, before a turn on it, and once a day while an agent uses it (only when no turn runs). OpenClaw needs Node.js 24.16+ or 26.1+; its installer provisions a private Node.js where the system one is older | `jarvis/agent_runtimes/` (`hermes.py`, `openclaw.py`, `base.py::child_env`, `manager.py`), `jarvis/agent_chat/runner_acp.py`, `jarvis/core/process_tree.py` | Windows: both runtimes verified live 2026-10-06 (Hermes 0.20.6, OpenClaw 2026.9.8, local Ollama model, memory read and write through the Jarvis tools). macOS/Linux: the same code path, verified only by the weekly `agent-runtimes-canary.yml` workflow (latest Hermes and OpenClaw, fake model). Headless `python:3.11-slim`: nothing is installed or started unless an agent is switched to a runtime; Hermes' Linux installer needs git and curl, OpenClaw needs a supported Node.js. Guards: `tests/unit/agent_runtimes/`, `tests/unit/society/test_agent_runtime_field.py` |
## Agent conversation continuity and learning (2026-09-07)
diff --git a/jarvis/agent_chat/runner_acp.py b/jarvis/agent_chat/runner_acp.py
index 29051e0e35..3f032a99f5 100644
--- a/jarvis/agent_chat/runner_acp.py
+++ b/jarvis/agent_chat/runner_acp.py
@@ -65,6 +65,42 @@ def _denied_native(agent: Any, plan_mode: bool) -> frozenset[str]:
return frozenset(denied)
+async def _ready(handle: Any, runtime_name: str, runtime: Any) -> None:
+ """Install or update the runtime first when it cannot run this turn.
+
+ Nobody sets Hermes or OpenClaw up by hand: the first turn on a fresh
+ machine (or after a failed update) waits for the official installer and
+ says so in the chat. A runtime that still is not ready ends the turn
+ with the reason.
+ """
+ from jarvis.agent_chat.events import make_event
+ from jarvis.agent_chat.runner_cli import CliUnavailable
+ from jarvis.agent_runtimes import manager
+
+ current = manager.job(runtime_name)
+ setting_up = current is not None and current.state == "running"
+ status = await asyncio.to_thread(runtime.detect)
+ if status.ready and not setting_up:
+ return
+ await handle.emit(
+ make_event(
+ "notice",
+ {
+ "kind": "runtime_setup",
+ "runtime": runtime_name,
+ "turn_id": handle.turn_id,
+ "text": f"Setting up {runtime.label} for this agent. The first time takes "
+ "a few minutes; the message is sent as soon as it is ready.",
+ },
+ )
+ )
+ status = await manager.wait_ready(runtime_name)
+ if not status.ready:
+ current = manager.job(runtime_name)
+ reason = (current.message if current is not None else "") or status.problem
+ raise CliUnavailable(f"{runtime.label} could not be set up. {reason}".strip())
+
+
async def plan_runtime_turn(
handle: Any,
runner: str,
@@ -109,6 +145,7 @@ async def plan_runtime_turn(
denied_native=_denied_native(agent, plan_mode),
)
runtime = driver(runtime_name)
+ await _ready(handle, runtime_name, runtime)
try:
launch = await runtime.launch(turn)
except RuntimeUnavailable as exc:
diff --git a/jarvis/agent_runtimes/base.py b/jarvis/agent_runtimes/base.py
index a30c204cf1..d16ceaf3b3 100644
--- a/jarvis/agent_runtimes/base.py
+++ b/jarvis/agent_runtimes/base.py
@@ -7,10 +7,12 @@ A runtime module (``hermes``, ``openclaw``) answers three questions:
* :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.
+ runtime's own official installer and updater, run by ``manager`` when an
+ agent needs the runtime and once a day to keep it current.
-Everything a runtime writes lives under ``user_data_dir()/agent_runtimes/``;
-the person's own Hermes or OpenClaw setup is never read or changed.
+Every agent's runtime state lives under ``user_data_dir()/agent_runtimes/``;
+the person's own Hermes or OpenClaw configuration is never read or changed.
+The program itself is the standard install the official installer makes.
"""
from __future__ import annotations
@@ -181,6 +183,10 @@ class AgentRuntimeDriver(Protocol):
def update_command(self) -> list[str] | None: ...
+ def busy(self) -> bool:
+ """Whether a turn is running on this runtime (updates wait for idle)."""
+ ...
+
async def stop(self, agent_id: str | None = None) -> None:
"""Stop background processes (all agents when ``agent_id`` is None)."""
...
@@ -218,6 +224,10 @@ class TurnSlots:
def lock(self, key: str) -> asyncio.Lock:
return self._locks.setdefault(key, asyncio.Lock())
+ def busy(self) -> bool:
+ """Whether any turn holds a slot right now."""
+ return any(lock.locked() for lock in self._locks.values())
+
async def acquire(self, key: str) -> Callable[[], None]:
lock = self.lock(key)
try:
diff --git a/jarvis/agent_runtimes/hermes.py b/jarvis/agent_runtimes/hermes.py
index f054dc66e0..364e77484b 100644
--- a/jarvis/agent_runtimes/hermes.py
+++ b/jarvis/agent_runtimes/hermes.py
@@ -150,6 +150,9 @@ class HermesRuntime:
binary = _binary()
return [binary, "update", "--yes"] if binary else None
+ def busy(self) -> bool:
+ return self._slots.busy()
+
async def stop(self, agent_id: str | None = None) -> None:
"""Hermes runs one process per turn; nothing stays behind between turns."""
return
diff --git a/jarvis/agent_runtimes/manager.py b/jarvis/agent_runtimes/manager.py
index 8b2da679de..81ce7fc234 100644
--- a/jarvis/agent_runtimes/manager.py
+++ b/jarvis/agent_runtimes/manager.py
@@ -1,11 +1,18 @@
-"""Install and update Hermes / OpenClaw with their own official tools.
-
-Only ever started by the person (a button in an agent's Brain settings): an
-install downloads and runs the project's own installer, an update runs the
-runtime's own updater. One job per runtime at a time; its output goes to a
-log file whose tail the UI shows. Before an update every running process of
-that runtime is stopped — on Windows a running Hermes venv or OpenClaw
-Gateway would hold files the updater must replace.
+"""Install and keep Hermes / OpenClaw current with their own official tools.
+
+Nobody sets either runtime up by hand. Choosing Hermes or OpenClaw for an
+agent starts :func:`ensure`: the project's own installer when it is missing
+(OpenClaw's also adds the Node.js it needs), its own updater when it is too
+old. A turn that finds its runtime not ready waits for that job
+(:func:`wait_ready`). While any agent uses a runtime, :func:`keep_current`
+runs the updater once a day when no turn of it is running; an update that
+leaves the runtime unable to start is repaired by a fresh install.
+
+One job per runtime at a time; its output goes to a log file whose tail the
+UI can show. Before an update every running process of that runtime is
+stopped — on Windows a running Hermes venv or OpenClaw Gateway would hold
+files the updater must replace. None of this calls a model, so nothing here
+spends a key.
"""
from __future__ import annotations
@@ -14,11 +21,12 @@ import asyncio
import contextlib
import logging
import time
+from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from typing import Any, Final, Literal
from jarvis.agent_runtimes import RUNTIME_NAMES, driver
-from jarvis.agent_runtimes.base import child_env, runtimes_root
+from jarvis.agent_runtimes.base import RuntimeStatus, child_env, runtimes_root
log = logging.getLogger(__name__)
@@ -28,6 +36,10 @@ JobState = Literal["running", "done", "failed"]
#: An installer that has not finished in this long is stopped.
_JOB_TIMEOUT_S: Final[float] = 30 * 60
+#: First automatic update round after the app starts, then one per day.
+_FIRST_UPDATE_DELAY_S: Final[float] = 10 * 60
+_UPDATE_EVERY_S: Final[float] = 24 * 60 * 60
+
@dataclass(slots=True)
class RuntimeJob:
@@ -104,10 +116,111 @@ async def start(runtime: str, kind: JobKind) -> RuntimeJob:
return failed
new_job = RuntimeJob(runtime, kind)
_JOBS[runtime] = new_job
- _TASKS[runtime] = asyncio.get_running_loop().create_task(_run(new_job, argv))
+ _TASKS[runtime] = asyncio.get_running_loop().create_task(_run_job(new_job, argv))
return new_job
+def _needed(status: RuntimeStatus) -> JobKind | None:
+ """Which job makes ``status`` ready; ``None`` when it already is."""
+ if status.ready:
+ return None
+ if not status.installed or status.problem_kind == "node":
+ # OpenClaw's own installer is also what adds the Node.js it needs.
+ return "install"
+ return "update"
+
+
+async def ensure(runtime: str) -> RuntimeJob | None:
+ """Start the install or update ``runtime`` needs; ``None`` when it is ready."""
+ current = _JOBS.get(runtime)
+ if current is not None and current.state == "running":
+ return current
+ status = await asyncio.to_thread(driver(runtime).detect, refresh=True)
+ kind = _needed(status)
+ if kind is None:
+ return None
+ log.info(
+ "agent runtimes: %s is not ready (%s), starting its %s",
+ runtime,
+ status.problem_kind,
+ kind,
+ )
+ return await start(runtime, kind)
+
+
+async def wait_ready(runtime: str, *, timeout_s: float = _JOB_TIMEOUT_S) -> RuntimeStatus:
+ """Set ``runtime`` up when it needs it, wait for that, and return its status."""
+ await ensure(runtime)
+ task = _TASKS.get(runtime)
+ if task is not None:
+ # Shielded: a turn that gives up must not cancel a setup others wait for.
+ with contextlib.suppress(TimeoutError): # the status below says it is not ready
+ await asyncio.wait_for(asyncio.shield(task), timeout=timeout_s)
+ return await asyncio.to_thread(driver(runtime).detect)
+
+
+async def _run_job(current: RuntimeJob, argv: list[str]) -> None:
+ try:
+ await _run(current, argv)
+ if current.kind != "update":
+ return
+ status = await asyncio.to_thread(driver(current.runtime).detect, refresh=True)
+ if status.ready:
+ return
+ # The updater left a runtime that cannot start: the project's own
+ # installer replaces it.
+ install = driver(current.runtime).install_command()
+ if not install:
+ return
+ log.warning(
+ "agent runtimes: %s is not ready after its update (%s); reinstalling",
+ current.runtime,
+ status.problem_kind,
+ )
+ repair = RuntimeJob(current.runtime, "install")
+ _JOBS[current.runtime] = repair
+ await _run(repair, install)
+ finally:
+ _TASKS.pop(current.runtime, None)
+
+
+async def keep_current(in_use: Callable[[], Awaitable[set[str]]]) -> None:
+ """Update the runtimes agents use once a day, while none of their turns runs.
+
+ ``in_use`` answers which runtimes at least one agent is set to. Runs until
+ cancelled (the society runtime owns the task); a failed round is logged
+ and the next one comes a day later.
+ """
+ await asyncio.sleep(_FIRST_UPDATE_DELAY_S)
+ while True:
+ try:
+ used = await in_use()
+ for name in RUNTIME_NAMES:
+ if name in used:
+ await _update_when_idle(name)
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001 — logged; the next daily round tries again
+ log.warning("agent runtimes: the daily update round failed", exc_info=True)
+ await asyncio.sleep(_UPDATE_EVERY_S)
+
+
+async def _update_when_idle(name: str) -> None:
+ target = driver(name)
+ if target.busy():
+ log.info("agent runtimes: %s is busy; its update waits for the next round", name)
+ return
+ current = _JOBS.get(name)
+ if current is not None and current.state == "running":
+ return
+ status = await asyncio.to_thread(target.detect, refresh=True)
+ kind: JobKind = "update" if status.installed and status.problem_kind != "node" else "install"
+ await start(name, kind)
+ task = _TASKS.get(name)
+ if task is not None:
+ await asyncio.shield(task)
+
+
async def _run(current: RuntimeJob, argv: list[str]) -> None:
from jarvis.core.process_tree import make_process_tree
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
@@ -153,6 +266,5 @@ async def _run(current: RuntimeJob, argv: list[str]) -> None:
# Cancelled (app shutdown): never leave a job that looks alive.
current.state = "failed"
current.message = current.message or f"The {current.kind} was interrupted."
- _TASKS.pop(current.runtime, None)
# ``--version`` spawns a process: off the event loop.
await asyncio.to_thread(target.detect, refresh=True)
diff --git a/jarvis/agent_runtimes/model_map.py b/jarvis/agent_runtimes/model_map.py
index faaa88399d..a26dce4c78 100644
--- a/jarvis/agent_runtimes/model_map.py
+++ b/jarvis/agent_runtimes/model_map.py
@@ -28,6 +28,9 @@ 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"
+#: A Claude subscription (OAuth) token, never an Anthropic API key.
+_CLAUDE_LOGIN_PREFIX: Final[str] = "sk-ant-oat"
+
#: The provider name Jarvis registers inside the runtime's config.
RUNTIME_PROVIDER_NAME: Final[str] = "jarvis"
@@ -150,6 +153,15 @@ def route_for(config: Any, provider: str, model: str) -> ModelRoute:
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 not None and provider == "claude-api" and key.startswith(_CLAUDE_LOGIN_PREFIX):
+ # A Claude subscription login saved in the API-key slot. Jarvis' own
+ # seats can use it; Anthropic's API refuses it from Hermes / OpenClaw
+ # ("OAuth access token is invalid"), so it is not an API key here.
+ raise RouteUnavailable(
+ "The saved Anthropic credential is a Claude subscription login, not an "
+ "API key. Hermes and OpenClaw need an Anthropic API key, or pick another "
+ "provider."
+ )
if key is None and not endpoint.keyless:
raise RouteUnavailable(
f"No API key is saved for {provider}. Connect it in Settings → API keys."
diff --git a/jarvis/agent_runtimes/openclaw.py b/jarvis/agent_runtimes/openclaw.py
index 332b2b8f12..39a10052df 100644
--- a/jarvis/agent_runtimes/openclaw.py
+++ b/jarvis/agent_runtimes/openclaw.py
@@ -539,6 +539,9 @@ class OpenClawRuntime:
log.info("agent runtimes: stopping idle OpenClaw gateway %s", key)
await self._stop_gateway(gateway)
+ def busy(self) -> bool:
+ return self._slots.busy()
+
async def stop(self, agent_id: str | None = None) -> None:
for key, gateway in list(self._gateways.items()):
if agent_id is None or key in (agent_id, f"{agent_id}~runs"):
diff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.py
index bb7f519fbf..f393d5fa14 100644
--- a/jarvis/society/runtime.py
+++ b/jarvis/society/runtime.py
@@ -289,9 +289,21 @@ class SocietyRuntime:
await self.coding_supervision.start()
self._require_open_owner()
self.background(self.recover_reviews())
+ self.background(self._keep_agent_runtimes_current())
log.info("society runtime started (%s)", self.store.path)
return self
+ async def _keep_agent_runtimes_current(self) -> None:
+ """Daily Hermes / OpenClaw updates for the runtimes agents use
+ (``agent_runtimes.manager.keep_current``; first round after 10 min)."""
+ from jarvis.agent_runtimes import manager
+
+ async def in_use() -> set[str]:
+ agents = await self.roster.list()
+ return {str(agent.runtime) for agent in agents} - {"", "jarvis"}
+
+ await manager.keep_current(in_use)
+
async def _delivery_failed(self, env: SocietyEnvelope) -> None:
"""Project a terminal scheduler veto onto an already-visible chat receipt."""
if env.msg_type is not MsgType.VETO or not env.parent_event_id:
diff --git a/jarvis/ui/web/agent_runtime_routes.py b/jarvis/ui/web/agent_runtime_routes.py
index 7fcaad198b..4b1a6673b3 100644
--- a/jarvis/ui/web/agent_runtime_routes.py
+++ b/jarvis/ui/web/agent_runtime_routes.py
@@ -1,9 +1,9 @@
"""``/api/agent-runtimes`` — Hermes / OpenClaw status, install and update.
-The society UI reads these to offer the runtime switch on an agent's Brain
-settings: installed or not, version, whether that version is new enough, and
-a running setup job with its log tail. Install and update run the runtimes'
-own official tools and only when the person presses the button.
+The create dialog reads these to show whether Hermes or OpenClaw is ready
+or being set up. Setup and updates run the runtimes' own official tools and
+start on their own (``agent_runtimes.manager``): picking a runtime sends
+``ensure``.
"""
from __future__ import annotations
@@ -53,11 +53,16 @@ async def list_agent_runtimes(request: Request, refresh: bool = False) -> dict[s
openapi_extra={"x-jarvis-dangerous": True},
)
async def run_agent_runtime_setup(
- runtime: str, action: Literal["install", "update"]
+ runtime: str, action: Literal["install", "update", "ensure"]
) -> dict[str, Any]:
- """Start the runtime's official installer or updater (person-started only)."""
+ """Start the runtime's official installer or updater. ``ensure`` starts
+ whichever one it needs (``job`` is ``null`` when it is ready already);
+ the create dialog sends it as soon as Hermes or OpenClaw is picked."""
if runtime not in RUNTIME_NAMES:
raise HTTPException(404, f"unknown runtime {runtime!r}")
+ if action == "ensure":
+ found = await manager.ensure(runtime)
+ return {"job": found.to_dict() if found is not None else None}
return {"job": (await manager.start(runtime, action)).to_dict()}
diff --git a/jarvis/ui/web/frontend/src/components/society/card/RuntimePicker.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/RuntimePicker.test.tsx
index 59422547e5..0e2faee1c4 100644
--- a/jarvis/ui/web/frontend/src/components/society/card/RuntimePicker.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/card/RuntimePicker.test.tsx
@@ -2,24 +2,34 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { ReactNode } from "react";
import { afterEach, describe, expect, test, vi } from "vitest";
-import type { AgentRuntimesResponse } from "@/lib/agentRuntimesApi";
+import type { AgentRuntimeJob, AgentRuntimesResponse } from "@/lib/agentRuntimesApi";
import { RuntimeChoice, RuntimeStatusRow } from "./RuntimePicker";
vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));
-const { runtimes, setup } = vi.hoisted(() => ({
- setup: vi.fn(),
+const { runtimes, ensure } = vi.hoisted(() => ({
+ ensure: vi.fn(),
runtimes: { value: null as unknown },
}));
vi.mock("@/lib/agentRuntimesApi", () => ({
fetchAgentRuntimes: () => Promise.resolve(runtimes.value),
- startAgentRuntimeSetup: setup,
+ ensureAgentRuntime: ensure,
}));
-function status(runtime: "hermes" | "openclaw", ready: boolean, installed = ready) {
+function job(runtime: "hermes" | "openclaw", state: AgentRuntimeJob["state"]): AgentRuntimeJob {
return {
- runtime, label: runtime, installed, version: installed ? "1.0.0" : "", minimum_version: "1.0.0",
- ready, problem: "", problem_kind: installed ? (ready ? "" : "outdated") : "not_installed",
- install_hint: "", job: null,
+ runtime, kind: "install", state, started_ms: 0, finished_ms: null, exit_code: null,
+ message: state === "failed" ? "installer exited with 1" : "", log_tail: [],
+ };
+}
+
+function status(
+ runtime: "hermes" | "openclaw",
+ ready: boolean,
+ running: AgentRuntimeJob | null = null,
+) {
+ return {
+ runtime, label: runtime, installed: ready, version: ready ? "1.2.3" : "", minimum_version: "1.0.0",
+ ready, problem: "", problem_kind: ready ? "" : "not_installed", install_hint: "", job: running,
};
}
@@ -28,45 +38,68 @@ function withData(data: AgentRuntimesResponse, node: ReactNode) {
return render(<QueryClientProvider client={new QueryClient()}>{node}</QueryClientProvider>);
}
-const MIXED: AgentRuntimesResponse = {
- runtimes: [status("hermes", true), status("openclaw", false)] as AgentRuntimesResponse["runtimes"],
- supported_providers: ["openai"],
-};
+function data(...rows: ReturnType<typeof status>[]): AgentRuntimesResponse {
+ return { runtimes: rows as AgentRuntimesResponse["runtimes"], supported_providers: ["openai"] };
+}
afterEach(() => { cleanup(); vi.clearAllMocks(); });
describe("RuntimeChoice", () => {
test("offers the three runtimes and reports the pick", async () => {
const onChange = vi.fn();
- withData(MIXED, <RuntimeChoice value="jarvis" onChange={onChange} />);
+ withData(data(status("hermes", true), status("openclaw", false)), <RuntimeChoice value="jarvis" onChange={onChange} />);
fireEvent.click(await screen.findByRole("radio", { name: "society.runtime.hermes" }));
expect(onChange).toHaveBeenCalledWith("hermes");
expect(screen.getAllByRole("radio")).toHaveLength(3);
+ expect(ensure).not.toHaveBeenCalled();
});
- test("a chosen runtime that is missing offers its installer", async () => {
- setup.mockResolvedValue({});
- withData(MIXED, <RuntimeChoice value="openclaw" onChange={vi.fn()} />);
- fireEvent.click(await screen.findByRole("button", { name: "society.runtime.install" }));
- await waitFor(() => expect(setup).toHaveBeenCalledWith("openclaw", "install"));
+ test("never shows a version number", async () => {
+ withData(data(status("hermes", true), status("openclaw", true)), <RuntimeChoice value="hermes" onChange={vi.fn()} />);
+ expect(await screen.findAllByText("society.runtime.ready")).toHaveLength(2);
+ expect(screen.queryByText(/1\.2\.3/)).toBeNull();
});
-});
-describe("RuntimeStatusRow", () => {
- test("names the runtime and offers an update when it is outdated", async () => {
+ test("picking a runtime that is not set up starts its setup by itself", async () => {
+ ensure.mockResolvedValue(job("openclaw", "running"));
+ withData(data(status("hermes", true), status("openclaw", false)), <RuntimeChoice value="openclaw" onChange={vi.fn()} />);
+ await waitFor(() => expect(ensure).toHaveBeenCalledWith("openclaw"));
+ expect(ensure).toHaveBeenCalledTimes(1);
+ expect(screen.queryByRole("button", { name: /install|update/i })).toBeNull();
+ });
+
+ test("a running setup says so", async () => {
withData(
- {
- runtimes: [status("hermes", false, true), status("openclaw", true)] as AgentRuntimesResponse["runtimes"],
- supported_providers: [],
- },
- <RuntimeStatusRow runtime="hermes" />,
+ data(status("hermes", true), status("openclaw", false, job("openclaw", "running"))),
+ <RuntimeChoice value="openclaw" onChange={vi.fn()} />,
);
- expect(await screen.findByRole("button", { name: "society.runtime.update" })).toBeTruthy();
- expect(screen.getByText(/society\.runtime\.runs_on/)).toBeTruthy();
+ expect(await screen.findByText("society.runtime.setting_up")).toBeTruthy();
+ expect(screen.getByText("society.runtime.setting_up_hint")).toBeTruthy();
+ expect(ensure).not.toHaveBeenCalled();
+ });
+
+ test("a failed setup can be tried again", async () => {
+ ensure.mockResolvedValue(job("openclaw", "running"));
+ withData(
+ data(status("hermes", true), status("openclaw", false, job("openclaw", "failed"))),
+ <RuntimeChoice value="openclaw" onChange={vi.fn()} />,
+ );
+ expect(await screen.findByRole("alert")).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: "society.runtime.retry" }));
+ await waitFor(() => expect(ensure).toHaveBeenCalledWith("openclaw"));
+ });
+});
+
+describe("RuntimeStatusRow", () => {
+ test("names the runtime without a version", async () => {
+ withData(data(status("hermes", true), status("openclaw", true)), <RuntimeStatusRow runtime="hermes" />);
+ expect(await screen.findByText(/society\.runtime\.runs_on/)).toBeTruthy();
+ expect(screen.queryByText(/1\.2\.3/)).toBeNull();
+ expect(screen.queryByRole("button")).toBeNull();
});
test("a Jarvis agent needs no setup", async () => {
- withData(MIXED, <RuntimeStatusRow runtime="jarvis" />);
+ withData(data(status("hermes", true), status("openclaw", false)), <RuntimeStatusRow runtime="jarvis" />);
expect(await screen.findByText(/society\.runtime\.runs_on/)).toBeTruthy();
expect(screen.queryByRole("button")).toBeNull();
});
diff --git a/jarvis/ui/web/frontend/src/components/society/card/RuntimePicker.tsx b/jarvis/ui/web/frontend/src/components/society/card/RuntimePicker.tsx
index 897da1761e..cf902e3fcb 100644
--- a/jarvis/ui/web/frontend/src/components/society/card/RuntimePicker.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/card/RuntimePicker.tsx
@@ -2,26 +2,28 @@
* The agent's runtime: Jarvis (default), Hermes or OpenClaw
* (docs/agent-runtimes.md). It is chosen once, in the create dialog
* (`RuntimeChoice`), and fixed for the agent's life; the model menu only
- * shows it (`RuntimeStatusRow`). Hermes and OpenClaw are installed and
- * updated with their own official tools, only when the person presses the
- * button.
+ * shows it (`RuntimeStatusRow`). Nobody installs Hermes or OpenClaw by hand:
+ * picking one asks the backend to set it up (`ensure`), and Jarvis keeps it
+ * up to date on its own. The UI only says whether it is ready or still being
+ * set up — never a version number.
*/
-import { useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Bot, Loader2 } from "lucide-react";
import { ProviderLogo } from "@/components/providers/ProviderLogo";
import { useT } from "@/i18n";
import {
+ ensureAgentRuntime,
fetchAgentRuntimes,
- startAgentRuntimeSetup,
type AgentRuntimeStatus,
+ type ExternalRuntime,
} from "@/lib/agentRuntimesApi";
import { AGENT_RUNTIMES, type AgentRuntime } from "@/lib/societyApi";
import { cn } from "@/lib/utils";
export const AGENT_RUNTIMES_QUERY_KEY = ["agent-runtimes"] as const;
-/** Status of both external runtimes; polls while an install or update runs. */
+/** Status of both external runtimes; polls while a setup or update runs. */
export function useAgentRuntimes() {
return useQuery({
queryKey: AGENT_RUNTIMES_QUERY_KEY,
@@ -41,91 +43,95 @@ function statusesByName(data: ReturnType<typeof useAgentRuntimes>["data"]) {
return new Map<string, AgentRuntimeStatus>(rows.map((row) => [row.runtime, row]));
}
+type SetupState = "ready" | "setting_up" | "failed" | "pending";
+
+function setupState(status: AgentRuntimeStatus | undefined): SetupState {
+ if (!status) return "pending";
+ if (status.job?.state === "running") return "setting_up";
+ if (status.ready) return "ready";
+ return status.job?.state === "failed" ? "failed" : "pending";
+}
+
function RuntimeMark({ runtime, label }: { runtime: AgentRuntime; label: string }) {
return runtime === "jarvis"
? <Bot className="size-4 shrink-0 text-muted-foreground" aria-hidden />
: <ProviderLogo providerId={runtime} label={label} size="sm" />;
}
-/** Install / update offer for one external runtime that is not ready. */
-function RuntimeSetup({ status }: { status: AgentRuntimeStatus }) {
- const t = useT();
+/** Ask the backend to set a runtime up; refreshes the status either way. */
+function useEnsureRuntime() {
const client = useQueryClient();
const [error, setError] = useState<string | null>(null);
- const job = status.job;
- const running = job?.state === "running";
- // OpenClaw's own installer also adds the Node.js it needs.
- const action: "install" | "update" =
- status.installed && status.problem_kind !== "node" ? "update" : "install";
- const label = t(`society.runtime.${status.runtime}`);
- const problem =
- status.problem_kind === "outdated"
- ? fill(t("society.runtime.needs_update"), label, status.minimum_version)
- : status.problem_kind === "node"
- ? t("society.runtime.node_hint")
- : status.problem_kind === "no_version"
- ? fill(t("society.runtime.no_version"), label)
- : fill(t("society.runtime.not_installed"), label);
-
- async function setup() {
+ const ensure = useCallback(async (runtime: ExternalRuntime) => {
setError(null);
try {
- await startAgentRuntimeSetup(status.runtime, action);
+ await ensureAgentRuntime(runtime);
} catch (exc) {
- setError(fill(t("society.runtime.setup_failed"), exc instanceof Error ? exc.message : String(exc)));
+ setError(exc instanceof Error ? exc.message : String(exc));
}
await client.invalidateQueries({ queryKey: AGENT_RUNTIMES_QUERY_KEY });
- }
+ }, [client]);
+ return { ensure, error };
+}
+/** What a runtime that is not ready yet is doing, and a retry when its setup failed. */
+function RuntimeSetupNote({ status, onRetry, error }: {
+ status: AgentRuntimeStatus | undefined; onRetry: () => void; error: string | null;
+}) {
+ const t = useT();
+ const state = setupState(status);
+ if (state === "ready" || !status) return null;
+ const label = t(`society.runtime.${status.runtime}`);
+ const failure = error ?? (state === "failed" ? status.job?.message || status.job?.log_tail.at(-1) || status.problem : null);
return (
- <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
- <span>{problem}</span>
- <button
- type="button"
- disabled={running}
- onClick={() => void setup()}
- className="inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 text-xs text-foreground hover:bg-secondary disabled:opacity-60"
- >
- {running ? <Loader2 className="size-3 animate-spin" aria-hidden /> : null}
- {running
- ? t(job?.kind === "update" ? "society.runtime.updating" : "society.runtime.installing")
- : t(`society.runtime.${action}`)}
- </button>
- {job?.state === "failed" ? (
- <span role="alert" className="w-full text-destructive">
- {fill(t("society.runtime.setup_failed"), job.message || job.log_tail.at(-1) || "")}
- </span>
- ) : null}
- {running && job?.log_tail.length ? (
- <span className="w-full truncate font-mono text-[11px]">{job.log_tail.at(-1)}</span>
+ <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground" data-testid="runtime-setup">
+ {state === "setting_up" ? <Loader2 className="size-3 animate-spin" aria-hidden /> : null}
+ <span>
+ {fill(t(state === "setting_up" ? "society.runtime.setting_up_hint" : "society.runtime.auto_setup_hint"), label)}
+ </span>
+ {failure ? (
+ <>
+ <span role="alert" className="w-full text-destructive">{fill(t("society.runtime.setup_failed"), failure)}</span>
+ <button
+ type="button"
+ onClick={onRetry}
+ className="rounded-full border border-border px-2 py-0.5 text-xs text-foreground hover:bg-secondary"
+ >
+ {t("society.runtime.retry")}
+ </button>
+ </>
) : null}
- {error ? <span role="alert" className="w-full text-destructive">{error}</span> : null}
</div>
);
}
-/** Whether a runtime can run a turn right now (Jarvis always can). */
-export function runtimeReady(
- runtime: AgentRuntime,
- data: ReturnType<typeof useAgentRuntimes>["data"],
-): boolean {
- return runtime === "jarvis" || Boolean(statusesByName(data).get(runtime)?.ready);
-}
-
-/** The create dialog's choice: three cards, and setup for one that is not ready. */
+/** The create dialog's choice: three cards; picking Hermes or OpenClaw sets it up. */
export function RuntimeChoice({ value, onChange, disabled = false }: {
value: AgentRuntime; onChange: (runtime: AgentRuntime) => void; disabled?: boolean;
}) {
const t = useT();
const runtimes = useAgentRuntimes();
const byName = statusesByName(runtimes.data);
- const chosen = value === "jarvis" ? null : byName.get(value);
+ const { ensure, error } = useEnsureRuntime();
+ const chosen = value === "jarvis" ? undefined : byName.get(value);
+ const chosenState = value === "jarvis" ? "ready" : setupState(chosen);
+
+ const asked = useRef(new Set<string>());
+ const loaded = Boolean(runtimes.data);
+ useEffect(() => {
+ // Picking a runtime starts its setup at once (once per runtime), so it is
+ // usually done by the time the agent gets its first message.
+ if (value === "jarvis" || !loaded || chosenState !== "pending" || asked.current.has(value)) return;
+ asked.current.add(value);
+ void ensure(value);
+ }, [value, loaded, chosenState, ensure]);
+
return (
<div className="flex flex-col gap-2" data-testid="runtime-choice">
<div className="grid grid-cols-3 gap-2" role="radiogroup" aria-label={t("society.runtime.title")}>
{AGENT_RUNTIMES.map((runtime) => {
- const status = runtime === "jarvis" ? null : byName.get(runtime);
const label = t(`society.runtime.${runtime}`);
+ const state = runtime === "jarvis" ? null : setupState(byName.get(runtime));
return (
<button
key={runtime}
@@ -146,37 +152,46 @@ export function RuntimeChoice({ value, onChange, disabled = false }: {
<RuntimeMark runtime={runtime} label={label} />
{label}
</span>
- <span className="text-[11px] leading-snug">
- {status
- ? status.ready
- ? fill(t("society.runtime.version"), status.version)
- : t(status.installed ? "society.runtime.needs_setup" : "society.runtime.not_installed_short")
- : t("society.runtime.built_in")}
+ <span className="inline-flex items-center gap-1 text-[11px] leading-snug">
+ {state === "setting_up" ? <Loader2 className="size-3 animate-spin" aria-hidden /> : null}
+ {t(
+ state === null
+ ? "society.runtime.built_in"
+ : state === "ready"
+ ? "society.runtime.ready"
+ : state === "setting_up"
+ ? "society.runtime.setting_up"
+ : "society.runtime.auto_setup",
+ )}
</span>
</button>
);
})}
</div>
<p className="text-xs text-muted-foreground">{t(`society.runtime.${value}_hint`)}</p>
- {chosen && !chosen.ready ? <RuntimeSetup status={chosen} /> : null}
+ {value !== "jarvis" ? (
+ <RuntimeSetupNote status={chosen} error={error} onRetry={() => void ensure(value)} />
+ ) : null}
</div>
);
}
-/** The model menu's line: the runtime the agent runs on, and its update when needed. */
+/** The model menu's line: the runtime the agent runs on, and its setup while one runs. */
export function RuntimeStatusRow({ runtime }: { runtime: AgentRuntime }) {
const t = useT();
const runtimes = useAgentRuntimes();
- const status = runtime === "jarvis" ? null : statusesByName(runtimes.data).get(runtime);
+ const { ensure, error } = useEnsureRuntime();
+ const status = runtime === "jarvis" ? undefined : statusesByName(runtimes.data).get(runtime);
const label = t(`society.runtime.${runtime}`);
return (
<div className="flex flex-col gap-1.5" data-testid="runtime-status">
<span className="inline-flex items-center gap-1.5 text-xs text-muted-foreground">
<RuntimeMark runtime={runtime} label={label} />
{fill(t("society.runtime.runs_on"), label)}
- {status?.version ? ` · ${fill(t("society.runtime.version"), status.version)}` : ""}
</span>
- {status && !status.ready ? <RuntimeSetup status={status} /> : null}
+ {runtime !== "jarvis" ? (
+ <RuntimeSetupNote status={status} error={error} onRetry={() => void ensure(runtime)} />
+ ) : null}
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
index b531e1c12f..f8084039f5 100644
--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
@@ -779,6 +779,12 @@ function NoticeLine({ item }: { item: NoticeItem }) {
if (item.kind === "context_rollover") {
return <p className="py-1 text-center text-[11px] text-muted-foreground">{t("society.chat.context_rollover")}</p>;
}
+ if (item.kind === "runtime_setup") {
+ const runtime = String(item.data.runtime ?? "");
+ return <p className="py-1 text-center text-[11px] text-muted-foreground" data-testid="runtime-setup-notice">
+ {runtime ? t("society.runtime.setting_up_chat").replace("{0}", t(`society.runtime.${runtime}`)) : item.text}
+ </p>;
+ }
if (item.kind === "routine_run") {
const sessionId = String(item.data.session_id ?? "");
const agentId = item.agentId || String(item.data.agent_id ?? "");
diff --git a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.test.tsx b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.test.tsx
index f01a034647..fb34df4a9a 100644
--- a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.test.tsx
@@ -9,8 +9,9 @@ vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));
vi.mock("../companion/CompanionEditor", () => ({
CompanionEditor: ({ value }: { value: { shape: string } }) => <div data-testid="companion-editor">{value.shape}</div>,
}));
-const { createAgent, runtimes } = vi.hoisted(() => ({
+const { createAgent, ensureRuntime, runtimes } = vi.hoisted(() => ({
createAgent: vi.fn(),
+ ensureRuntime: vi.fn(),
runtimes: { value: null as unknown },
}));
vi.mock("../data", async () => {
@@ -19,7 +20,7 @@ vi.mock("../data", async () => {
});
vi.mock("@/lib/agentRuntimesApi", () => ({
fetchAgentRuntimes: () => Promise.resolve(runtimes.value),
- startAgentRuntimeSetup: vi.fn(),
+ ensureAgentRuntime: ensureRuntime,
}));
const READY: AgentRuntimesResponse = {
@@ -76,13 +77,18 @@ describe("CreateAgentDialog", () => {
expect(screen.queryByTestId("create-agent-provider")).toBeNull();
});
- test("a runtime that is not installed cannot be created yet", async () => {
+ test("a runtime that is not installed yet sets itself up and can be created right away", async () => {
+ ensureRuntime.mockResolvedValue(null);
+ createAgent.mockResolvedValue({ agentId: "agent-3" });
mount();
act(() => { useCreateAgentDialog.getState().request().catch(() => undefined); });
fireEvent.click(await screen.findByRole("radio", { name: "society.runtime.openclaw" }));
+ await waitFor(() => expect(ensureRuntime).toHaveBeenCalledWith("openclaw"));
const submit = screen.getByTestId("create-agent-submit") as HTMLButtonElement;
- await waitFor(() => expect(submit.disabled).toBe(true));
- expect(screen.getByRole("button", { name: "society.runtime.install" })).toBeTruthy();
+ await waitFor(() => expect(submit.disabled).toBe(false));
+ fireEvent.click(submit);
+ await waitFor(() => expect(createAgent).toHaveBeenCalled());
+ expect(createAgent.mock.calls[0][0]).toMatchObject({ runtime: "openclaw", provider: "openai" });
});
test("closing the dialog cancels the request quietly", async () => {
diff --git a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx
index 2cf3314cfe..4c87432e68 100644
--- a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx
@@ -16,7 +16,7 @@ import { useT } from "@/i18n";
import type { AgentRuntime } from "@/lib/societyApi";
import { AgentNameTaken, useCreateSocietyAgent } from "../data";
import { defaultCompanion, type CompanionAppearance } from "../companion/appearance";
-import { RuntimeChoice, runtimeReady, useAgentRuntimes } from "../card/RuntimePicker";
+import { RuntimeChoice, useAgentRuntimes } from "../card/RuntimePicker";
import { useCreateAgentDialog } from "./createAgentStore";
const CompanionEditor = lazy(() =>
@@ -67,9 +67,10 @@ function CreateAgentDialog() {
if (external && !providers.includes(provider)) setProvider(providers[0] ?? "");
}, [external, providers, provider]);
- const ready = runtimeReady(runtime, runtimes.data);
+ // A runtime still being set up does not hold creation back: the agent's
+ // first turn waits for the setup (agent_runtimes.manager).
const needsProvider = external && !provider;
- const canCreate = !saving && ready && !needsProvider;
+ const canCreate = !saving && !needsProvider;
async function submit() {
if (!canCreate) return;
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index e54150b9a8..26690d9f24 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -5696,8 +5696,9 @@
},
"runtime": {
"built_in": "Eingebaut",
- "needs_setup": "Braucht ein Update",
- "not_installed_short": "Nicht installiert",
+ "ready": "Bereit",
+ "auto_setup": "Richtet sich selbst ein",
+ "setting_up": "Wird eingerichtet …",
"runs_on": "Läuft auf {0}",
"title": "Laufzeit",
"jarvis": "Jarvis",
@@ -5706,16 +5707,11 @@
"jarvis_hint": "Jarvis' eigene Agenten-Schleife, auf dem Modell, das du im Chat wählst.",
"hermes_hint": "Der Hermes-Agent mit seinen eigenen Werkzeugen – dazu Gedächtnis, Skills und Werkzeuge aus Jarvis.",
"openclaw_hint": "Der OpenClaw-Agent mit seinen eigenen Werkzeugen – dazu Gedächtnis, Skills und Werkzeuge aus Jarvis.",
- "install": "Installieren",
- "update": "Aktualisieren",
- "installing": "Wird installiert …",
- "updating": "Wird aktualisiert …",
- "version": "Version {0}",
- "not_installed": "{0} ist auf diesem Computer nicht installiert.",
- "needs_update": "{0} {1} oder neuer wird gebraucht.",
+ "setting_up_hint": "{0} wird gerade auf diesem Computer eingerichtet. Du kannst den Agenten schon anlegen; er antwortet, sobald die Einrichtung fertig ist.",
+ "auto_setup_hint": "Jarvis installiert {0} selbst und hält es aktuell.",
"setup_failed": "Einrichtung nicht abgeschlossen: {0}",
- "node_hint": "OpenClaw braucht Node.js 24.16 oder neuer. Sein Installer richtet eines nur für OpenClaw ein.",
- "no_version": "{0} ist installiert, meldet aber keine Version. Installiere es neu."
+ "setting_up_chat": "{0} wird auf diesem Computer eingerichtet. Beim ersten Mal dauert das ein paar Minuten; deine Nachricht wird beantwortet, sobald alles bereit ist.",
+ "retry": "Erneut versuchen"
},
"approval_mode": {
"title": "Agentenberechtigungen",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 45ec25bd4a..68209290d3 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -5696,8 +5696,9 @@
},
"runtime": {
"built_in": "Built in",
- "needs_setup": "Needs an update",
- "not_installed_short": "Not installed",
+ "ready": "Ready",
+ "auto_setup": "Sets itself up",
+ "setting_up": "Setting up…",
"runs_on": "Runs on {0}",
"title": "Runtime",
"jarvis": "Jarvis",
@@ -5706,16 +5707,11 @@
"jarvis_hint": "Jarvis' own agent loop, on the model you pick in its chat.",
"hermes_hint": "The Hermes agent with its own tools — plus this agent's Jarvis memory, skills and tools.",
"openclaw_hint": "The OpenClaw agent with its own tools — plus this agent's Jarvis memory, skills and tools.",
- "install": "Install",
- "update": "Update",
- "installing": "Installing…",
- "updating": "Updating…",
- "version": "Version {0}",
- "not_installed": "{0} is not installed on this computer.",
- "needs_update": "{0} {1} or newer is needed.",
+ "setting_up_hint": "{0} is being set up on this computer. You can create the agent now; it answers as soon as the setup is done.",
+ "auto_setup_hint": "Jarvis installs {0} by itself and keeps it up to date.",
"setup_failed": "Setup did not finish: {0}",
- "node_hint": "OpenClaw needs Node.js 24.16 or newer. Its installer adds one for OpenClaw only.",
- "no_version": "{0} is installed but did not report its version. Reinstall it."
+ "setting_up_chat": "Setting up {0} on this computer. The first time takes a few minutes; your message is answered as soon as it is ready.",
+ "retry": "Try again"
},
"approval_mode": {
"title": "Agent permissions",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 847893c749..b9b5807760 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -5696,8 +5696,9 @@
},
"runtime": {
"built_in": "Integrado",
- "needs_setup": "Necesita una actualización",
- "not_installed_short": "No instalado",
+ "ready": "Listo",
+ "auto_setup": "Se configura solo",
+ "setting_up": "Configurando…",
"runs_on": "Funciona con {0}",
"title": "Motor",
"jarvis": "Jarvis",
@@ -5706,16 +5707,11 @@
"jarvis_hint": "El bucle de agente propio de Jarvis, con el modelo que elijas en su chat.",
"hermes_hint": "El agente Hermes con sus propias herramientas, más la memoria, las habilidades y las herramientas de Jarvis.",
"openclaw_hint": "El agente OpenClaw con sus propias herramientas, más la memoria, las habilidades y las herramientas de Jarvis.",
- "install": "Instalar",
- "update": "Actualizar",
- "installing": "Instalando…",
- "updating": "Actualizando…",
- "version": "Versión {0}",
- "not_installed": "{0} no está instalado en este equipo.",
- "needs_update": "Se necesita {0} {1} o posterior.",
+ "setting_up_hint": "{0} se está configurando en este equipo. Ya puedes crear el agente; responderá en cuanto termine la configuración.",
+ "auto_setup_hint": "Jarvis instala {0} por sí mismo y lo mantiene actualizado.",
"setup_failed": "La instalación no terminó: {0}",
- "node_hint": "OpenClaw necesita Node.js 24.16 o posterior. Su instalador añade uno solo para OpenClaw.",
- "no_version": "{0} está instalado pero no indica su versión. Vuelve a instalarlo."
+ "setting_up_chat": "Configurando {0} en este equipo. La primera vez tarda unos minutos; tu mensaje se responde en cuanto esté listo.",
+ "retry": "Reintentar"
},
"approval_mode": {
"title": "Permisos del agente",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.json
index b2ef192ac6..4361716ce8 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json
@@ -5676,6 +5676,41 @@
"monitor": "监控",
"ask": "先询问"
},
+ "create_agent": {
+ "title": "新建智能体",
+ "subtitle": "给它起个名字,选择它的运行方式,再挑一个小伙伴。",
+ "name_label": "名称",
+ "name_placeholder": "留空则由智能体自己取名",
+ "type_label": "智能体类型",
+ "type_fixed": "智能体创建后类型不可更改。",
+ "provider_label": "模型提供方",
+ "provider_hint": "Hermes 和 OpenClaw 使用 API 密钥或本地模型运行。之后可以在聊天中更换模型。",
+ "no_provider": "尚未连接 API 密钥或本地模型。请在 设置 → API 密钥 中添加。",
+ "companion_label": "小伙伴",
+ "cancel": "取消",
+ "create": "创建智能体",
+ "creating": "正在创建…",
+ "name_taken": "已存在同名的智能体。"
+ },
+ "runtime": {
+ "built_in": "内置",
+ "ready": "就绪",
+ "auto_setup": "自动安装",
+ "setting_up": "正在安装…",
+ "runs_on": "运行于 {0}",
+ "title": "运行时",
+ "jarvis": "Jarvis",
+ "hermes": "Hermes",
+ "openclaw": "OpenClaw",
+ "jarvis_hint": "Jarvis 自己的智能体循环,使用你在聊天中选择的模型。",
+ "hermes_hint": "带有自身工具的 Hermes 智能体,并配有该智能体在 Jarvis 中的记忆、技能和工具。",
+ "openclaw_hint": "带有自身工具的 OpenClaw 智能体,并配有该智能体在 Jarvis 中的记忆、技能和工具。",
+ "setting_up_hint": "正在这台电脑上安装 {0}。你现在就可以创建智能体,安装完成后它就会回复。",
+ "auto_setup_hint": "Jarvis 会自动安装 {0} 并保持更新。",
+ "setup_failed": "安装未完成:{0}",
+ "setting_up_chat": "正在这台电脑上安装 {0}。第一次需要几分钟,准备好后会立即回复你的消息。",
+ "retry": "重试"
+ },
"approval_mode": {
"title": "智能体权限",
"bypass": "跳过权限确认",
diff --git a/jarvis/ui/web/frontend/src/lib/agentRuntimesApi.ts b/jarvis/ui/web/frontend/src/lib/agentRuntimesApi.ts
index 73aeae0749..f28bb16cfc 100644
--- a/jarvis/ui/web/frontend/src/lib/agentRuntimesApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agentRuntimesApi.ts
@@ -56,12 +56,10 @@ export function fetchAgentRuntimes(refresh = false): Promise<AgentRuntimesRespon
return json<AgentRuntimesResponse>(`/api/agent-runtimes${refresh ? "?refresh=true" : ""}`);
}
-export async function startAgentRuntimeSetup(
- runtime: ExternalRuntime,
- action: "install" | "update",
-): Promise<AgentRuntimeJob> {
- const body = await json<{ job: AgentRuntimeJob }>(
- `/api/agent-runtimes/${encodeURIComponent(runtime)}/${action}`,
+/** Install or update the runtime when it needs it (`null` when it is ready). */
+export async function ensureAgentRuntime(runtime: ExternalRuntime): Promise<AgentRuntimeJob | null> {
+ const body = await json<{ job: AgentRuntimeJob | null }>(
+ `/api/agent-runtimes/${encodeURIComponent(runtime)}/ensure`,
{ method: "POST" },
);
return body.job;
diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.py
index 5ef40b5e00..a4d28c858b 100644
--- a/jarvis/ui/web/society_routes.py
+++ b/jarvis/ui/web/society_routes.py
@@ -376,6 +376,15 @@ async def create_agent(body: CreateAgentBody, request: Request) -> dict[str, Any
if created and progression is not None:
# Growing the team levels the person up (jarvis/progression).
await progression.note_agent_hired(agent.agent_id)
+ if created and str(agent.runtime) not in ("", "jarvis"):
+ # Hermes / OpenClaw install or update themselves in the background;
+ # the agent's first turn waits for that (runner_acp._ready).
+ from jarvis.agent_runtimes import manager
+
+ try:
+ await manager.ensure(str(agent.runtime))
+ except Exception: # noqa: BLE001 — the agent exists; its first turn retries the setup
+ log.warning("society: %s setup could not start", agent.runtime, exc_info=True)
return {
"agent": agent.to_dict(),
"created": created,
diff --git a/tests/unit/agent_runtimes/test_runtime_manager.py b/tests/unit/agent_runtimes/test_runtime_manager.py
index e442b0303d..02932c479f 100644
--- a/tests/unit/agent_runtimes/test_runtime_manager.py
+++ b/tests/unit/agent_runtimes/test_runtime_manager.py
@@ -19,25 +19,62 @@ from jarvis.ui.web.agent_runtime_routes import router
class FakeDriver:
- def __init__(self, name: str, *, exit_code: int = 0) -> None:
+ """A runtime whose readiness is a marker file its scripted installer writes.
+
+ ``ready`` / ``installed`` describe it before any job. An install always
+ writes the marker (ready afterwards); an update only when ``update_fixes``.
+ """
+
+ def __init__(
+ self,
+ name: str,
+ *,
+ exit_code: int = 0,
+ ready: bool = True,
+ installed: bool = True,
+ update_fixes: bool = True,
+ marker: Path | None = None,
+ ) -> None:
self.name = name
self.label = name.title()
self.exit_code = exit_code
+ self.ready = ready
+ self.installed = installed
+ self.update_fixes = update_fixes
+ self.marker = marker
self.stopped = 0
self.refreshed = 0
+ self.is_busy = False
def detect(self, *, refresh: bool = False) -> RuntimeStatus:
self.refreshed += int(refresh)
- return RuntimeStatus(self.name, self.label, installed=True, version="1.0.0", ready=True)
-
- def _script(self, word: str) -> list[str]:
- return [sys.executable, "-c", f"print('{word}'); raise SystemExit({self.exit_code})"]
+ fixed = self.marker is not None and self.marker.exists()
+ ready = self.ready or fixed
+ installed = self.installed or fixed
+ kind = "" if ready else ("outdated" if installed else "not_installed")
+ return RuntimeStatus(
+ self.name,
+ self.label,
+ installed=installed,
+ version="1.0.0",
+ ready=ready,
+ problem="" if ready else "not ready",
+ problem_kind=kind,
+ )
+
+ def _script(self, word: str, fixes: bool) -> list[str]:
+ write = f"open({str(self.marker)!r}, 'w').close(); " if fixes and self.marker else ""
+ code = f"print('{word}'); {write}raise SystemExit({self.exit_code})"
+ return [sys.executable, "-c", code]
def install_command(self) -> list[str]:
- return self._script("installing")
+ return self._script("installing", True)
def update_command(self) -> list[str]:
- return self._script("updating")
+ return self._script("updating", self.update_fixes)
+
+ def busy(self) -> bool:
+ return self.is_busy
async def stop(self, agent_id: str | None = None) -> None:
self.stopped += 1
@@ -49,6 +86,23 @@ def fakes(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
drivers = {"hermes": FakeDriver("hermes"), "openclaw": FakeDriver("openclaw", exit_code=3)}
monkeypatch.setattr(runtimes, "_DRIVERS", drivers)
monkeypatch.setattr(manager, "_JOBS", {})
+ monkeypatch.setattr(manager, "_TASKS", {})
+ return drivers
+
+
+def unset(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """Runtimes that are not set up yet: Hermes missing, OpenClaw outdated."""
+ monkeypatch.setattr(base, "runtimes_root", lambda: tmp_path)
+ drivers = {
+ "hermes": FakeDriver("hermes", ready=False, installed=False, marker=tmp_path / "h.ok"),
+ "openclaw": FakeDriver(
+ "openclaw", ready=False, update_fixes=False, marker=tmp_path / "o.ok"
+ ),
+ }
+ monkeypatch.setattr(runtimes, "_DRIVERS", drivers)
+ monkeypatch.setattr(manager, "_JOBS", {})
+ monkeypatch.setattr(manager, "_TASKS", {})
return drivers
@@ -111,3 +165,88 @@ def test_routes_list_status_and_start_jobs(fakes):
job = client.post("/api/agent-runtimes/hermes/install").json()["job"]
assert job["kind"] == "install" and job["runtime"] == "hermes"
assert client.get("/api/agent-runtimes/hermes/job").json()["job"]["kind"] == "install"
+
+
+async def test_ensure_leaves_a_ready_runtime_alone(fakes):
+ assert await manager.ensure("hermes") is None
+ assert manager.job("hermes") is None
+
+
+async def test_ensure_installs_a_missing_runtime_and_a_turn_waits_for_it(unset):
+ started = await manager.ensure("hermes")
+ assert started is not None and started.kind == "install"
+ assert await manager.ensure("hermes") is started # a second pick joins the job
+ status = await manager.wait_ready("hermes", timeout_s=30)
+ assert status.ready
+ assert manager.job("hermes").state == "done"
+
+
+async def test_an_update_that_leaves_the_runtime_broken_is_repaired_by_an_install(unset):
+ started = await manager.ensure("openclaw")
+ assert started is not None and started.kind == "update"
+ status = await manager.wait_ready("openclaw", timeout_s=30)
+ assert status.ready
+ repair = manager.job("openclaw")
+ assert repair.kind == "install" and repair.state == "done"
+ assert unset["openclaw"].stopped == 1
+
+
+async def test_the_daily_update_waits_while_a_turn_runs(fakes):
+ fakes["hermes"].is_busy = True
+ await manager._update_when_idle("hermes")
+ assert manager.job("hermes") is None
+ fakes["hermes"].is_busy = False
+ await manager._update_when_idle("hermes")
+ assert manager.job("hermes").kind == "update"
+ assert manager.job("hermes").state == "done"
+
+
+async def test_the_daily_round_updates_only_runtimes_an_agent_uses(fakes, monkeypatch):
+ monkeypatch.setattr(manager, "_FIRST_UPDATE_DELAY_S", 0)
+ rounds: list[int] = []
+
+ async def in_use() -> set[str]:
+ rounds.append(1)
+ return {"hermes"}
+
+ task = asyncio.create_task(manager.keep_current(in_use))
+ try:
+ for _ in range(200):
+ current = manager.job("hermes")
+ if current is not None and current.state != "running":
+ break
+ await asyncio.sleep(0.05)
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert rounds == [1]
+ assert manager.job("hermes").kind == "update"
+ assert manager.job("openclaw") is None
+
+
+def test_the_ensure_route_starts_what_is_needed(unset):
+ app = FastAPI()
+ app.include_router(router)
+ body = TestClient(app).post("/api/agent-runtimes/hermes/ensure").json()
+ assert body["job"]["kind"] == "install"
+
+
+def test_a_claude_login_in_the_api_key_slot_is_not_offered(fakes):
+ import jarvis.ui.web.agent_runtime_routes as routes
+ from jarvis.agent_runtimes.model_map import RouteUnavailable, route_for
+
+ config = SimpleNamespace(brain=SimpleNamespace(providers={}))
+ routes._USABLE_CACHE[:] = [float("-inf"), []]
+ app = FastAPI()
+ app.include_router(router)
+ app.state.config = config
+ login = "sk-ant-" + "oat01-" + "x" * 20
+ with override_provider_secrets(
+ {"openai": None, "claude-api": login, "openrouter": None, "grok": None,
+ "nvidia": None, "gemini": None}
+ ):
+ body = TestClient(app).get("/api/agent-runtimes").json()
+ with pytest.raises(RouteUnavailable, match="subscription login"):
+ route_for(config, "claude-api", "claude-sonnet-5-5")
+ assert "claude-api" not in body["supported_providers"]
diff --git a/tests/unit/agent_runtimes/test_runtime_setup_turn.py b/tests/unit/agent_runtimes/test_runtime_setup_turn.py
new file mode 100644
index 0000000000..ca05ed396e
--- /dev/null
+++ b/tests/unit/agent_runtimes/test_runtime_setup_turn.py
@@ -0,0 +1,78 @@
+"""A turn on a runtime that is not set up yet waits for the setup and says so."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from jarvis.agent_chat import runner_acp
+from jarvis.agent_chat.runner_cli import CliUnavailable
+from jarvis.agent_runtimes import manager
+from jarvis.agent_runtimes.base import RuntimeStatus
+
+
+class Handle:
+ turn_id = "turn-1"
+
+ def __init__(self) -> None:
+ self.events: list[dict[str, Any]] = []
+
+ async def emit(self, event: dict[str, Any]) -> None:
+ self.events.append(event)
+
+
+class Driver:
+ label = "Hermes"
+
+ def __init__(self, ready: bool) -> None:
+ self.ready = ready
+
+ def detect(self, *, refresh: bool = False) -> RuntimeStatus:
+ return RuntimeStatus("hermes", "Hermes", installed=self.ready, ready=self.ready)
+
+
[email protected](autouse=True)
+def no_jobs(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(manager, "_JOBS", {})
+ monkeypatch.setattr(manager, "_TASKS", {})
+
+
+async def test_a_ready_runtime_starts_at_once(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def never(*_args: Any, **_kwargs: Any) -> RuntimeStatus:
+ raise AssertionError("a ready runtime needs no setup")
+
+ monkeypatch.setattr(manager, "wait_ready", never)
+ handle = Handle()
+ await runner_acp._ready(handle, "hermes", Driver(ready=True))
+ assert handle.events == []
+
+
+async def test_a_missing_runtime_is_set_up_first(monkeypatch: pytest.MonkeyPatch) -> None:
+ driver = Driver(ready=False)
+
+ async def install(name: str, **_kwargs: Any) -> RuntimeStatus:
+ assert name == "hermes"
+ driver.ready = True
+ return driver.detect()
+
+ monkeypatch.setattr(manager, "wait_ready", install)
+ handle = Handle()
+ await runner_acp._ready(handle, "hermes", driver)
+ assert [event["kind"] for event in handle.events] == ["notice"]
+ assert "Setting up Hermes" in handle.events[0]["payload"]["text"]
+
+
+async def test_a_setup_that_fails_ends_the_turn_with_its_reason(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ driver = Driver(ready=False)
+
+ async def fail(name: str, **_kwargs: Any) -> RuntimeStatus:
+ failed = manager.RuntimeJob(name, "install", state="failed", message="no network")
+ manager._JOBS[name] = failed
+ return driver.detect()
+
+ monkeypatch.setattr(manager, "wait_ready", fail)
+ with pytest.raises(CliUnavailable, match="no network"):
+ await runner_acp._ready(Handle(), "hermes", driver)