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-chat): the Jarvis surface runs on the brain runner — Jarvis' own harness with a per-chat pick

rubenluetke10-beepd06b9c7d3c20
diff --git a/jarvis/agent_chat/__init__.py b/jarvis/agent_chat/__init__.py
index 51a899a93a..c3a49d8298 100644
--- a/jarvis/agent_chat/__init__.py
+++ b/jarvis/agent_chat/__init__.py
@@ -1,11 +1,21 @@
-"""Agent chat — the typed front-page chat as an agent session.
+"""Agent chat — the typed chat: Jarvis with a keyboard, and the IDE's coding sessions.
-The chat surface of the front page used to be a second mouth for the voice
-brain: typed text went down the same ``MessageSent`` path the microphone
-uses and the router brain answered. Since 2026-08-23 it is its own thing —
-a coding-agent session in the Claude Code shape, run on whichever
-*agent-tier* provider and model the person picks in the composer, with the
-reasoning effort dialled by hand:
+One package, two surfaces (``store.SURFACES``):
+
+* ``"jarvis"`` — the front page's chat. What you type is input to Jarvis:
+ the same assistant the microphone talks to, on the model the composer
+ picked for THIS chat (:mod:`.runner_brain` — ``BrainManager.generate``
+ with a per-turn override; the live voice brain is never switched). A
+ subscription CLI seat (Claude Code, Codex, …) runs as Jarvis through
+ :mod:`.runner_cli` + :mod:`.jarvis_harness`, so the subscription pays.
+ The folder chip is Jarvis' working folder (:mod:`.folder_tools`), and the
+ one permission ladder — Ask / Auto-accept edits / Bypass, plus Plan —
+ decides what asks through a clickable card (:mod:`.approval_bridge`).
+* ``"agent"`` — a plain coding-agent session in a folder, the Claude Code
+ shape, which the Agentic IDE's chat mode runs: a vendor CLI or the API tool
+ loop, with the vendor's own permission ladder.
+
+The pieces:
* :mod:`.effort` — which effort levels each provider family offers and how
a picked level maps onto what a provider actually accepts;
@@ -16,9 +26,12 @@ reasoning effort dialled by hand:
* :mod:`.events` — the one event vocabulary both the store and the live
stream speak;
* :mod:`.store` — SQLite persistence for sessions and their event log;
-* :mod:`.runner_api` / :mod:`.runner_cli` — the two ways a turn runs: the
- provider's own chat API in a tool loop, or a vendor CLI (``claude``,
- ``codex``, ``agy``, ``grok``) driven non-interactively;
+* :mod:`.runner_api` / :mod:`.runner_cli` / :mod:`.runner_brain` — the
+ three ways a turn runs: the provider's own chat API in a coding-agent tool
+ loop, a vendor CLI (``claude``, ``codex``, ``agy``, ``grok``) driven
+ non-interactively, or Jarvis' own brain;
+* :mod:`.folder_tools` / :mod:`.approval_bridge` — the Jarvis surface's
+ hands in the folder and the card that answers the executor's ticket;
* :mod:`.service` — sessions in flight, subscribers, cancel and approvals.
The voice path is untouched: nothing here subscribes to the event bus, and
diff --git a/jarvis/agent_chat/runner_api.py b/jarvis/agent_chat/runner_api.py
index e7eec55328..5fe0474134 100644
--- a/jarvis/agent_chat/runner_api.py
+++ b/jarvis/agent_chat/runner_api.py
@@ -130,7 +130,14 @@ def system_prompt(*, cwd: Path, assistant_name: str, plan: bool = False) -> str:
@dataclass(slots=True)
class TurnHandle:
- """What the service hands a runner: where to emit, how to ask, when to stop."""
+ """What the service hands a runner: where to emit, how to ask, when to stop.
+
+ ``trace_id`` is the turn's correlation id on the app bus (the brain runner
+ passes it to ``generate`` and reads its own tool events back by it);
+ ``bus`` is the app bus, ``None`` when the service runs without one;
+ ``surface`` and ``stance`` are the session's chat and, on the Jarvis
+ surface, its permission stance (``jarvis.agent_chat.permissions``).
+ """
session: AgentChatSession
turn_id: str
@@ -139,6 +146,10 @@ class TurnHandle:
cancel: asyncio.Event
history: list[dict[str, Any]] = field(default_factory=list)
assistant_name: str = "Jarvis"
+ trace_id: uuid.UUID = field(default_factory=uuid.uuid4)
+ bus: Any | None = None
+ surface: str = "agent"
+ stance: str = ""
# ------------------------------------------------------------ history
diff --git a/jarvis/agent_chat/runner_brain.py b/jarvis/agent_chat/runner_brain.py
new file mode 100644
index 0000000000..dad77f6795
--- /dev/null
+++ b/jarvis/agent_chat/runner_brain.py
@@ -0,0 +1,518 @@
+"""The Jarvis surface's runner: Jarvis' own brain, driven by text.
+
+This is what the front page's chat runs on for an API-key or local seat. A
+typed turn is the same turn a spoken one is — ``BrainManager.generate`` with
+its router, its tools, its memory, its wiki and its safety tiers — with the
+keyboard in place of the microphone. Nothing here spawns a coding CLI or a
+second agent loop; there is one assistant in this app and this is how you
+type at it (maintainer, 2026-08-25).
+
+What the composer's pick changes is which model Jarvis thinks with FOR THIS
+CHAT, and how hard: provider, model and effort travel as a
+:class:`jarvis.brain.turn_override.TurnOverride` on the one ``generate``
+call, and nothing else. The live brain the voice runs on — its active
+provider, its config, its dead-lists — is never touched; the first version
+of this runner (2026-08-24) switched it and was reverted for exactly that.
+
+The chat's folder is Jarvis' working folder for the turn: the folder tools
+(:mod:`jarvis.agent_chat.folder_tools`) join Jarvis' own tools on the turn's
+surface, every call goes through ``ToolExecutor``, and the chat's permission
+stance decides what asks — through a clickable card, not a spoken "yes"
+(:mod:`jarvis.agent_chat.approval_bridge`).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import time
+import uuid
+from collections.abc import Callable
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Final, get_args
+
+from jarvis.agent_chat.approval_bridge import ChatApprovalBridge, ChatGrant, approval_ref
+from jarvis.agent_chat.effort import normalize_effort
+from jarvis.agent_chat.events import make_event
+from jarvis.agent_chat.folder_tools import PLAN_STANCE, folder_tools, plan_filter
+from jarvis.agent_chat.runner_api import messages_from_events
+from jarvis.agent_chat.tools import summarize_call
+from jarvis.brain.turn_override import TurnOverride
+from jarvis.core.protocols import BrainMessage, ReasoningEffort
+
+if TYPE_CHECKING:
+ from uuid import UUID
+
+ from jarvis.agent_chat.runner_api import TurnHandle
+ from jarvis.agent_chat.store import AgentChatSession
+
+log = logging.getLogger(__name__)
+
+#: The runner id this module answers to, in the catalog and in ``turn_started``.
+RUNNER: Final[str] = "brain"
+
+#: ``MessageSent.source_layer`` for a turn typed into the chat surface. The
+#: brain's router reads it; it is a conversational layer, so the router may
+#: still spawn a worker on an explicit request (``_NON_SPAWN_SOURCE_LAYERS``
+#: does not list it — typing at Jarvis is not a background channel).
+SOURCE_LAYER: Final[str] = "ui.chat.typed"
+
+#: How long a card may stay open. A person reading a chat is not on a spoken
+#: turn's clock; the executor clamps this to its own ceiling.
+APPROVAL_TIMEOUT_S: Final[float] = 600.0
+
+#: The tool-loop ceiling of a chat turn — the API runner's own round budget.
+MAX_TURNS: Final[int] = 40
+
+#: How much of the chat's own log rides along as history.
+_HISTORY_MAX: Final[int] = 40
+
+_EFFORTS: Final[frozenset[str]] = frozenset(get_args(ReasoningEffort))
+
+
+def brain_manager() -> Any | None:
+ """The live BrainManager, or ``None`` before the brain finished building."""
+ from jarvis.core import runtime_refs
+
+ return runtime_refs.get_brain_manager()
+
+
+# ------------------------------------------------------------------ history
+
+
+def brain_history_from_events(events: list[dict[str, Any]]) -> list[BrainMessage]:
+ """The chat's own log as the turn's history: what was said, in prose.
+
+ User and assistant TEXT only. A tool round is folded into the assistant
+ message as one line per call ("[used tool X: …]") and its results are
+ dropped: Jarvis' loop rebuilds its own tool rounds, and replaying a
+ foreign provider's ``tool_use`` ids into a different provider fails its
+ validation. Capped to the last ``_HISTORY_MAX`` messages.
+ """
+ out: list[BrainMessage] = []
+ for message in messages_from_events(events):
+ if message.role == "user":
+ text = message.content if isinstance(message.content, str) else ""
+ if text.strip():
+ out.append(BrainMessage(role="user", content=text))
+ elif message.role == "assistant":
+ text = _assistant_prose(message.content)
+ if not text.strip():
+ continue
+ if out and out[-1].role == "assistant":
+ # One answer per turn: the tool round and the prose after it
+ # are two provider messages but one thing Jarvis said.
+ merged = f"{out[-1].content}\n{text}"
+ out[-1] = BrainMessage(role="assistant", content=merged)
+ else:
+ out.append(BrainMessage(role="assistant", content=text))
+ return out[-_HISTORY_MAX:]
+
+
+def _assistant_prose(content: str | list[dict[str, Any]]) -> str:
+ if isinstance(content, str):
+ return content
+ lines: list[str] = []
+ for block in content:
+ kind = block.get("type")
+ if kind == "text":
+ text = str(block.get("text") or "")
+ if text.strip():
+ lines.append(text)
+ elif kind == "tool_use":
+ name = str(block.get("name") or "tool")
+ args = block.get("input") or {}
+ summary = summarize_call(name, args) if isinstance(args, dict) else ""
+ lines.append(f"[used tool {name}: {summary}]" if summary else f"[used tool {name}]")
+ return "\n".join(lines)
+
+
+# ----------------------------------------------------------------- override
+
+
+def build_override(
+ session: AgentChatSession,
+ brain: Any,
+ *,
+ stance: str,
+ cwd: Path,
+ ref: str,
+) -> TurnOverride:
+ """The pick for this turn: the session's provider / model / effort, the
+ folder's hands, and the tool context that routes approvals to the card."""
+ provider = session.provider
+ model = (session.model or "").strip() or _default_model(brain, provider)
+ effort = normalize_effort(provider, session.effort)
+ reasoning_effort: ReasoningEffort | None = (
+ effort if effort in _EFFORTS else None # type: ignore[assignment]
+ )
+ return TurnOverride(
+ provider=provider,
+ model=model,
+ reasoning_effort=reasoning_effort,
+ tools_extra=folder_tools(cwd, stance=stance),
+ tool_filter=plan_filter if stance == PLAN_STANCE else None,
+ tool_context={
+ # A typed answer is read, not heard: no spoken two-liners.
+ "delivery": "written",
+ # The executor asks the card, never the voice sentinel.
+ "approval_surface": "interactive",
+ "approval_ref": ref,
+ "approval_timeout_s": APPROVAL_TIMEOUT_S,
+ "tool_origin": "agent-chat",
+ "cwd": str(cwd),
+ },
+ max_turns=MAX_TURNS,
+ )
+
+
+def _default_model(brain: Any, provider: str) -> str | None:
+ fast = getattr(brain, "_fast_model", None)
+ if callable(fast):
+ try:
+ return fast(provider) or None
+ except Exception: # noqa: BLE001 — the provider's own default then
+ return None
+ return None
+
+
+# ------------------------------------------------------------- step mirror
+
+
+class _StepMirror:
+ """Turns THIS turn's bus events into the timeline's step rows.
+
+ The brain does not report its work to the chat; it publishes it on the
+ app bus, where the voice lane and the run inspector read it too. This
+ subscribes for the length of one turn and translates — for the events
+ that carry this turn's trace only, so a voice turn running alongside
+ never draws rows in the chat:
+
+ * ``ActionProposed`` -> a tool row, plus its ``rationale`` as reasoning
+ text. That sentence is the model's OWN words for why it reaches for the
+ tool — never a second "explain yourself" call.
+ * ``ActionExecuted`` / ``ActionDenied`` -> that row's result.
+ * ``ToolCallStarted`` / ``ToolCallCompleted`` -> the same for the paths
+ that publish those instead.
+
+ Rows are paired per tool name, oldest open first. Read-only and
+ defensive: a malformed event never reaches the brain (AP-18).
+ """
+
+ __slots__ = ("_bus", "_children", "_emit", "_open", "_seen_text", "_trace_id", "_turn_id")
+
+ def __init__(self, emit: Any, turn_id: str, bus: Any | None, trace_id: UUID) -> None:
+ self._emit = emit
+ self._turn_id = turn_id
+ self._bus = bus
+ self._trace_id = trace_id
+ self._open: list[tuple[str, str]] = [] # (tool name, call id)
+ self._children: set[UUID] = set()
+ self._seen_text: set[str] = set()
+
+ def start(self) -> None:
+ if self._bus is not None and hasattr(self._bus, "subscribe_all"):
+ self._bus.subscribe_all(self._on_event)
+
+ def stop(self) -> None:
+ if self._bus is not None and hasattr(self._bus, "unsubscribe_all"):
+ try:
+ self._bus.unsubscribe_all(self._on_event)
+ except Exception: # noqa: BLE001 — detaching must never raise
+ log.debug("brain runner: could not detach the step mirror", exc_info=True)
+
+ def open_call_id(self, tool_name: str) -> str:
+ """The open row for ``tool_name`` (the bridge's card hangs off it), else ""."""
+ for name, call_id in self._open:
+ if name == tool_name:
+ return call_id
+ return ""
+
+ async def _on_event(self, event: Any) -> None:
+ try:
+ await self._translate(event)
+ except Exception: # noqa: BLE001 — AP-18: never leave a subscriber
+ log.debug("brain runner: step mirror skipped an event", exc_info=True)
+
+ def _mine(self, event: Any) -> bool:
+ return getattr(event, "trace_id", None) == self._trace_id
+
+ async def _open_call(self, tool_name: str, args: Any) -> None:
+ call_id = uuid.uuid4().hex
+ self._open.append((tool_name, call_id))
+ if isinstance(args, dict):
+ payload_in: Any = args
+ elif args:
+ payload_in = {"arguments": str(args)}
+ else:
+ payload_in = {}
+ await self._emit(
+ "tool_call",
+ {"turn_id": self._turn_id, "call_id": call_id, "name": tool_name, "input": payload_in},
+ )
+
+ async def _close_call(self, tool_name: str, *, ok: bool, output: str, duration_ms: Any) -> None:
+ index = next((i for i, (name, _) in enumerate(self._open) if name == tool_name), None)
+ if index is None:
+ # A result with no row of its own (another path's, or a report
+ # without a start) would draw a headless row; drop it.
+ return
+ _, call_id = self._open.pop(index)
+ await self._emit(
+ "tool_result",
+ {
+ "turn_id": self._turn_id,
+ "call_id": call_id,
+ "output": str(output)[:2000],
+ "is_error": not ok,
+ "duration_ms": int(duration_ms or 0),
+ },
+ )
+
+ async def _translate(self, event: Any) -> None:
+ name = type(event).__name__
+ if name == "ActionProposed" and self._mine(event):
+ text = (getattr(event, "rationale", "") or "").strip()
+ if text and text not in self._seen_text:
+ self._seen_text.add(text)
+ await self._emit("reasoning_delta", {"turn_id": self._turn_id, "text": text})
+ await self._open_call(
+ getattr(event, "tool_name", "") or "tool", getattr(event, "args", None)
+ )
+ elif name == "ActionExecuted" and self._mine(event):
+ await self._close_call(
+ getattr(event, "tool_name", "") or "tool",
+ ok=bool(getattr(event, "success", False)),
+ output=getattr(event, "error", None) or getattr(event, "output_preview", "") or "",
+ duration_ms=getattr(event, "duration_ms", 0),
+ )
+ elif name == "ActionDenied" and self._mine(event):
+ await self._close_call(
+ getattr(event, "tool_name", "") or "tool",
+ ok=False,
+ output=str(getattr(event, "reason", "") or "denied"),
+ duration_ms=0,
+ )
+ elif (
+ name == "ToolCallStarted" and getattr(event, "parent_trace_id", None) == self._trace_id
+ ):
+ self._children.add(event.trace_id)
+ await self._open_call(
+ getattr(event, "tool_name", "") or "tool", getattr(event, "args_preview", "") or ""
+ )
+ elif name == "ToolCallCompleted" and getattr(event, "trace_id", None) in self._children:
+ self._children.discard(event.trace_id)
+ tool_name = getattr(event, "tool_name", "") or (
+ self._open[0][0] if self._open else "tool"
+ )
+ await self._close_call(
+ tool_name,
+ ok=bool(getattr(event, "success", False)),
+ output=getattr(event, "error", None) or getattr(event, "output_preview", "") or "",
+ duration_ms=getattr(event, "duration_ms", 0),
+ )
+
+
+# ------------------------------------------------------------------- turn
+
+
+async def run_brain_turn(
+ handle: TurnHandle,
+ text: str,
+ *,
+ bridge: ChatApprovalBridge | None,
+ always_allowed: set[str],
+) -> None:
+ """Run one typed turn on Jarvis' brain, streaming it into the timeline."""
+ started = time.monotonic()
+ turn_id = handle.turn_id
+ message_id = uuid.uuid4().hex
+ session = handle.session
+
+ async def emit(kind: str, payload: dict[str, Any]) -> None:
+ await handle.emit(make_event(kind, payload))
+
+ mirror = _StepMirror(emit, turn_id, handle.bus, handle.trace_id)
+ ref = approval_ref(session.session_id)
+
+ async def finish(status: str, usage: dict[str, Any], error: str | None = None) -> None:
+ await emit(
+ "turn_finished",
+ {
+ "turn_id": turn_id,
+ "status": status,
+ "duration_ms": int((time.monotonic() - started) * 1000),
+ "usage": usage,
+ "error": error,
+ },
+ )
+
+ brain = brain_manager()
+ if brain is None or not callable(getattr(brain, "generate", None)):
+ await finish(
+ "error", {}, "Jarvis' brain is still starting up. Give it a moment and send again."
+ )
+ return
+
+ cwd = Path(session.cwd or Path.home())
+ stance = handle.stance or "ask"
+ override = build_override(session, brain, stance=stance, cwd=cwd, ref=ref)
+ _note_skill_trigger(brain, text)
+
+ if bridge is not None:
+ bridge.arm(
+ ref,
+ ChatGrant(
+ session_id=session.session_id,
+ turn_id=turn_id,
+ stance=stance,
+ always_allowed=always_allowed,
+ ask=handle.request_approval,
+ call_id_for=mirror.open_call_id,
+ ),
+ )
+
+ # The "thinking" line the timeline shows until the first words arrive,
+ # and the watcher that fills it: every tool Jarvis reaches for and every
+ # sentence it writes next to one lands in the timeline as it happens.
+ await emit("reasoning_started", {"turn_id": turn_id, "message_id": message_id})
+ mirror.start()
+
+ loop = asyncio.get_running_loop()
+ seen: list[str] = []
+
+ def feed(chunk: str) -> None:
+ """Called by the brain as the answer is produced — a CHUNK, not the whole so far."""
+ if not chunk:
+ return
+ seen.append(chunk)
+ # The consumer is synchronous (the brain's contract); hand the emit
+ # back to the loop rather than blocking the producer.
+ asyncio.run_coroutine_threadsafe(
+ emit("text_delta", {"turn_id": turn_id, "message_id": message_id, "text": chunk}),
+ loop,
+ )
+
+ status = "done"
+ error: str | None = None
+ reply = ""
+ try:
+ reply = await _generate(brain, text, handle, override, feed)
+ except asyncio.CancelledError:
+ status = "cancelled"
+ except Exception as exc: # noqa: BLE001 — the timeline must never spin forever
+ log.exception("brain chat turn %s failed", turn_id)
+ status, error = "error", f"{type(exc).__name__}: {exc}"
+ finally:
+ if bridge is not None:
+ bridge.disarm(ref)
+ mirror.stop()
+
+ if status == "done" and handle.cancel.is_set():
+ status = "cancelled"
+ if status == "done":
+ answer = (reply or "").strip() or "".join(seen).strip()
+ if answer:
+ await emit(
+ "assistant_text", {"turn_id": turn_id, "message_id": message_id, "text": answer}
+ )
+ await finish(status, override.receipt.usage(), error)
+
+
+async def _generate(
+ brain: Any,
+ text: str,
+ handle: TurnHandle,
+ override: TurnOverride,
+ feed: Callable[[str], None],
+) -> str:
+ """The one ``generate`` call, under the chat's credentials, cancellable.
+
+ ``allow_voice_confirm=False`` is load-bearing: the executor must never
+ park a chat's consequential action in the manager-wide voice slot that
+ the NEXT spoken turn would consume. The chat's stance and card decide
+ (``approval_surface`` in the tool context).
+ """
+ from jarvis.core.config import get_jarvis_agent_secret, override_provider_secrets
+
+ session = handle.session
+ history = brain_history_from_events(handle.history)
+ kwargs: dict[str, Any] = {
+ "use_history": False,
+ "history_override": history,
+ "conversation_id": session.session_id,
+ "source_layer": SOURCE_LAYER,
+ "trace_id": handle.trace_id,
+ "allow_voice_confirm": False,
+ "emit_tool_ack": False,
+ "publish_response": False,
+ "text_consumer": feed,
+ "turn_override": override,
+ }
+ secret = _agent_secret(get_jarvis_agent_secret, session.provider)
+ overrides = {session.provider: secret} if secret else {}
+ # The task inherits the credential override through its context copy, so
+ # the scoped brain instance resolves the Agents-tab key on first use.
+ with override_provider_secrets(overrides):
+ task: asyncio.Task[str] = asyncio.create_task(
+ brain.generate(text, **kwargs), name=f"agent-chat-brain-{handle.turn_id[:8]}"
+ )
+ waiter = asyncio.create_task(handle.cancel.wait())
+ try:
+ done, _ = await asyncio.wait({task, waiter}, return_when=asyncio.FIRST_COMPLETED)
+ if task in done:
+ return await task
+ task.cancel()
+ try:
+ await task
+ except (asyncio.CancelledError, Exception) as exc: # noqa: BLE001 — the turn is over
+ log.debug("brain runner: cancelled turn ended with %r", exc)
+ raise asyncio.CancelledError
+ finally:
+ waiter.cancel()
+
+
+def _agent_secret(resolver: Callable[[str], str | None], provider: str) -> str | None:
+ try:
+ return resolver(provider)
+ except Exception: # noqa: BLE001 — no dedicated key: the brain resolves as usual
+ log.debug("brain runner: no agent-tier secret for %s", provider, exc_info=True)
+ return None
+
+
+def _note_skill_trigger(brain: Any, text: str) -> None:
+ """The desktop text path's pre-brain hook, verbatim in effect: a skill
+ whose trigger matches is noted on the brain, which injects its
+ instructions into this turn (desktop_app._on_user_message)."""
+ try:
+ from jarvis.skills.skill_context import try_get_skill_context
+ from jarvis.skills.trigger_matcher import TriggerMatcher
+
+ skill_ctx = try_get_skill_context()
+ note = getattr(brain, "note_skill_trigger", None)
+ if skill_ctx is None or not callable(note):
+ return
+ match_result = TriggerMatcher(skill_ctx.registry).match_voice_with_match(text, lang="auto")
+ if match_result is None:
+ return
+ matched, regex_match = match_result
+ content = ""
+ for group in reversed(regex_match.groups()):
+ if group and group.strip():
+ content = group.strip()
+ break
+ note(matched.name, content=content, source="chat")
+ except Exception: # noqa: BLE001 — the hook is defensive; a crash must never cost the turn
+ log.debug("brain runner: skill pre-hook skipped", exc_info=True)
+
+
+__all__ = [
+ "APPROVAL_TIMEOUT_S",
+ "MAX_TURNS",
+ "RUNNER",
+ "SOURCE_LAYER",
+ "brain_history_from_events",
+ "brain_manager",
+ "build_override",
+ "run_brain_turn",
+]
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index 7883c18f97..bb55b02db5 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -27,11 +27,13 @@ from collections.abc import Callable
from pathlib import Path
from typing import Any
+from jarvis.agent_chat.approval_bridge import ChatApprovalBridge
from jarvis.agent_chat.catalog import provider_row
from jarvis.agent_chat.effort import normalize_effort
from jarvis.agent_chat.events import make_event
from jarvis.agent_chat.permissions import ladder_key, normalize_permission
from jarvis.agent_chat.runner_api import TurnHandle, run_api_turn, supports_api_runner
+from jarvis.agent_chat.runner_brain import run_brain_turn
from jarvis.agent_chat.runner_cli import run_cli_turn, supports_cli_runner
from jarvis.agent_chat.store import DEFAULT_SURFACE, AgentChatSession, AgentChatStore
@@ -93,10 +95,22 @@ class AgentChatService:
*,
assistant_name: Callable[[], str] | None = None,
default_cwd: Callable[[], str] | None = None,
+ bus: Callable[[], Any | None] | None = None,
) -> None:
self.store = store
self._assistant_name = assistant_name or (lambda: "Jarvis")
self._default_cwd = default_cwd or (lambda: str(Path.home()))
+ # The app bus, resolved late (the server builds this service before
+ # the brain is up). The brain runner reads its tool events off it and
+ # the approval bridge answers the executor on it; without a bus the
+ # Jarvis surface still answers, just without tool rows and cards.
+ self._bus = bus or (lambda: None)
+ self._bridge: ChatApprovalBridge | None = None
+ # Brain-runner turns run one at a time across sessions: the manager
+ # keeps some per-turn state on itself (the realtime delegate lives
+ # with that too), and one person types one chat at a time. The voice
+ # is NOT held by this lock.
+ self._brain_lock = asyncio.Lock()
self._running: dict[str, _Running] = {}
self._subscribers: dict[str, set[Subscriber]] = {}
self._approvals: dict[str, asyncio.Future[str]] = {}
@@ -113,6 +127,14 @@ class AgentChatService:
def default_cwd(self) -> str:
return self._default_cwd()
+ def _bridge_for(self, bus: Any | None) -> ChatApprovalBridge | None:
+ """The approval bridge, built on the first Jarvis turn that has a bus."""
+ if bus is None:
+ return None
+ if self._bridge is None:
+ self._bridge = ChatApprovalBridge(bus)
+ return self._bridge
+
def create_session(
self,
*,
@@ -213,6 +235,7 @@ class AgentChatService:
),
)
+ bus = self._bus()
handle = TurnHandle(
session=session,
turn_id=turn_id,
@@ -223,11 +246,22 @@ class AgentChatService:
cancel=cancel,
history=history,
assistant_name=self._assistant_name(),
+ bus=bus,
+ surface=session.surface,
+ stance=session.permission_mode if session.surface == "jarvis" else "",
)
async def _body() -> None:
try:
- if supports_cli_runner(runner):
+ if runner == "brain":
+ async with self._brain_lock:
+ await run_brain_turn(
+ handle,
+ text,
+ bridge=self._bridge_for(bus),
+ always_allowed=self.always_allowed(session_id),
+ )
+ elif supports_cli_runner(runner):
vendor = await run_cli_turn(handle, text, runner)
if vendor and vendor != session.vendor_session:
self.store.update_session(session_id, vendor_session=vendor)
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index cee6920295..d5ab6d0889 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -3491,7 +3491,7 @@ class WebServer:
except Exception: # noqa: BLE001 — the name is cosmetic
return "Jarvis"
- return AgentChatService(store, assistant_name=_name)
+ return AgentChatService(store, assistant_name=_name, bus=lambda: self.bus)
async def stop(self) -> None:
self._mic_level_sessions.clear()
diff --git a/tests/fakes/fake_brain_manager.py b/tests/fakes/fake_brain_manager.py
new file mode 100644
index 0000000000..5dc7a3dd7c
--- /dev/null
+++ b/tests/fakes/fake_brain_manager.py
@@ -0,0 +1,102 @@
+"""A stand-in for ``BrainManager`` as the agent chat's brain runner sees it.
+
+Records every ``generate`` call's keyword arguments, streams its reply through
+``text_consumer`` in chunks, optionally publishes one tool round on the bus
+under the turn's trace id (so a step mirror can be tested against real
+events), and fills the override's receipt. ``switch`` / ``apply_provider_model``
+raise: the one thing the brain runner must never do is move the live brain.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+from jarvis.core.events import ActionExecuted, ActionProposed
+
+
+class FakeBrainManager:
+ def __init__(
+ self,
+ *,
+ bus: Any | None = None,
+ reply: str = "Hello from Jarvis",
+ chunks: tuple[str, ...] = ("Hello ", "from ", "Jarvis"),
+ tool: tuple[str, dict[str, Any]] | None = None,
+ hold: asyncio.Event | None = None,
+ fail: Exception | None = None,
+ fast_model: str = "fake-fast",
+ ) -> None:
+ self.bus = bus
+ self.reply = reply
+ self.chunks = chunks
+ self.tool = tool
+ self.hold = hold
+ self.fail = fail
+ self.fast_model = fast_model
+ self.calls: list[tuple[str, dict[str, Any]]] = []
+ self.noted_skills: list[tuple[str, str, str]] = []
+ self.seen_key: str | None = None
+
+ # -- what the runner reads ------------------------------------------------
+
+ def _fast_model(self, provider: str) -> str:
+ return self.fast_model
+
+ def note_skill_trigger(self, name: str, *, content: str = "", source: str = "") -> None:
+ self.noted_skills.append((name, content, source))
+
+ async def generate(self, text: str, **kwargs: Any) -> str:
+ self.calls.append((text, dict(kwargs)))
+ from jarvis.core.config import get_provider_secret
+
+ override = kwargs.get("turn_override")
+ provider = getattr(override, "provider", "") or ""
+ try:
+ self.seen_key = get_provider_secret(provider) if provider else None
+ except Exception: # noqa: BLE001 — a test box may have no secret store
+ self.seen_key = None
+ consumer = kwargs.get("text_consumer")
+ if self.hold is not None:
+ await self.hold.wait()
+ if self.fail is not None:
+ raise self.fail
+ if self.tool is not None and self.bus is not None:
+ name, args = self.tool
+ trace_id = kwargs.get("trace_id")
+ await self.bus.publish(
+ ActionProposed(
+ trace_id=trace_id, tool_name=name, args=args, rationale="Let me look."
+ )
+ )
+ await self.bus.publish(
+ ActionExecuted(
+ trace_id=trace_id,
+ tool_name=name,
+ success=True,
+ duration_ms=3,
+ output_preview="looked",
+ )
+ )
+ if callable(consumer):
+ for chunk in self.chunks:
+ consumer(chunk)
+ await asyncio.sleep(0)
+ if override is not None:
+ override.receipt.record(
+ provider=provider,
+ model=getattr(override, "model", None),
+ tokens_in=12,
+ tokens_out=4,
+ cost_usd=0.002,
+ finish_reason="stop",
+ )
+ return self.reply
+
+ # -- what the runner must never touch --------------------------------------
+
+ async def switch(self, *_a: Any, **_k: Any) -> None:
+ raise AssertionError("the brain runner must never switch the live brain")
+
+ def apply_provider_model(self, *_a: Any, **_k: Any) -> bool:
+ raise AssertionError("the brain runner must never rewrite the provider config")
diff --git a/tests/unit/agent_chat/test_runner_brain.py b/tests/unit/agent_chat/test_runner_brain.py
new file mode 100644
index 0000000000..329899597a
--- /dev/null
+++ b/tests/unit/agent_chat/test_runner_brain.py
@@ -0,0 +1,263 @@
+"""The Jarvis surface's brain runner — a whole typed turn through the service.
+
+A fake BrainManager (tests/fakes/fake_brain_manager.py) stands in for the
+harness; everything else is real: the store, the service, the event log, the
+app bus, the step mirror and the approval bridge.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.agent_chat import runner_brain
+from jarvis.agent_chat.events import make_event
+from jarvis.agent_chat.service import AgentChatService
+from jarvis.agent_chat.store import AgentChatStore
+from jarvis.core.bus import EventBus
+from tests.fakes.fake_brain_manager import FakeBrainManager
+
+
+async def _drain(q: asyncio.Queue, until_kind: str, wait_s: float = 5.0) -> list[dict[str, Any]]:
+ out: list[dict[str, Any]] = []
+ async with asyncio.timeout(wait_s):
+ while True:
+ ev = await q.get()
+ out.append(ev)
+ if ev["kind"] == until_kind:
+ return out
+
+
+def _service(bus: EventBus | None) -> AgentChatService:
+ return AgentChatService(
+ AgentChatStore(":memory:"), assistant_name=lambda: "Testo", bus=lambda: bus
+ )
+
+
+def _jarvis_session(svc: AgentChatService, tmp_path: Path, **over: Any):
+ kwargs: dict[str, Any] = {
+ "provider": "openai",
+ "model": "gpt-x",
+ "effort": "high",
+ "cwd": str(tmp_path),
+ "permission_mode": "ask",
+ "surface": "jarvis",
+ }
+ kwargs.update(over)
+ return svc.create_session(**kwargs)
+
+
+def no_cli(monkeypatch: pytest.MonkeyPatch):
+ from jarvis.agent_chat import service as svc_mod
+
+ monkeypatch.setattr(svc_mod, "_claude_cli_installed", lambda: False)
+
+
+async def test_a_jarvis_turn_runs_on_the_brain_with_the_sessions_pick(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_cli
+):
+ bus = EventBus()
+ fake = FakeBrainManager(bus=bus, tool=("open-app", {"name": "Notes"}))
+ monkeypatch.setattr(runner_brain, "brain_manager", lambda: fake)
+ monkeypatch.setattr(runner_brain, "_agent_secret", lambda _r, _p: "k-agent")
+ svc = _service(bus)
+ session = _jarvis_session(svc, tmp_path)
+ q = svc.subscribe(session.session_id)
+
+ turn_id = await svc.send(session.session_id, "Open my notes please")
+ events = await _drain(q, "turn_finished")
+ kinds = [e["kind"] for e in events]
+
+ started = next(e for e in events if e["kind"] == "turn_started")["payload"]
+ assert started["runner"] == "brain" and started["surface"] == "jarvis"
+ assert "reasoning_started" in kinds
+ assert [e["payload"]["text"] for e in events if e["kind"] == "text_delta"] == [
+ "Hello ",
+ "from ",
+ "Jarvis",
+ ], "deltas are chunks, not the text so far"
+ assert "reasoning_delta" in kinds and "tool_call" in kinds and "tool_result" in kinds
+ call = next(e for e in events if e["kind"] == "tool_call")["payload"]
+ result = next(e for e in events if e["kind"] == "tool_result")["payload"]
+ assert call["name"] == "open-app" and call["input"] == {"name": "Notes"}
+ assert result["call_id"] == call["call_id"] and result["output"] == "looked"
+ final = next(e for e in events if e["kind"] == "assistant_text")["payload"]
+ assert final["text"] == "Hello from Jarvis"
+ finished = events[-1]["payload"]
+ assert finished["turn_id"] == turn_id and finished["status"] == "done"
+ assert finished["usage"] == {"input_tokens": 12, "output_tokens": 4, "cost_usd": 0.002}
+
+ # The one generate call carried the pick — and nothing moved the live brain.
+ text, kw = fake.calls[0]
+ assert text == "Open my notes please"
+ override = kw["turn_override"]
+ assert override.provider == "openai" and override.model == "gpt-x"
+ assert override.reasoning_effort == "high"
+ assert kw["use_history"] is False and kw["publish_response"] is False
+ assert kw["allow_voice_confirm"] is False and kw["emit_tool_ack"] is False
+ assert kw["source_layer"] == runner_brain.SOURCE_LAYER
+ assert kw["conversation_id"] == session.session_id
+ assert set(override.tools_extra) == {
+ "Read",
+ "Write",
+ "Edit",
+ "Ls",
+ "Glob",
+ "Grep",
+ "RunCommand",
+ }
+ assert override.tool_context["approval_surface"] == "interactive"
+ assert override.tool_context["approval_ref"] == f"agent-chat:{session.session_id}"
+ assert override.tool_context["cwd"] == str(tmp_path)
+ assert override.tool_context["delivery"] == "written"
+ assert fake.seen_key == "k-agent", "the Agents-tab key was the turn's credential"
+ assert not svc.is_running(session.session_id)
+
+
+async def test_history_is_the_sessions_own_log_in_prose(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_cli
+):
+ fake = FakeBrainManager(reply="second")
+ monkeypatch.setattr(runner_brain, "brain_manager", lambda: fake)
+ svc = _service(None)
+ session = _jarvis_session(svc, tmp_path)
+ sid = session.session_id
+ svc.store.append_event(sid, make_event("user_message", {"text": "first question"}))
+ svc.store.append_event(sid, make_event("turn_started", {"turn_id": "t0"}))
+ svc.store.append_event(
+ sid,
+ make_event(
+ "tool_call",
+ {"turn_id": "t0", "call_id": "c1", "name": "Read", "input": {"file_path": "a.py"}},
+ ),
+ )
+ svc.store.append_event(
+ sid,
+ make_event(
+ "tool_result",
+ {"turn_id": "t0", "call_id": "c1", "output": "print(1)", "is_error": False},
+ ),
+ )
+ svc.store.append_event(
+ sid, make_event("assistant_text", {"turn_id": "t0", "text": "It prints 1."})
+ )
+ svc.store.append_event(sid, make_event("turn_finished", {"turn_id": "t0", "status": "done"}))
+ q = svc.subscribe(sid)
+
+ await svc.send(sid, "and now?")
+ await _drain(q, "turn_finished")
+
+ _, kw = fake.calls[0]
+ history = kw["history_override"]
+ assert [m.role for m in history] == ["user", "assistant"]
+ assert history[0].content == "first question"
+ assert "[used tool Read: a.py]" in history[1].content and "It prints 1." in history[1].content
+ assert all(isinstance(m.content, str) for m in history), "prose only, no foreign tool ids"
+
+
+async def test_plan_stance_offers_reading_hands_only(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_cli
+):
+ fake = FakeBrainManager()
+ monkeypatch.setattr(runner_brain, "brain_manager", lambda: fake)
+ svc = _service(None)
+ session = _jarvis_session(svc, tmp_path, permission_mode="plan")
+ q = svc.subscribe(session.session_id)
+ await svc.send(session.session_id, "what is in here?")
+ await _drain(q, "turn_finished")
+ override = fake.calls[0][1]["turn_override"]
+ assert set(override.tools_extra) == {"Read", "Ls", "Glob", "Grep"}
+ assert override.tool_filter is not None
+
+
+async def test_cancel_ends_a_running_brain_turn(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_cli
+):
+ hold = asyncio.Event()
+ fake = FakeBrainManager(hold=hold)
+ monkeypatch.setattr(runner_brain, "brain_manager", lambda: fake)
+ svc = _service(None)
+ session = _jarvis_session(svc, tmp_path)
+ q = svc.subscribe(session.session_id)
+ await svc.send(session.session_id, "take your time")
+ await _drain(q, "reasoning_started")
+ assert await svc.cancel(session.session_id)
+ events = await _drain(q, "turn_finished")
+ assert events[-1]["payload"]["status"] == "cancelled"
+ assert not svc.is_running(session.session_id)
+
+
+async def test_a_brain_error_ends_the_turn_honestly(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_cli
+):
+ fake = FakeBrainManager(fail=RuntimeError("provider down"))
+ monkeypatch.setattr(runner_brain, "brain_manager", lambda: fake)
+ svc = _service(None)
+ session = _jarvis_session(svc, tmp_path)
+ q = svc.subscribe(session.session_id)
+ await svc.send(session.session_id, "hi")
+ events = await _drain(q, "turn_finished")
+ finished = events[-1]["payload"]
+ assert finished["status"] == "error" and "provider down" in (finished["error"] or "")
+
+
+async def test_no_brain_yet_is_a_clear_error_not_a_hang(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_cli
+):
+ monkeypatch.setattr(runner_brain, "brain_manager", lambda: None)
+ svc = _service(None)
+ session = _jarvis_session(svc, tmp_path)
+ q = svc.subscribe(session.session_id)
+ await svc.send(session.session_id, "hi")
+ events = await _drain(q, "turn_finished")
+ assert events[-1]["payload"]["status"] == "error"
+ assert "starting up" in events[-1]["payload"]["error"]
+
+
+async def test_the_agent_surface_still_runs_the_api_loop(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_cli
+):
+ """A coding-agent session never reaches the brain runner."""
+ fake = FakeBrainManager()
+ monkeypatch.setattr(runner_brain, "brain_manager", lambda: fake)
+ svc = _service(None)
+ session = svc.create_session(
+ provider="openai", model="m", effort="high", cwd=str(tmp_path), surface="agent"
+ )
+ q = svc.subscribe(session.session_id)
+ await svc.send(session.session_id, "hi")
+ events = await _drain(q, "turn_finished")
+ started = next(e for e in events if e["kind"] == "turn_started")["payload"]
+ assert started["runner"] == "api" and started["surface"] == "agent"
+ assert fake.calls == []
+
+
+def test_step_mirror_ignores_another_turns_events():
+ async def scenario() -> None:
+ import uuid
+
+ from jarvis.core.events import ActionExecuted, ActionProposed
+
+ bus = EventBus()
+ mine, theirs = uuid.uuid4(), uuid.uuid4()
+ rows: list[tuple[str, dict[str, Any]]] = []
+
+ async def emit(kind: str, payload: dict[str, Any]) -> None:
+ rows.append((kind, payload))
+
+ mirror = runner_brain._StepMirror(emit, "turn-1", bus, mine)
+ mirror.start()
+ await bus.publish(ActionProposed(trace_id=theirs, tool_name="voice-tool", args={}))
+ await bus.publish(ActionProposed(trace_id=mine, tool_name="Read", args={"file_path": "x"}))
+ assert mirror.open_call_id("Read") and not mirror.open_call_id("voice-tool")
+ await bus.publish(ActionExecuted(trace_id=theirs, tool_name="voice-tool", success=True))
+ await bus.publish(ActionExecuted(trace_id=mine, tool_name="Read", success=True))
+ mirror.stop()
+ assert [k for k, _ in rows] == ["tool_call", "tool_result"]
+ assert rows[0][1]["name"] == "Read"
+
+ asyncio.run(scenario())