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(chat): the typed chat is an agent session — provider, model, effort and permission picks, wired to Claude Code, Codex, Antigravity and the API runner

rubenluetke10-beep645f4619c7ff
diff --git a/jarvis/agent_chat/__init__.py b/jarvis/agent_chat/__init__.py
new file mode 100644
index 0000000000..51a899a93a
--- /dev/null
+++ b/jarvis/agent_chat/__init__.py
@@ -0,0 +1,26 @@
+"""Agent chat — the typed front-page chat as an agent session.
+
+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:
+
+* :mod:`.effort` — which effort levels each provider family offers and how
+ a picked level maps onto what a provider actually accepts;
+* :mod:`.catalog` — the provider rows the picker shows (labels, runner
+ family, curated model lists for the CLI-backed providers);
+* :mod:`.tools` — the hands of the in-process agent (Read / Write / Edit /
+ Ls / Glob / Grep / RunCommand) scoped to the session's working directory;
+* :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:`.service` — sessions in flight, subscribers, cancel and approvals.
+
+The voice path is untouched: nothing here subscribes to the event bus, and
+nothing on the voice critical path imports this package (AP-9).
+"""
diff --git a/jarvis/agent_chat/catalog.py b/jarvis/agent_chat/catalog.py
new file mode 100644
index 0000000000..924d69d864
--- /dev/null
+++ b/jarvis/agent_chat/catalog.py
@@ -0,0 +1,247 @@
+"""The provider rows the agent-chat composer can pick from.
+
+The picker lists every provider of the AGENT tier — the same families the
+API-Keys "Agents" section shows (``MAPPINGS`` in
+``jarvis.missions.worker_runtime.provider_map`` plus the three direct CLI
+workers) — whether or not a credential is saved: a provider without one is
+shown disabled with a "connect" hint that leads to the API-Keys page, so the
+person sees what they *could* use (maintainer, 2026-08-23: all agents, not
+only the active one).
+
+Two kinds of runner sit behind the rows:
+
+``api``
+ The provider's own chat API, driven in-process in a tool loop
+ (:mod:`jarvis.agent_chat.runner_api`). Model lists come live from the
+ provider catalog (``GET /api/providers/{id}/models``).
+
+``claude-cli`` / ``codex-cli`` / ``agy-cli`` / ``grok-cli``
+ A vendor CLI driven non-interactively (:mod:`jarvis.agent_chat.runner_cli`).
+ The CLI brings its own tools and permissions; the model list is the
+ CLI's own — read live where the CLI publishes one (``agy models``,
+ Codex's ``models_cache.json``), else the curated fallback here — and
+ ``""`` means "the CLI's default".
+
+``claude-api`` is the one dual row: with a Claude subscription login the
+``claude`` CLI runs the session (Claude Code proper — tools, skills, the
+Max plan's included usage); with only an Anthropic API key the API runner
+does. The route decides per request by probing; this module only carries the
+static shape.
+
+Presentation data only — nothing here decides behaviour (AP-21); the rows
+exist so the picker can show a provider before a key is typed.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Final, Literal
+
+from jarvis.agent_chat.effort import default_effort, effort_levels
+from jarvis.brain.model_catalog import CURATED_MODELS
+
+Runner = Literal["api", "claude-cli", "codex-cli", "agy-cli", "grok-cli"]
+
+
+@dataclass(frozen=True, slots=True)
+class CuratedModel:
+ id: str
+ label: str
+ #: The effort levels THIS model takes, when narrower than the provider's
+ #: ladder (agy's Pro knows low/high, its Claude models none; Codex's 5.5
+ #: stops at xhigh). ``None`` = the provider ladder applies unchanged.
+ efforts: tuple[str, ...] | None = None
+ #: A short note the picker shows as the hint ("retires 2026-08-31").
+ note: str = ""
+
+ def to_dict(self) -> dict[str, Any]:
+ d: dict[str, Any] = {"id": self.id, "label": self.label}
+ if self.efforts is not None:
+ d["efforts"] = list(self.efforts)
+ if self.note:
+ d["note"] = self.note
+ return d
+
+
+@dataclass(frozen=True, slots=True)
+class ProviderRow:
+ """One row in the composer's provider column."""
+
+ id: str
+ label: str
+ #: Brand family for the mark (ProviderLogo.providerFamily in the UI).
+ family: str
+ runner: Runner
+ #: Where the model list comes from: "live" = the provider catalog route,
+ #: "curated" = the list embedded below (CLI-backed providers).
+ models_source: Literal["live", "curated"]
+ curated_models: tuple[CuratedModel, ...] = field(default_factory=tuple)
+ #: ``""`` = the runner's own default model.
+ default_model: str = ""
+ #: Runs on the person's own hardware — no credential to ask for.
+ keyless: bool = False
+ #: True when the CLI runner supports resuming a conversation natively
+ #: (claude --resume, codex exec resume). Others get the transcript replayed.
+ native_resume: bool = False
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "id": self.id,
+ "label": self.label,
+ "family": self.family,
+ "runner": self.runner,
+ "models_source": self.models_source,
+ "curated_models": [m.to_dict() for m in self.curated_models],
+ "default_model": self.default_model,
+ "keyless": self.keyless,
+ "native_resume": self.native_resume,
+ "effort_levels": list(effort_levels(self.id)),
+ "default_effort": default_effort(self.id),
+ }
+
+
+def _curated(provider: str) -> tuple[CuratedModel, ...]:
+ return tuple(CuratedModel(m.id, m.label) for m in CURATED_MODELS.get(provider, ()))
+
+
+def _agy_fallback_models() -> tuple[tuple[str, str, tuple[str, ...]], ...]:
+ from jarvis.agent_chat.runner_cli import AGY_FALLBACK_MODELS
+
+ return AGY_FALLBACK_MODELS
+
+
+#: What Claude Code's ``--model`` takes (claude 2.1.241): the current
+#: families by full id, the two legacy families that still answer, and the
+#: aliases people type. Per-model effort caps follow the docs (no xhigh on
+#: 4.6; no effort at all on Haiku 4.5 and the 4.5 generation).
+CLAUDE_CODE_MODELS: Final[tuple[CuratedModel, ...]] = (
+ CuratedModel("claude-fable-5", "Claude Fable 5"),
+ CuratedModel("claude-opus-5", "Claude Opus 5"),
+ CuratedModel("claude-opus-5[1m]", "Claude Opus 5", note="1M context"),
+ CuratedModel("claude-sonnet-5", "Claude Sonnet 5"),
+ CuratedModel("claude-haiku-4-5-20251001", "Claude Haiku 4.5", efforts=()),
+ CuratedModel("opusplan", "Opus plans, Sonnet builds", note="alias"),
+ CuratedModel("best", "Best available", note="alias"),
+ CuratedModel("claude-opus-4-8", "Claude Opus 4.8"),
+ CuratedModel("claude-opus-4-7", "Claude Opus 4.7"),
+ CuratedModel("claude-opus-4-6", "Claude Opus 4.6", efforts=("low", "medium", "high", "max")),
+ CuratedModel(
+ "claude-sonnet-4-6", "Claude Sonnet 4.6", efforts=("low", "medium", "high", "max")
+ ),
+ CuratedModel("claude-sonnet-4-5-20250929", "Claude Sonnet 4.5", efforts=()),
+ CuratedModel("claude-opus-4-5-20251101", "Claude Opus 4.5", efforts=()),
+)
+
+#: Codex's catalog as of codex 0.149 (the bundled list, ``visibility: list``),
+#: for a box where ``models_cache.json`` cannot be read. The route prefers the
+#: account's live list.
+CODEX_FALLBACK_MODELS: Final[tuple[CuratedModel, ...]] = (
+ CuratedModel("gpt-5.6-sol", "GPT-5.6 Sol", ("low", "medium", "high", "xhigh", "max", "ultra")),
+ CuratedModel(
+ "gpt-5.6-terra", "GPT-5.6 Terra", ("low", "medium", "high", "xhigh", "max", "ultra")
+ ),
+ CuratedModel("gpt-5.6-luna", "GPT-5.6 Luna", ("low", "medium", "high", "xhigh", "max")),
+ CuratedModel("gpt-5.5", "GPT-5.5", ("low", "medium", "high", "xhigh")),
+ CuratedModel("gpt-5.2", "GPT-5.2", ("low", "medium", "high", "xhigh")),
+)
+
+
+# Order = the order the picker shows. Subscription CLIs first (they are what
+# "our own Claude Code" means for most people), then the API families, then
+# the local servers.
+PROVIDER_ROWS: Final[tuple[ProviderRow, ...]] = (
+ ProviderRow(
+ id="claude-api",
+ label="Anthropic Claude",
+ family="claude",
+ runner="claude-cli",
+ models_source="curated",
+ curated_models=_curated("claude-api"),
+ default_model="",
+ native_resume=True,
+ ),
+ ProviderRow(
+ id="openai-codex",
+ label="OpenAI Codex",
+ family="openai",
+ runner="codex-cli",
+ models_source="curated",
+ # Codex's OWN catalog, not the OpenAI API's: the route replaces this
+ # with the account's live list from ``models_cache.json``.
+ curated_models=CODEX_FALLBACK_MODELS,
+ default_model="",
+ native_resume=True,
+ ),
+ ProviderRow(
+ id="antigravity",
+ label="Antigravity",
+ family="antigravity",
+ runner="agy-cli",
+ models_source="curated",
+ # agy's OWN ids (not the Gemini API's): the route replaces this with
+ # the live ``agy models`` list when the binary answers.
+ curated_models=tuple(
+ CuratedModel(mid, label, efforts) for mid, label, efforts in _agy_fallback_models()
+ ),
+ default_model="",
+ native_resume=True,
+ ),
+ ProviderRow(
+ id="grok-build",
+ label="Grok Build",
+ family="xai",
+ runner="grok-cli",
+ models_source="curated",
+ curated_models=_curated("grok"),
+ default_model="",
+ ),
+ ProviderRow(id="openai", label="OpenAI", family="openai", runner="api", models_source="live"),
+ ProviderRow(
+ id="gemini", label="Google Gemini", family="gemini", runner="api", models_source="live"
+ ),
+ ProviderRow(id="grok", label="xAI Grok", family="xai", runner="api", models_source="live"),
+ ProviderRow(
+ id="openrouter",
+ label="OpenRouter",
+ family="openrouter",
+ runner="api",
+ models_source="live",
+ ),
+ ProviderRow(
+ id="nvidia", label="NVIDIA NIM", family="nvidia", runner="api", models_source="live"
+ ),
+ ProviderRow(
+ id="vertex",
+ label="Google Vertex AI",
+ family="google-cloud",
+ runner="api",
+ models_source="curated",
+ curated_models=_curated("gemini"),
+ ),
+ ProviderRow(
+ id="ollama",
+ label="Ollama",
+ family="ollama",
+ runner="api",
+ models_source="live",
+ keyless=True,
+ ),
+ ProviderRow(
+ id="local-openai",
+ label="Local OpenAI-compatible",
+ family="local",
+ runner="api",
+ models_source="live",
+ keyless=True,
+ ),
+)
+
+_BY_ID: Final[dict[str, ProviderRow]] = {row.id: row for row in PROVIDER_ROWS}
+
+
+def provider_row(provider_id: str) -> ProviderRow | None:
+ return _BY_ID.get((provider_id or "").strip().lower())
+
+
+def known_provider_ids() -> tuple[str, ...]:
+ return tuple(row.id for row in PROVIDER_ROWS)
diff --git a/jarvis/agent_chat/effort.py b/jarvis/agent_chat/effort.py
new file mode 100644
index 0000000000..de699c0ad6
--- /dev/null
+++ b/jarvis/agent_chat/effort.py
@@ -0,0 +1,122 @@
+"""Reasoning-effort levels per agent-chat provider.
+
+Every provider exposes its own ladder: Claude Code takes ``--effort low |
+medium | high | xhigh | max``, the Codex CLI ``low .. ultra`` (per model), the
+OpenAI API ``none .. max`` (per model), Gemini 3 has three ``thinking_level``
+steps, Antigravity's ``agy`` takes ``low | medium | high`` (per model, none
+on its Claude models). The picker in the
+composer shows exactly the ladder of the provider in use, and
+:func:`normalize_effort` folds a picked level onto the nearest one a provider
+accepts when the two disagree (a session that moves from Codex to Gemini
+keeps "high"; "xhigh" becomes Gemini's "high").
+
+Single source of truth: the frontend receives these lists through
+``GET /api/agent-chat/catalog`` and never mirrors them (AP-4).
+"""
+
+from __future__ import annotations
+
+from typing import Final
+
+# The universal ordering — every provider ladder is a sub-sequence of this.
+ORDER: Final[tuple[str, ...]] = (
+ "none",
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultra",
+)
+
+# Provider id -> (offered levels in ascending order, default level).
+# ``""`` as default means "leave it to the provider" and is shown as
+# "Default" in the picker; it is only used for providers whose models vary
+# too much to pick one honest default (OpenRouter, NVIDIA NIM, local servers).
+_LADDERS: Final[dict[str, tuple[tuple[str, ...], str]]] = {
+ # Anthropic: the Claude Code CLI ladder (low/medium/high/xhigh/max). The
+ # API path has no effort knob today; the CLI is the preferred runner for
+ # a subscription login, so the ladder shown is the CLI's.
+ "claude-api": (("low", "medium", "high", "xhigh", "max"), "high"),
+ # OpenAI reasoning.effort for the GPT-5 family (``max`` since GPT-5.6;
+ # ``minimal`` only on the older 5.x — the plugin retries without a level
+ # the model rejects).
+ "openai": (("none", "minimal", "low", "medium", "high", "xhigh", "max"), "medium"),
+ # Codex CLI ``model_reasoning_effort`` (codex 0.149: low..xhigh on every
+ # current model, ``max`` on the 5.6 family, ``ultra`` = max + automatic
+ # task delegation on terra/sol). The catalog narrows it per model.
+ "openai-codex": (("low", "medium", "high", "xhigh", "max", "ultra"), "medium"),
+ # Gemini 3 thinking_level. MINIMAL exists on some 3.x models but 400s on
+ # others (3.7-flash), and the plugin maps nothing onto it — so it is not
+ # offered here; 2.5 maps onto budgets, the plugin handles both.
+ "gemini": (("low", "medium", "high"), "medium"),
+ "vertex": (("low", "medium", "high"), "medium"),
+ # agy --effort.
+ "antigravity": (("low", "medium", "high"), "medium"),
+ # OpenRouter forwards reasoning.effort to whatever sits behind the slug.
+ "openrouter": (("", "none", "low", "medium", "high", "xhigh"), ""),
+ # xAI reasoning_effort: grok-4.6 low..xhigh, grok-4.5 low..high; "" leaves
+ # a model that reasons on its own alone.
+ "grok": (("", "low", "medium", "high", "xhigh"), ""),
+ "grok-build": (("", "low", "medium", "high"), ""),
+ "nvidia": (("", "none", "low", "medium", "high"), ""),
+ "ollama": (("", "none", "low", "medium", "high", "max"), ""),
+ "local-openai": (("", "none", "low", "medium", "high"), ""),
+}
+
+_FALLBACK_LADDER: Final[tuple[tuple[str, ...], str]] = (("", "low", "medium", "high"), "")
+
+
+def effort_levels(provider: str) -> tuple[str, ...]:
+ """The ladder the composer offers for ``provider`` (ascending)."""
+ return _LADDERS.get((provider or "").strip().lower(), _FALLBACK_LADDER)[0]
+
+
+def default_effort(provider: str) -> str:
+ """The level a fresh session on ``provider`` starts with."""
+ return _LADDERS.get((provider or "").strip().lower(), _FALLBACK_LADDER)[1]
+
+
+def snap_to_ladder(level: str | None, ladder: tuple[str, ...] | list[str]) -> str:
+ """Fold ``level`` onto ``ladder`` (a model's own levels), lower neighbour first.
+
+ ``""``/``None`` passes through (provider default); an empty ladder means
+ the model has no knob and returns ``""``.
+ """
+ picked = (level or "").strip().lower()
+ offered = [lvl for lvl in ladder if lvl]
+ if not picked or not offered:
+ return "" if not offered else picked if picked in offered else ""
+ if picked in offered:
+ return picked
+ if picked not in ORDER:
+ return offered[0]
+ idx = ORDER.index(picked)
+ lower = [lvl for lvl in offered if lvl in ORDER and ORDER.index(lvl) <= idx]
+ return lower[-1] if lower else offered[0]
+
+
+def normalize_effort(provider: str, level: str | None) -> str:
+ """Fold ``level`` onto the nearest level ``provider`` accepts.
+
+ ``""``/``None`` means "provider default" and passes through. A level the
+ provider offers passes through unchanged. Anything else snaps to the
+ closest offered level on the universal ladder, preferring the lower
+ neighbour (a stronger model that cannot go higher should not silently
+ cost more): ``xhigh`` on Gemini -> ``high``; ``none`` on Claude Code ->
+ ``low``; ``max`` on Codex -> ``xhigh``.
+ """
+ picked = (level or "").strip().lower()
+ if not picked:
+ return ""
+ offered = [lvl for lvl in effort_levels(provider) if lvl]
+ if picked in offered:
+ return picked
+ if picked not in ORDER or not offered:
+ return default_effort(provider)
+ idx = ORDER.index(picked)
+ lower = [lvl for lvl in offered if ORDER.index(lvl) <= idx]
+ if lower:
+ return lower[-1]
+ return offered[0]
diff --git a/jarvis/agent_chat/events.py b/jarvis/agent_chat/events.py
new file mode 100644
index 0000000000..caa4a93e93
--- /dev/null
+++ b/jarvis/agent_chat/events.py
@@ -0,0 +1,48 @@
+"""The event vocabulary of an agent-chat session.
+
+One shape for the persisted log and the live WebSocket stream: every event is
+a plain dict ``{"seq", "ts_ms", "kind", "payload"}``. The UI rebuilds a
+session's timeline by folding the persisted events, then keeps folding live
+ones — the same reducer for both, so a reopened session looks exactly like
+it did while it ran (``src/components/agentchat/reduce.ts``).
+
+Kinds (``payload`` keys in brackets):
+
+``user_message`` [text] — the person's turn
+``turn_started`` [turn_id, provider, model, effort, runner]
+``text_delta`` [turn_id, message_id, text] — live only, never stored
+``assistant_text`` [turn_id, message_id, text] — the finished block
+``reasoning_delta`` [turn_id, text] — live only
+``reasoning`` [turn_id, text, duration_ms] — the finished block
+``tool_call`` [turn_id, call_id, name, input]
+``tool_result`` [turn_id, call_id, output, is_error, duration_ms]
+``approval_required`` [turn_id, approval_id, call_id, name, input, summary]
+``approval_resolved`` [turn_id, approval_id, decision] decision: allow | deny
+``turn_finished`` [turn_id, status, duration_ms, usage, error, cost_usd]
+ status: done | cancelled | error
+``session_updated`` [title?, provider?, model?, effort?, cwd?, permission_mode?]
+``error`` [turn_id?, message]
+
+``text_delta`` / ``reasoning_delta`` are the only transient kinds: the
+finished block carries the whole text, so the log never stores token dust.
+"""
+
+from __future__ import annotations
+
+import time
+from typing import Any, Final
+
+TRANSIENT_KINDS: Final[frozenset[str]] = frozenset({"text_delta", "reasoning_delta"})
+
+
+def now_ms() -> int:
+ return int(time.time() * 1000)
+
+
+def make_event(kind: str, payload: dict[str, Any] | None = None, *, seq: int = 0) -> dict[str, Any]:
+ """Build one event dict. ``seq`` is assigned by the store on persist."""
+ return {"seq": seq, "ts_ms": now_ms(), "kind": kind, "payload": dict(payload or {})}
+
+
+def is_transient(event: dict[str, Any]) -> bool:
+ return event.get("kind") in TRANSIENT_KINDS
diff --git a/jarvis/agent_chat/permissions.py b/jarvis/agent_chat/permissions.py
new file mode 100644
index 0000000000..586874eeaf
--- /dev/null
+++ b/jarvis/agent_chat/permissions.py
@@ -0,0 +1,276 @@
+"""Permission modes per agent-chat runner.
+
+Every runner has its own idea of "how much may the agent do without asking":
+Claude Code has ``--permission-mode`` (default / acceptEdits / plan /
+bypassPermissions / dontAsk), the Codex CLI pairs a sandbox with an approval
+policy (the TUI's Read-only / Auto / Full-access presets, plus headless
+``--approve-for-me`` where its own reviewer model answers the prompts),
+Antigravity's ``agy`` knows accept-edits, plan and a skip-permissions
+switch, and the in-process API runner gates its own tools. The composer
+shows exactly the ladder of the runner in use — the same words the vendor's
+own CLI uses, so a person who knows Claude Code's "Auto-accept edits" finds
+it here — and
+:func:`normalize_permission` folds a mode onto the nearest one another runner
+offers when a session moves between providers.
+
+``plan`` is special: every ladder that has it maps it onto "read and plan,
+change nothing" (Claude Code's plan mode; a read-only sandbox on Codex; the
+read-only tool set on the API runner). The composer draws it as the
+Build | Plan switch next to the permission pill.
+
+Single source of truth: the frontend receives the ladders through
+``GET /api/agent-chat/catalog`` and never mirrors them (AP-4).
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Final
+
+
+@dataclass(frozen=True, slots=True)
+class PermissionMode:
+ id: str
+ label: str
+ description: str
+
+ def to_dict(self) -> dict[str, str]:
+ return {"id": self.id, "label": self.label, "description": self.description}
+
+
+# ----------------------------------------------------------------- ladders
+
+_CLAUDE: Final[tuple[PermissionMode, ...]] = (
+ PermissionMode(
+ "default",
+ "Ask before acting",
+ "Claude Code's default: reads run freely; edits and commands show an "
+ "approval card here in the chat before they run.",
+ ),
+ PermissionMode(
+ "acceptEdits",
+ "Auto-accept edits",
+ "Edits and file writes in the working folder run without asking; "
+ "shell commands still ask (an approval card here in the chat).",
+ ),
+ PermissionMode(
+ "plan",
+ "Plan",
+ "Read and plan only — nothing is changed; the finished plan asks before building starts.",
+ ),
+ PermissionMode(
+ "auto",
+ "Auto (classifier)",
+ "Claude Code's own classifier approves routine actions and asks only "
+ "for the risky ones (approval card here in the chat).",
+ ),
+ PermissionMode(
+ "dontAsk",
+ "Don't ask",
+ "Never prompt: anything that would need a prompt is denied outright.",
+ ),
+ PermissionMode(
+ "bypassPermissions",
+ "Bypass permissions",
+ "Everything runs without asking — edits, commands, the lot. Use on a "
+ "folder you can afford to lose.",
+ ),
+)
+
+_CODEX: Final[tuple[PermissionMode, ...]] = (
+ PermissionMode(
+ "read-only",
+ "Read only",
+ "The sandbox lets the agent read; edits and commands that write are "
+ "blocked (Codex `--sandbox read-only`).",
+ ),
+ PermissionMode(
+ "approve-for-me",
+ "Ask (auto-review)",
+ "Codex's own reviewer model approves or declines what would have "
+ "asked you — the one ask-stance a headless run has "
+ "(`--approve-for-me`); the sandbox stays workspace-write.",
+ ),
+ PermissionMode(
+ "auto",
+ "Auto",
+ "Edits and commands inside the working folder run on their own; "
+ "anything outside it or on the network is blocked "
+ "(`--sandbox workspace-write`).",
+ ),
+ PermissionMode(
+ "plan",
+ "Plan",
+ "Read and plan only — a read-only sandbox; nothing is changed.",
+ ),
+ PermissionMode(
+ "full-access",
+ "Full access",
+ "No sandbox, no approvals — the agent may touch anything on this "
+ "machine (`--dangerously-bypass-approvals-and-sandbox`).",
+ ),
+)
+
+_AGY: Final[tuple[PermissionMode, ...]] = (
+ PermissionMode(
+ "accept-edits",
+ "Auto-accept edits",
+ "Edits run on their own; commands that need a permission are declined "
+ "and reported to the model.",
+ ),
+ PermissionMode(
+ "plan",
+ "Plan",
+ "Read and plan only — nothing is changed.",
+ ),
+ PermissionMode(
+ "skip-permissions",
+ "Skip permissions",
+ "Everything runs without asking (`--dangerously-skip-permissions`).",
+ ),
+)
+
+_GROK: Final[tuple[PermissionMode, ...]] = (
+ PermissionMode(
+ "default",
+ "Ask before acting",
+ "Grok Build's default: edits and commands would ask; in the chat the "
+ "CLI cannot ask back, so they are declined and reported.",
+ ),
+ PermissionMode(
+ "acceptEdits",
+ "Auto-accept edits",
+ "Edits in the working folder run without asking.",
+ ),
+ PermissionMode(
+ "plan",
+ "Plan",
+ "Read and plan only — nothing is changed.",
+ ),
+ PermissionMode(
+ "bypassPermissions",
+ "Bypass permissions",
+ "Everything runs without asking.",
+ ),
+)
+
+_API: Final[tuple[PermissionMode, ...]] = (
+ PermissionMode(
+ "ask",
+ "Ask before acting",
+ "Reads run freely; every edit, write and shell command shows an "
+ "approval card here in the chat before it runs.",
+ ),
+ PermissionMode(
+ "accept-edits",
+ "Auto-accept edits",
+ "Edits and writes in the working folder run on their own; shell commands still ask.",
+ ),
+ PermissionMode(
+ "plan",
+ "Plan",
+ "Read and plan only — the agent gets no editing or shell tools.",
+ ),
+ PermissionMode(
+ "auto",
+ "Full access",
+ "Everything runs without asking.",
+ ),
+)
+
+# runner -> (ladder, default)
+_LADDERS: Final[dict[str, tuple[tuple[PermissionMode, ...], str]]] = {
+ "claude-cli": (_CLAUDE, "acceptEdits"),
+ "codex-cli": (_CODEX, "auto"),
+ "agy-cli": (_AGY, "accept-edits"),
+ "grok-cli": (_GROK, "acceptEdits"),
+ "api": (_API, "ask"),
+}
+
+# The universal stance ordering: every ladder is a sub-sequence of this once
+# its vendor words are translated, so a mode can be folded across runners.
+_STANCE: Final[dict[str, int]] = {
+ # 0 = reads only, 1 = ask first, 2 = edits yes / commands ask, 3 = all.
+ "plan": 0,
+ "read-only": 0,
+ "ask": 1,
+ "default": 1,
+ "dontAsk": 1,
+ "approve-for-me": 1,
+ "accept-edits": 2,
+ "acceptEdits": 2,
+ "auto_codex": 2,
+ "auto_claude": 2,
+ "auto": 3,
+ "full-access": 3,
+ "bypassPermissions": 3,
+ "skip-permissions": 3,
+}
+
+
+def _stance(runner: str, mode: str) -> int:
+ # Codex's "auto" is the workspace-write sandbox (edits yes, not everything);
+ # Claude Code's "auto" is its classifier (routine yes, risky asks).
+ if runner == "codex-cli" and mode == "auto":
+ return _STANCE["auto_codex"]
+ if runner == "claude-cli" and mode == "auto":
+ return _STANCE["auto_claude"]
+ return _STANCE.get(mode, 1)
+
+
+def permission_modes(runner: str) -> tuple[PermissionMode, ...]:
+ """The ladder the composer offers for ``runner``."""
+ return _LADDERS.get(runner, _LADDERS["api"])[0]
+
+
+def default_permission(runner: str) -> str:
+ return _LADDERS.get(runner, _LADDERS["api"])[1]
+
+
+def permission_ids(runner: str) -> tuple[str, ...]:
+ return tuple(m.id for m in permission_modes(runner))
+
+
+def is_permission_mode(runner: str, mode: str) -> bool:
+ return mode in permission_ids(runner)
+
+
+def normalize_permission(runner: str, mode: str | None) -> str:
+ """Fold ``mode`` onto the closest mode ``runner`` accepts.
+
+ A mode the runner offers passes through. ``plan`` passes through wherever
+ a ladder has it. Anything else (a mode from another runner's ladder, or
+ the legacy ``ask``/``auto`` pair) snaps to the mode of the same stance,
+ else the nearest LOWER stance — moving to a runner that cannot express
+ "edits yes, commands ask" must not silently grant everything.
+ """
+ picked = (mode or "").strip()
+ ids = permission_ids(runner)
+ if not picked:
+ return default_permission(runner)
+ if picked in ids:
+ return picked
+ # Legacy ask/auto from before the ladders (store rows written by the
+ # first draft of this package).
+ want = _stance(runner, picked) if picked in _STANCE else 1
+ if picked == "auto":
+ want = 3
+ # Plan / read-only are only ever the target when that is what was asked
+ # for: folding "ask" onto a read-only sandbox would silently take the
+ # hands away.
+ pool = [m for m in ids if want == 0 or _stance(runner, m) > 0]
+ candidates = sorted(
+ (abs(_stance(runner, m) - want), _stance(runner, m) > want, i, m)
+ for i, m in enumerate(pool)
+ )
+ return candidates[0][3] if candidates else default_permission(runner)
+
+
+__all__ = [
+ "PermissionMode",
+ "default_permission",
+ "is_permission_mode",
+ "normalize_permission",
+ "permission_ids",
+ "permission_modes",
+]
diff --git a/jarvis/agent_chat/runner_api.py b/jarvis/agent_chat/runner_api.py
new file mode 100644
index 0000000000..3c83221e70
--- /dev/null
+++ b/jarvis/agent_chat/runner_api.py
@@ -0,0 +1,528 @@
+"""The in-process agent loop — one turn on a provider's chat API.
+
+This is "our own Claude Code": the provider's own streaming chat API
+(``jarvis.plugins.brain.*``) driven in a tool-use loop over
+:mod:`jarvis.agent_chat.tools`. Per round the model streams text (forwarded
+live as ``text_delta``), may request tool calls, each call is gated by the
+session's permission mode, executed, and its result fed back; the loop ends
+when a round produces no tool calls, the round budget is spent, or the
+person stops it.
+
+Provider-agnostic by construction (AP-21): the provider id selects the brain
+class through a capability-style map, the reasoning effort goes through the
+``BrainRequest.reasoning_effort`` hint every plugin already reads, and the
+agent-tier credential is applied through ``override_provider_secrets`` so a
+dedicated Agents-tab key wins over the shared brain key without touching the
+process environment.
+
+Conversation memory is the session's persisted event log: the turn
+reconstructs the provider messages from it (user text, assistant text + tool
+calls, tool results), so a reopened session continues with its whole
+history and nothing is kept in process between turns.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import platform
+import time
+import uuid
+from collections.abc import Awaitable, Callable
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Final
+
+from jarvis.agent_chat.effort import normalize_effort
+from jarvis.agent_chat.events import make_event
+from jarvis.agent_chat.permissions import normalize_permission
+from jarvis.agent_chat.store import AgentChatSession
+from jarvis.agent_chat.tools import (
+ EDIT_TOOLS,
+ READ_ONLY_TOOLS,
+ TOOL_SPECS,
+ execute_tool,
+ shell_label,
+ summarize_call,
+)
+from jarvis.core.protocols import BrainDelta, BrainMessage, BrainRequest
+
+log = logging.getLogger(__name__)
+
+# Provider slug -> (module, class). Lazy-imported so a turn on one provider
+# never imports another's SDK. Mirrors the agent worker's map; the chat has
+# no reason to diverge from the set the Agents tab offers.
+BRAIN_BY_PROVIDER: Final[dict[str, tuple[str, str]]] = {
+ "openai": ("jarvis.plugins.brain.openai", "OpenAIBrain"),
+ "openrouter": ("jarvis.plugins.brain.openrouter", "OpenRouterBrain"),
+ "grok": ("jarvis.plugins.brain.grok", "GrokBrain"),
+ "nvidia": ("jarvis.plugins.brain.nvidia", "NvidiaBrain"),
+ "claude-api": ("jarvis.plugins.brain.claude_api", "ClaudeAPIBrain"),
+ "gemini": ("jarvis.plugins.brain.gemini", "GeminiBrain"),
+ "vertex": ("jarvis.plugins.brain.vertex", "VertexBrain"),
+ "ollama": ("jarvis.plugins.brain.ollama", "OllamaBrain"),
+ "local-openai": ("jarvis.plugins.brain.local_openai", "LocalOpenAIBrain"),
+}
+
+MAX_ROUNDS: Final[int] = 40
+MAX_TOKENS: Final[int] = 8192
+# Tool output fed back to the model is capped here (the UI gets the full
+# output from the tool_result event, which carries the same text).
+_TOOL_RESULT_CAP: Final[int] = 24_000
+# How many past events are replayed into the provider messages. A long
+# session still works; this bounds the request size.
+_HISTORY_MAX_EVENTS: Final[int] = 600
+
+_ROUND_BUDGET_DIRECTIVE: Final[str] = (
+ "[round budget exhausted] Summarize what you did and what is still open. "
+ "Do not call any more tools in this reply."
+)
+
+
+def supports_api_runner(provider: str) -> bool:
+ return (provider or "").strip().lower() in BRAIN_BY_PROVIDER
+
+
+def build_brain(provider: str, model: str) -> Any:
+ mod_name, cls_name = BRAIN_BY_PROVIDER[provider]
+ mod = __import__(mod_name, fromlist=[cls_name])
+ return getattr(mod, cls_name)(model=model or None)
+
+
+def system_prompt(*, cwd: Path, assistant_name: str, plan: bool = False) -> str:
+ """The Claude-Code-shaped operating instructions for the API runner.
+
+ ``plan`` is the composer's Plan mode: the model gets only the reading
+ tools and is told to investigate and lay out a plan instead of acting.
+ """
+ plan_note = (
+ "\n\nPLAN MODE is on: you may read, search and list, but you have no tools that "
+ "change anything, and you must not try to. Investigate, then answer with a "
+ "concrete, numbered plan of the changes you would make (files, functions, the "
+ "order), plus the open questions. The person switches to Build mode to have it "
+ "carried out."
+ if plan
+ else ""
+ )
+ return (
+ f"You are {assistant_name}, an expert software engineer and general assistant "
+ "working as an interactive coding agent in the person's own environment — the "
+ "same job Claude Code does in a terminal, here inside a chat window.\n\n"
+ f"Working directory: {cwd}\n"
+ f"Operating system: {platform.system()} {platform.release()}\n"
+ f"Shell for RunCommand: {shell_label()}\n"
+ f"Date: {time.strftime('%Y-%m-%d')}\n\n"
+ "How to work:\n"
+ "- Use the tools to look before you answer: read the files you talk about, "
+ "run the tests you claim pass, check git state before describing it.\n"
+ "- Prefer Edit over Write for existing files; keep changes minimal and in the "
+ "style of the surrounding code.\n"
+ "- A tool result marked denied means the person declined that action. Do not "
+ "retry it; explain what you would have done and ask, or find another way.\n"
+ "- Be concise. Lead with the outcome. Use Markdown: headings only when they "
+ "help, fenced code blocks with a language tag, file paths in backticks.\n"
+ "- Never invent file contents, command output or results you did not observe.\n"
+ "- When the task is done, stop calling tools and give a short summary of what "
+ "changed and anything the person should do next." + plan_note
+ )
+
+
+@dataclass(slots=True)
+class TurnHandle:
+ """What the service hands a runner: where to emit, how to ask, when to stop."""
+
+ session: AgentChatSession
+ turn_id: str
+ emit: Callable[[dict[str, Any]], Awaitable[None]]
+ request_approval: Callable[[str, str, dict[str, Any], str], Awaitable[str]]
+ cancel: asyncio.Event
+ history: list[dict[str, Any]] = field(default_factory=list)
+ assistant_name: str = "Jarvis"
+
+
+# ------------------------------------------------------------ history
+
+
+def messages_from_events(events: list[dict[str, Any]]) -> list[BrainMessage]:
+ """Rebuild the provider conversation from the persisted event log.
+
+ ``user_message`` -> user; inside a turn, ``assistant_text`` and
+ ``tool_call`` fold into ONE assistant message of content blocks (a text
+ block, then the tool_use blocks in order) per round; ``tool_result``
+ becomes a tool message keyed by ``call_id``. Rounds are split where a
+ tool_result is followed by more assistant output.
+ """
+ out: list[BrainMessage] = []
+ pending_blocks: list[dict[str, Any]] = []
+
+ def flush() -> None:
+ nonlocal pending_blocks
+ if not pending_blocks:
+ return
+ only_text = all(b.get("type") == "text" for b in pending_blocks)
+ if only_text:
+ text = "".join(str(b.get("text") or "") for b in pending_blocks)
+ if text.strip():
+ out.append(BrainMessage(role="assistant", content=text))
+ else:
+ out.append(BrainMessage(role="assistant", content=list(pending_blocks)))
+ pending_blocks = []
+
+ for ev in events[-_HISTORY_MAX_EVENTS:]:
+ kind = ev.get("kind")
+ payload = ev.get("payload") or {}
+ if kind == "user_message":
+ flush()
+ text = str(payload.get("text") or "")
+ if text:
+ out.append(BrainMessage(role="user", content=text))
+ elif kind == "assistant_text":
+ text = str(payload.get("text") or "")
+ if text:
+ pending_blocks.append({"type": "text", "text": text})
+ elif kind == "tool_call":
+ block: dict[str, Any] = {
+ "type": "tool_use",
+ "id": str(payload.get("call_id") or f"call_{uuid.uuid4().hex[:8]}"),
+ "name": str(payload.get("name") or ""),
+ "input": payload.get("input") or {},
+ }
+ meta = payload.get("meta") or {}
+ if meta.get("thought_signature"):
+ block["thought_signature"] = meta["thought_signature"]
+ pending_blocks.append(block)
+ elif kind == "tool_result":
+ # Plain string content on purpose: the Anthropic adapter wraps a
+ # string into its tool_result block, Gemini and the OpenAI family
+ # pass it through — an envelope list would reach the OpenAI family
+ # as a JSON-serialised wrapper.
+ flush()
+ call_id = str(payload.get("call_id") or "")
+ output = str(payload.get("output") or "")
+ if payload.get("is_error"):
+ output = f"[error] {output}"
+ out.append(
+ BrainMessage(
+ role="tool",
+ content=_cap(output, _TOOL_RESULT_CAP),
+ tool_call_id=call_id,
+ name=str(payload.get("name") or ""),
+ )
+ )
+ elif kind == "turn_finished":
+ flush()
+ flush()
+ # A provider rejects a conversation that ends on a tool message or an
+ # assistant message with unanswered tool calls (a cancelled turn); the
+ # service appends the new user message after this, so close any open
+ # assistant tool round with a synthetic "cancelled" result first.
+ return _close_dangling_tool_calls(out)
+
+
+def _close_dangling_tool_calls(messages: list[BrainMessage]) -> list[BrainMessage]:
+ answered: set[str] = set()
+ for m in messages:
+ if m.role == "tool" and m.tool_call_id:
+ answered.add(m.tool_call_id)
+ out: list[BrainMessage] = []
+ for m in messages:
+ out.append(m)
+ if m.role == "assistant" and isinstance(m.content, list):
+ for block in m.content:
+ if block.get("type") == "tool_use" and block.get("id") not in answered:
+ out.append(
+ BrainMessage(
+ role="tool",
+ content="[cancelled before it ran]",
+ tool_call_id=str(block["id"]),
+ name=str(block.get("name") or ""),
+ )
+ )
+ return out
+
+
+def _cap(text: str, limit: int) -> str:
+ if len(text) <= limit:
+ return text
+ return text[:limit] + f"\n…[truncated, {len(text) - limit} more characters]"
+
+
+# ---------------------------------------------------------------- turn
+
+
+async def run_api_turn(handle: TurnHandle, user_text: str) -> None:
+ """Run one turn. Emits events through ``handle.emit``; never raises to the
+ caller except ``asyncio.CancelledError``."""
+ session = handle.session
+ provider = session.provider
+ cwd = Path(session.cwd or Path.home())
+ effort = normalize_effort(provider, session.effort)
+ t0 = time.perf_counter()
+ usage_total: dict[str, int] = {}
+
+ try:
+ brain = build_brain(provider, session.model)
+ except Exception as exc: # noqa: BLE001 — reported to the person, not raised
+ await handle.emit(
+ make_event(
+ "turn_finished",
+ {
+ "turn_id": handle.turn_id,
+ "status": "error",
+ "duration_ms": 0,
+ "usage": {},
+ "error": f"{type(exc).__name__}: {exc}",
+ },
+ )
+ )
+ return
+
+ messages = messages_from_events(handle.history)
+ messages.append(BrainMessage(role="user", content=user_text))
+ permission_mode = normalize_permission("api", session.permission_mode)
+ system = system_prompt(
+ cwd=cwd, assistant_name=handle.assistant_name, plan=permission_mode == "plan"
+ )
+ # Plan mode hands the model only the reading tools: it cannot change a
+ # thing, and it is told so in the system prompt.
+ tools: tuple[dict[str, Any], ...] = (
+ tuple(spec for spec in TOOL_SPECS if spec["name"] in READ_ONLY_TOOLS)
+ if permission_mode == "plan"
+ else TOOL_SPECS
+ )
+ status = "done"
+ error_text: str | None = None
+
+ from jarvis.core.config import get_jarvis_agent_secret, override_provider_secrets
+
+ secret = get_jarvis_agent_secret(provider)
+ overrides = {provider: secret} if secret else {}
+
+ try:
+ with override_provider_secrets(overrides):
+ for round_no in range(MAX_ROUNDS):
+ if handle.cancel.is_set():
+ status = "cancelled"
+ break
+ req = BrainRequest(
+ messages=tuple(messages),
+ tools=tools,
+ system=system,
+ temperature=0.2,
+ max_tokens=MAX_TOKENS,
+ stream=True,
+ reasoning_effort=effort or None, # type: ignore[arg-type]
+ )
+ message_id = uuid.uuid4().hex
+ text_parts: list[str] = []
+ tool_calls: list[dict[str, Any]] = []
+ try:
+ async for delta in _stream(brain, req, handle.cancel):
+ if delta.content:
+ text_parts.append(delta.content)
+ await handle.emit(
+ make_event(
+ "text_delta",
+ {
+ "turn_id": handle.turn_id,
+ "message_id": message_id,
+ "text": delta.content,
+ },
+ )
+ )
+ if delta.tool_call:
+ tool_calls.append(dict(delta.tool_call))
+ if delta.usage:
+ for k, v in delta.usage.items():
+ usage_total[k] = usage_total.get(k, 0) + int(v or 0)
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc: # noqa: BLE001 — provider error ends the turn honestly
+ status = "error"
+ error_text = f"{type(exc).__name__}: {exc}"
+ log.warning("agent chat turn %s: provider error: %s", handle.turn_id, exc)
+ break
+
+ text = "".join(text_parts)
+ if handle.cancel.is_set():
+ if text.strip():
+ await handle.emit(
+ make_event(
+ "assistant_text",
+ {"turn_id": handle.turn_id, "message_id": message_id, "text": text},
+ )
+ )
+ status = "cancelled"
+ break
+
+ if text.strip():
+ await handle.emit(
+ make_event(
+ "assistant_text",
+ {"turn_id": handle.turn_id, "message_id": message_id, "text": text},
+ )
+ )
+
+ if not tool_calls:
+ break
+
+ # Record the assistant round (text + tool_use blocks) for the
+ # next request.
+ blocks: list[dict[str, Any]] = []
+ if text:
+ blocks.append({"type": "text", "text": text})
+ for tc in tool_calls:
+ tc.setdefault("id", f"call_{uuid.uuid4().hex[:8]}")
+ block = {
+ "type": "tool_use",
+ "id": tc["id"],
+ "name": tc.get("name", ""),
+ "input": tc.get("input", {}) or {},
+ }
+ if tc.get("thought_signature"):
+ block["thought_signature"] = tc["thought_signature"]
+ blocks.append(block)
+ messages.append(BrainMessage(role="assistant", content=blocks))
+
+ for tc in tool_calls:
+ if handle.cancel.is_set():
+ status = "cancelled"
+ break
+ name = str(tc.get("name") or "")
+ args = tc.get("input") or {}
+ if not isinstance(args, dict):
+ try:
+ args = json.loads(str(args))
+ except (TypeError, ValueError):
+ args = {}
+ call_id = str(tc["id"])
+ meta = (
+ {"thought_signature": tc["thought_signature"]}
+ if tc.get("thought_signature")
+ else {}
+ )
+ await handle.emit(
+ make_event(
+ "tool_call",
+ {
+ "turn_id": handle.turn_id,
+ "call_id": call_id,
+ "name": name,
+ "input": args,
+ "summary": summarize_call(name, args),
+ "meta": meta,
+ },
+ )
+ )
+ t_tool = time.perf_counter()
+ output, is_error = await _run_gated_tool(
+ handle, permission_mode, call_id, name, args, cwd
+ )
+ if output == _PERMISSION_UPGRADED:
+ permission_mode = "auto"
+ output, is_error = await execute_tool(name, args, cwd=cwd)
+ await handle.emit(
+ make_event(
+ "tool_result",
+ {
+ "turn_id": handle.turn_id,
+ "call_id": call_id,
+ "name": name,
+ "output": output,
+ "is_error": is_error,
+ "duration_ms": int((time.perf_counter() - t_tool) * 1000),
+ },
+ )
+ )
+ fed = f"[error] {output}" if is_error else output
+ messages.append(
+ BrainMessage(
+ role="tool",
+ content=_cap(fed, _TOOL_RESULT_CAP),
+ tool_call_id=call_id,
+ name=name,
+ )
+ )
+ if status == "cancelled":
+ break
+ if round_no == MAX_ROUNDS - 2:
+ # Last round: no tools, summarize.
+ tools = ()
+ messages.append(BrainMessage(role="user", content=_ROUND_BUDGET_DIRECTIVE))
+ except asyncio.CancelledError:
+ status = "cancelled"
+ raise
+ finally:
+ await handle.emit(
+ make_event(
+ "turn_finished",
+ {
+ "turn_id": handle.turn_id,
+ "status": status,
+ "duration_ms": int((time.perf_counter() - t0) * 1000),
+ "usage": usage_total,
+ "error": error_text,
+ },
+ )
+ )
+
+
+_PERMISSION_UPGRADED: Final[str] = "\0permission-upgraded\0"
+
+
+async def _run_gated_tool(
+ handle: TurnHandle,
+ permission_mode: str,
+ call_id: str,
+ name: str,
+ args: dict[str, Any],
+ cwd: Path,
+) -> tuple[str, bool]:
+ """Ask first when the mode says so; run otherwise.
+
+ The ladder (jarvis/agent_chat/permissions.py): ``ask`` asks for every
+ mutating tool; ``accept-edits`` lets Write/Edit through and asks for
+ RunCommand; ``auto`` asks for nothing; ``plan`` never reaches here (the
+ model has no mutating tools) but is treated like ``ask`` if it did.
+ """
+ if name in READ_ONLY_TOOLS or permission_mode == "auto":
+ return await execute_tool(name, args, cwd=cwd)
+ if permission_mode == "accept-edits" and name in EDIT_TOOLS:
+ return await execute_tool(name, args, cwd=cwd)
+ decision = await handle.request_approval(call_id, name, args, summarize_call(name, args))
+ if decision == "deny":
+ return "Denied by the user.", True
+ if decision == "cancel":
+ return "Cancelled.", True
+ if decision == "allow_always":
+ return _PERMISSION_UPGRADED, False
+ return await execute_tool(name, args, cwd=cwd)
+
+
+async def _stream(brain: Any, req: BrainRequest, cancel: asyncio.Event):
+ """Iterate the brain stream, ending early when ``cancel`` is set."""
+ agen = brain.complete(req)
+ try:
+ while True:
+ if cancel.is_set():
+ return
+ nxt = asyncio.ensure_future(agen.__anext__())
+ waiter = asyncio.ensure_future(cancel.wait())
+ done, _ = await asyncio.wait({nxt, waiter}, return_when=asyncio.FIRST_COMPLETED)
+ if waiter in done and nxt not in done:
+ nxt.cancel()
+ return
+ waiter.cancel()
+ try:
+ delta: BrainDelta = nxt.result()
+ except StopAsyncIteration:
+ return
+ yield delta
+ finally:
+ aclose = getattr(agen, "aclose", None)
+ if aclose is not None:
+ try:
+ await aclose()
+ except Exception as exc: # noqa: BLE001 — closing a half-read stream may raise
+ log.debug("agent chat: closing the provider stream raised %s", exc)
diff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.py
new file mode 100644
index 0000000000..c97db9ba78
--- /dev/null
+++ b/jarvis/agent_chat/runner_cli.py
@@ -0,0 +1,1474 @@
+"""CLI-backed turns — a vendor agent binary drives the session.
+
+Four binaries, three wire shapes:
+
+* **Claude-shaped NDJSON** — ``claude`` (Claude Code) and ``grok`` (Grok
+ Build, whose ``--output-format streaming-messages-json`` is the Anthropic
+ Messages wire shape on purpose). One translator turns their ``system`` /
+ ``stream_event`` / ``assistant`` / ``user`` / ``result`` lines into
+ agent-chat events.
+* **Codex NDJSON** — ``codex exec --json`` with ``thread.*`` / ``turn.*`` /
+ ``item.*`` lines.
+* **Antigravity NDJSON** — ``agy --output-format stream-json`` with
+ ``event: init | step_update | result`` lines (``step_update`` carries text
+ deltas and tool steps keyed by ``step_index``; verified against agy 1.1.19).
+
+Every CLI resumes its own conversation natively (``claude --resume``,
+``codex exec resume``, ``grok -r``, ``agy --conversation``), so the session
+row keeps the vendor's id in ``vendor_session`` and a later turn continues
+the same conversation — the tools, skills, MCP servers and permissions are
+the CLI's own, exactly as in a terminal. The person's permission mode maps
+onto the closest stance each CLI offers; a print-mode CLI cannot ask back,
+so ``ask`` means "edits yes, anything riskier is declined by the CLI and
+reported to the model", and ``auto`` bypasses.
+
+Spawning follows the mission workers: shell-free argv, the prompt on stdin
+where the binary accepts it, ``NO_WINDOW_CREATIONFLAGS``, UTF-8 decoding,
+and the agent-account environment (``jarvis.agent_accounts.spawn_env``) so
+the active subscription seat is the one that answers.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import os
+import shutil
+import time
+import uuid
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Final
+
+from jarvis.agent_chat.effort import normalize_effort, snap_to_ladder
+from jarvis.agent_chat.events import make_event
+from jarvis.agent_chat.permissions import normalize_permission
+from jarvis.agent_chat.runner_api import TurnHandle
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+log = logging.getLogger(__name__)
+
+_READLINE_LIMIT: Final[int] = 16 * 1024 * 1024
+_TURN_TIMEOUT_S: Final[float] = 3600.0
+
+
+class CliUnavailable(RuntimeError):
+ """The binary is not installed (or not on PATH) — the UI says so."""
+
+
+# ------------------------------------------------------------ binaries
+
+
+def _which(*names: str) -> str | None:
+ for name in names:
+ found = shutil.which(name)
+ if found:
+ return found
+ return None
+
+
+def claude_argv_prefix() -> list[str]:
+ binary = _which("claude", "claude.cmd", "claude.exe")
+ if not binary:
+ raise CliUnavailable("Claude Code (claude) is not installed or not on PATH.")
+ from jarvis.claude_auth import claude_cli_argv_prefix
+
+ return claude_cli_argv_prefix(binary)
+
+
+def codex_argv_prefix() -> list[str]:
+ try:
+ from jarvis.missions.workers.codex_direct_worker import _resolve_codex_argv_prefix
+
+ prefix = _resolve_codex_argv_prefix()
+ except Exception: # noqa: BLE001 — the worker helper is a convenience, not a contract
+ prefix = []
+ if prefix:
+ return list(prefix)
+ binary = _which("codex", "codex.cmd", "codex.exe")
+ if not binary:
+ raise CliUnavailable("Codex CLI (codex) is not installed or not on PATH.")
+ return [binary]
+
+
+def agy_argv_prefix() -> list[str]:
+ try:
+ from jarvis.google_cli.resolver import resolve_google_cli
+
+ cli = resolve_google_cli()
+ except Exception: # noqa: BLE001 — fall back to PATH below
+ cli = None
+ if cli is not None and cli.kind == "agy":
+ return list(cli.argv_prefix)
+ binary = _which("agy", "agy.exe")
+ if not binary:
+ raise CliUnavailable("Antigravity CLI (agy) is not installed or not on PATH.")
+ return [binary]
+
+
+def grok_argv_prefix() -> list[str]:
+ binary = _which("grok", "grok.exe", "grok.cmd")
+ if not binary:
+ raise CliUnavailable("Grok Build (grok) is not installed or not on PATH.")
+ return [binary]
+
+
+def _account_env(platform: str) -> dict[str, str]:
+ """The child environment for the active subscription seat of ``platform``."""
+ try:
+ from jarvis import agent_accounts
+
+ account = agent_accounts.active_account(platform) # type: ignore[arg-type]
+ env = agent_accounts.spawn_env(platform, account.id, base=os.environ) # type: ignore[arg-type]
+ except Exception: # noqa: BLE001 — no account layer for this platform → plain env
+ env = dict(os.environ)
+ env.setdefault("PYTHONIOENCODING", "utf-8")
+ return env
+
+
+# ------------------------------------------------------------ argv per CLI
+
+#: Prepended to the prompt for a runner without a plan mode of its own: the
+#: sandbox already forbids changes; this tells the model what to do instead.
+_PLAN_PREAMBLE: Final[str] = (
+ "PLAN MODE: do not change any files or run commands that write. Investigate "
+ "(read, search, list), then answer with a concrete, numbered plan of the "
+ "changes you would make — files, functions, the order — and the open "
+ "questions. The person will switch to Build mode to have it carried out.\n\n"
+)
+
+
+@dataclass(slots=True)
+class CliPlan:
+ argv: list[str]
+ env: dict[str, str]
+ stdin_text: str | None
+ shape: str # "claude" | "codex" | "agy"
+ #: Vendor session id we chose up front (claude/grok --session-id), or None
+ #: when the CLI assigns one (agy, codex) and we read it from the stream.
+ vendor_session: str | None
+ #: Keep stdin open after the prompt: the CLI talks back on it (Claude
+ #: Code's control protocol — permission prompts answered from the chat).
+ #: The pump closes stdin once the turn's ``result`` line arrived.
+ keep_stdin: bool = False
+
+
+def claude_stream_input(prompt: str) -> str:
+ """One NDJSON user message for ``--input-format stream-json``."""
+ return (
+ json.dumps(
+ {"type": "user", "message": {"role": "user", "content": prompt}},
+ ensure_ascii=False,
+ )
+ + "\n"
+ )
+
+
+def plan_claude(
+ *, prompt: str, cwd: Path, model: str, effort: str, permission_mode: str, resume: str | None
+) -> CliPlan:
+ mode = normalize_permission("claude-cli", permission_mode)
+ argv = [
+ *claude_argv_prefix(),
+ "--print",
+ "--output-format",
+ "stream-json",
+ "--verbose",
+ "--include-partial-messages",
+ # The control protocol: the user message goes in as NDJSON and a
+ # permission prompt comes back as a ``control_request`` line that the
+ # chat answers on stdin — so "ask" really asks, here, in the chat.
+ "--input-format",
+ "stream-json",
+ "--permission-prompt-tool",
+ "stdio",
+ "--permission-mode",
+ mode,
+ ]
+ if model:
+ argv += ["--model", model]
+ if effort:
+ argv += ["--effort", effort]
+ if resume:
+ argv += ["--resume", resume]
+ sid = resume
+ else:
+ sid = str(uuid.uuid4())
+ argv += ["--session-id", sid]
+ return CliPlan(
+ argv,
+ _account_env("claude"),
+ claude_stream_input(prompt),
+ "claude",
+ sid,
+ keep_stdin=True,
+ )
+
+
+def plan_grok(
+ *, prompt: str, cwd: Path, model: str, effort: str, permission_mode: str, resume: str | None
+) -> CliPlan:
+ argv = [
+ *grok_argv_prefix(),
+ "--no-auto-update",
+ "--no-alt-screen",
+ "--output-format",
+ "streaming-messages-json",
+ "--include-partial-messages",
+ "--permission-mode",
+ normalize_permission("grok-cli", permission_mode),
+ "--cwd",
+ str(cwd),
+ ]
+ if model:
+ argv += ["-m", model]
+ if effort:
+ argv += ["--reasoning-effort", effort]
+ if resume:
+ argv += ["-r", resume]
+ sid = resume
+ else:
+ sid = str(uuid.uuid4())
+ argv += ["--session-id", sid]
+ argv += ["-p", prompt]
+ return CliPlan(argv, _account_env("grok-build"), None, "claude", sid)
+
+
+#: agy's own model ids as of 1.1.19, for a box where ``agy models`` cannot be
+#: read (the live list is account-dependent and wins whenever it answers).
+AGY_FALLBACK_MODELS: Final[tuple[tuple[str, str, tuple[str, ...]], ...]] = (
+ ("gemini-3.7-flash", "Gemini 3.7 Flash", ("low", "medium", "high")),
+ ("gemini-3.6-flash", "Gemini 3.6 Flash", ("low", "medium", "high")),
+ ("gemini-3.5-flash", "Gemini 3.5 Flash", ("low", "medium", "high")),
+ ("gemini-3.1-pro", "Gemini 3.1 Pro", ("low", "high")),
+ ("claude-sonnet-4-6", "Claude Sonnet 4.6 (Thinking)", ()),
+ ("claude-opus-4-6-thinking", "Claude Opus 4.6 (Thinking)", ()),
+ ("gpt-oss-120b", "GPT-OSS 120B", ("medium",)),
+)
+
+_AGY_EFFORT_SUFFIXES: Final[tuple[str, ...]] = ("low", "medium", "high")
+
+
+def agy_model_catalog(raw_models: list[dict[str, Any]] | None) -> list[dict[str, Any]]:
+ """Fold agy's suffixed ids into base models with an effort ladder each.
+
+ ``agy models`` lists ``gemini-3.5-flash-low`` / ``-medium`` / ``-high``
+ as three ids; the composer shows ONE model with a three-step effort
+ pick, so this folds ``<base>-<effort>`` onto ``<base>`` and records the
+ efforts seen. Ids without a suffix (the Claude models, ``gpt-oss-120b``)
+ keep an empty ladder = no effort pick. ``None`` (no list readable) gives
+ the fallback table.
+ """
+ if not raw_models:
+ return [
+ {"id": mid, "label": label, "efforts": list(efforts)}
+ for mid, label, efforts in AGY_FALLBACK_MODELS
+ ]
+ order: list[str] = []
+ efforts: dict[str, list[str]] = {}
+ labels: dict[str, str] = {}
+ for m in raw_models:
+ mid = str(m.get("id") or "").strip()
+ if not mid:
+ continue
+ label = str(m.get("label") or mid)
+ base, suffix = mid, ""
+ for sfx in _AGY_EFFORT_SUFFIXES:
+ if mid.endswith("-" + sfx):
+ base, suffix = mid[: -(len(sfx) + 1)], sfx
+ break
+ if base not in efforts:
+ efforts[base] = []
+ order.append(base)
+ labels[base] = _strip_effort_label(label) if suffix else label
+ if suffix and suffix not in efforts[base]:
+ efforts[base].append(suffix)
+ return [
+ {
+ "id": base,
+ "label": labels[base],
+ "efforts": sorted(efforts[base], key=_AGY_EFFORT_SUFFIXES.index),
+ }
+ for base in order
+ ]
+
+
+def _strip_effort_label(label: str) -> str:
+ # "Gemini 3.5 Flash (High)" -> "Gemini 3.5 Flash"
+ for sfx in ("(Low)", "(Medium)", "(High)"):
+ if label.endswith(sfx):
+ return label[: -len(sfx)].rstrip()
+ return label
+
+
+def agy_model_args(
+ model: str, effort: str, catalog: list[dict[str, Any]] | None = None
+) -> list[str]:
+ """The ``--model`` / ``--effort`` pair agy accepts for a base id + effort.
+
+ agy is strict: a base Gemini id REQUIRES ``--effort`` (and only the levels
+ that model has — Pro knows low/high), a suffixed id FORBIDS it, and the
+ Claude / GPT-OSS ids take none at all. The catalog says which is which;
+ without one the fallback table does.
+ """
+ rows = catalog or agy_model_catalog(None)
+ by_id = {r["id"]: r for r in rows}
+ if not model:
+ # Default model: agy accepts ``--effort`` alone.
+ return ["--effort", effort] if effort in _AGY_EFFORT_SUFFIXES else []
+ row = by_id.get(model)
+ if row is None:
+ # A suffixed or unknown id: pass it through untouched.
+ return ["--model", model]
+ ladder = list(row.get("efforts") or [])
+ if not ladder:
+ return ["--model", model]
+ if ladder == ["medium"] and model.startswith("gpt-oss"):
+ # gpt-oss-120b: the bare id runs; ``-medium`` is the only suffix.
+ return ["--model", model]
+ level = effort if effort in ladder else _nearest_lower(effort, ladder)
+ return ["--model", model, "--effort", level]
+
+
+def _nearest_lower(effort: str, ladder: list[str]) -> str:
+ order = list(_AGY_EFFORT_SUFFIXES)
+ if effort not in order:
+ return ladder[-1] if "high" in ladder else ladder[0]
+ idx = order.index(effort)
+ lower = [lvl for lvl in ladder if order.index(lvl) <= idx]
+ return lower[-1] if lower else ladder[0]
+
+
+def plan_agy(
+ *, prompt: str, cwd: Path, model: str, effort: str, permission_mode: str, resume: str | None
+) -> CliPlan:
+ mode = normalize_permission("agy-cli", permission_mode)
+ argv = [
+ *agy_argv_prefix(),
+ "--output-format",
+ "stream-json",
+ "--add-dir",
+ str(cwd),
+ # agy's own print timeout is 5 min; ours is the long one.
+ "--print-timeout",
+ f"{int(_TURN_TIMEOUT_S // 60)}m",
+ ]
+ if mode == "skip-permissions":
+ argv += ["--dangerously-skip-permissions"]
+ elif mode == "plan":
+ argv += ["--mode", "plan"]
+ else:
+ argv += ["--mode", "accept-edits"]
+ argv += agy_model_args(model, effort, _agy_catalog_cached())
+ if resume:
+ argv += ["--conversation", resume]
+ env = dict(os.environ)
+ env.setdefault("AGY_CLI_HIDE_LOGO", "1")
+ env.setdefault("PYTHONIOENCODING", "utf-8")
+ # Prompt on stdin: no argv length limit, and no ``-p`` that could swallow
+ # the next flag as its value.
+ return CliPlan(argv, env, prompt, "agy", resume)
+
+
+def read_codex_models() -> list[dict[str, Any]] | None:
+ """Codex's account catalog from ``$CODEX_HOME/models_cache.json``.
+
+ The CLI refreshes that file itself (TTL 5 min, ETag) on every run; it is
+ the same list the Codex TUI's model picker shows for this login. Rows:
+ ``{id, label, efforts, note}`` for ``visibility: list`` models, ordered
+ by the catalog's ``priority``. ``None`` when the file is missing or
+ unreadable (the caller falls back to the bundled list).
+ """
+ env = _account_env("codex")
+ home = Path(env.get("CODEX_HOME") or Path.home() / ".codex")
+ path = home / "models_cache.json"
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError) as exc:
+ log.debug("agent chat: codex models cache unreadable at %s: %s", path, exc)
+ return None
+ models = data.get("models") if isinstance(data, dict) else None
+ if not isinstance(models, list):
+ return None
+ rows: list[tuple[int, dict[str, Any]]] = []
+ for m in models:
+ if not isinstance(m, dict):
+ continue
+ if str(m.get("visibility") or "list") != "list":
+ continue
+ slug = str(m.get("slug") or m.get("id") or "").strip()
+ if not slug:
+ continue
+ levels = m.get("supported_reasoning_levels") or []
+ efforts = [
+ str(lvl.get("effort") if isinstance(lvl, dict) else lvl)
+ for lvl in levels
+ if (lvl.get("effort") if isinstance(lvl, dict) else lvl)
+ ]
+ note = ""
+ upgrade = m.get("upgrade")
+ if isinstance(upgrade, dict) and upgrade.get("retirement_at"):
+ note = f"retires {str(upgrade['retirement_at'])[:10]}"
+ try:
+ prio = int(m.get("priority") or 0)
+ except (TypeError, ValueError):
+ prio = 0
+ rows.append(
+ (
+ prio,
+ {
+ "id": slug,
+ "label": str(m.get("display_name") or slug),
+ "efforts": efforts,
+ "note": note,
+ },
+ )
+ )
+ rows.sort(key=lambda r: r[0])
+ return [r[1] for r in rows] or None
+
+
+_AGY_CATALOG: dict[str, Any] = {"at": 0.0, "rows": None}
+_AGY_CATALOG_TTL_S: Final[float] = 600.0
+
+
+def _agy_catalog_cached() -> list[dict[str, Any]] | None:
+ rows = _AGY_CATALOG.get("rows")
+ return rows if isinstance(rows, list) else None
+
+
+def read_agy_models(timeout_s: float = 8.0) -> list[dict[str, Any]]:
+ """``agy --output-format json models`` -> the folded catalog (cached 10 min).
+
+ Blocking (a ~2 s subprocess) — call it off the event loop. Any failure
+ yields the fallback table; the cache keeps a failure out of the next
+ request for the TTL too.
+ """
+ import subprocess
+
+ now = time.monotonic()
+ if _AGY_CATALOG["rows"] is not None and now - _AGY_CATALOG["at"] < _AGY_CATALOG_TTL_S:
+ return list(_AGY_CATALOG["rows"])
+ raw: list[dict[str, Any]] | None = None
+ try:
+ argv = [*agy_argv_prefix(), "--output-format", "json", "models"]
+ env = dict(os.environ)
+ env.setdefault("AGY_CLI_HIDE_LOGO", "1")
+ proc = subprocess.run( # noqa: S603 — fixed argv, no shell
+ argv,
+ capture_output=True,
+ timeout=timeout_s,
+ env=env,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ text = proc.stdout.decode("utf-8", errors="replace")
+ for line in text.splitlines():
+ line = line.strip()
+ if not line.startswith("{"):
+ continue
+ obj = json.loads(line)
+ data = ((obj.get("command") or {}).get("data") or {}) if isinstance(obj, dict) else {}
+ models = data.get("models") if isinstance(data, dict) else None
+ if isinstance(models, list):
+ raw = [m for m in models if isinstance(m, dict)]
+ break
+ except (CliUnavailable, OSError, ValueError, subprocess.SubprocessError) as exc:
+ log.debug("agent chat: agy models unavailable: %s", exc)
+ rows = agy_model_catalog(raw)
+ _AGY_CATALOG["rows"] = rows
+ _AGY_CATALOG["at"] = now
+ return list(rows)
+
+
+def plan_codex(
+ *, prompt: str, cwd: Path, model: str, effort: str, permission_mode: str, resume: str | None
+) -> CliPlan:
+ mode = normalize_permission("codex-cli", permission_mode)
+ base = codex_argv_prefix()
+ if resume:
+ argv = [*base, "exec", "resume", resume, "--json"]
+ else:
+ argv = [*base, "exec", "--json", "--cd", str(cwd)]
+ argv += ["--skip-git-repo-check"]
+ # The TUI's presets, spelled out for ``exec`` (codex 0.149): Read only /
+ # Auto (workspace-write) / Full access (``--yolo``), plus "approve for
+ # me" — Codex's own reviewer model decides what would have asked you,
+ # the one ask-stance a headless run has. ``exec`` never prompts on
+ # stdin; the sandbox decides what may happen. Plan is the read-only
+ # sandbox plus an instruction to plan instead of act. The sandbox goes
+ # through ``-c sandbox_mode`` because ``exec resume`` has no ``-s``.
+ if mode == "full-access":
+ argv += ["--dangerously-bypass-approvals-and-sandbox"]
+ elif mode == "approve-for-me":
+ argv += [
+ "-c",
+ 'sandbox_mode="workspace-write"',
+ "-c",
+ 'approvals_reviewer="auto_review"',
+ "-c",
+ 'approval_policy="on-request"',
+ ]
+ else:
+ sandbox = "workspace-write" if mode == "auto" else "read-only"
+ argv += ["-c", f'sandbox_mode="{sandbox}"']
+ if model:
+ # The account's catalog says which levels THIS model takes (5.5 stops
+ # at xhigh, terra goes to ultra); an unsupported level is snapped
+ # rather than sent for the server to reject.
+ for row in read_codex_models() or []:
+ if row.get("id") == model and row.get("efforts"):
+ effort = snap_to_ladder(effort, list(row["efforts"]))
+ break
+ if effort:
+ argv += ["-c", f"model_reasoning_effort={effort}"]
+ # Without a summary setting no ``reasoning`` items appear at all.
+ argv += ["-c", "model_reasoning_summary=auto"]
+ if model:
+ argv += ["--model", model]
+ argv += ["-"] # prompt on stdin
+ text = _PLAN_PREAMBLE + prompt if mode == "plan" else prompt
+ return CliPlan(argv, _account_env("codex"), text, "codex", resume)
+
+
+_PLANNERS: Final[dict[str, Any]] = {
+ "claude-cli": plan_claude,
+ "grok-cli": plan_grok,
+ "agy-cli": plan_agy,
+ "codex-cli": plan_codex,
+}
+
+
+def supports_cli_runner(runner: str) -> bool:
+ return runner in _PLANNERS
+
+
+# ------------------------------------------------------------ translation
+
+
+@dataclass(slots=True)
+class _ClaudeState:
+ turn_id: str
+ vendor_session: str | None = None
+ current_message_id: str | None = None
+ text_acc: dict[str, str] = field(default_factory=dict)
+ thinking_acc: dict[str, str] = field(default_factory=dict)
+ thinking_started: dict[str, float] = field(default_factory=dict)
+ emitted_tool_ids: set[str] = field(default_factory=set)
+ emitted_text: bool = False
+ status: str = "done"
+ error: str | None = None
+ usage: dict[str, int] = field(default_factory=dict)
+ cost_usd: float | None = None
+ result_text: str = ""
+ #: The turn's ``result`` line arrived — stdin may close, the CLI exits.
+ saw_result: bool = False
+
+
+def _claude_request_summary(tool_name: str, tool_input: dict[str, Any]) -> str:
+ for key in ("command", "file_path", "path", "pattern", "url", "query", "description"):
+ val = tool_input.get(key)
+ if isinstance(val, str) and val.strip():
+ return val.strip().splitlines()[0][:200]
+ return tool_name
+
+
+def _content_text(content: Any) -> str:
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ parts: list[str] = []
+ for block in content:
+ if isinstance(block, dict):
+ if block.get("type") == "text":
+ parts.append(str(block.get("text") or ""))
+ elif "text" in block:
+ parts.append(str(block.get("text") or ""))
+ elif isinstance(block, str):
+ parts.append(block)
+ return "\n".join(p for p in parts if p)
+ return "" if content is None else str(content)
+
+
+def translate_claude_line(obj: dict[str, Any], st: _ClaudeState) -> list[dict[str, Any]]:
+ """One Claude-shaped NDJSON object -> zero or more agent-chat events."""
+ out: list[dict[str, Any]] = []
+ kind = str(obj.get("type") or "")
+ sid = obj.get("session_id") or obj.get("conversation_id")
+ if sid and not st.vendor_session:
+ st.vendor_session = str(sid)
+
+ if kind == "system":
+ return out # init / hooks / status — nothing the timeline shows
+
+ if kind == "stream_event":
+ ev = obj.get("event") or {}
+ et = ev.get("type")
+ if et == "message_start":
+ mid = ((ev.get("message") or {}).get("id")) or uuid.uuid4().hex
+ st.current_message_id = str(mid)
+ elif et == "content_block_start":
+ block = ev.get("content_block") or {}
+ if block.get("type") == "thinking":
+ mid = st.current_message_id or uuid.uuid4().hex
+ st.current_message_id = mid
+ st.thinking_started.setdefault(mid, time.perf_counter())
+ elif et == "content_block_delta":
+ delta = ev.get("delta") or {}
+ mid = st.current_message_id or uuid.uuid4().hex
+ st.current_message_id = mid
+ if delta.get("type") == "text_delta" and delta.get("text"):
+ out.append(
+ make_event(
+ "text_delta",
+ {"turn_id": st.turn_id, "message_id": mid, "text": delta["text"]},
+ )
+ )
+ elif delta.get("type") == "thinking_delta" and delta.get("thinking"):
+ st.thinking_started.setdefault(mid, time.perf_counter())
+ out.append(
+ make_event(
+ "reasoning_delta",
+ {"turn_id": st.turn_id, "message_id": mid, "text": delta["thinking"]},
+ )
+ )
+ return out
+
+ if kind == "assistant":
+ message = obj.get("message") or {}
+ mid = str(message.get("id") or st.current_message_id or uuid.uuid4().hex)
+ st.current_message_id = mid
+ content = message.get("content") or []
+ if not isinstance(content, list):
+ content = [{"type": "text", "text": str(content)}]
+ text_blocks = [b for b in content if isinstance(b, dict) and b.get("type") == "text"]
+ snapshot = len(content) > 1
+ for block in content:
+ if not isinstance(block, dict):
+ continue
+ btype = block.get("type")
+ if btype == "thinking":
+ thought = str(block.get("thinking") or "")
+ if snapshot:
+ st.thinking_acc[mid] = thought
+ else:
+ st.thinking_acc[mid] = st.thinking_acc.get(mid, "") + thought
+ started = st.thinking_started.get(mid)
+ out.append(
+ make_event(
+ "reasoning",
+ {
+ "turn_id": st.turn_id,
+ "message_id": mid,
+ "text": st.thinking_acc[mid],
+ "duration_ms": int((time.perf_counter() - started) * 1000)
+ if started
+ else None,
+ },
+ )
+ )
+ elif btype == "tool_use":
+ call_id = str(block.get("id") or uuid.uuid4().hex)
+ if call_id in st.emitted_tool_ids:
+ continue
+ st.emitted_tool_ids.add(call_id)
+ name = str(block.get("name") or "tool")
+ args = block.get("input") or {}
+ out.append(
+ make_event(
+ "tool_call",
+ {
+ "turn_id": st.turn_id,
+ "call_id": call_id,
+ "name": name,
+ "input": args if isinstance(args, dict) else {"input": args},
+ "summary": _cli_tool_summary(name, args),
+ },
+ )
+ )
+ if text_blocks:
+ joined = "".join(str(b.get("text") or "") for b in text_blocks)
+ if snapshot:
+ st.text_acc[mid] = joined
+ else:
+ st.text_acc[mid] = st.text_acc.get(mid, "") + joined
+ if st.text_acc[mid].strip():
+ st.emitted_text = True
+ out.append(
+ make_event(
+ "assistant_text",
+ {"turn_id": st.turn_id, "message_id": mid, "text": st.text_acc[mid]},
+ )
+ )
+ return out
+
+ if kind == "user":
+ message = obj.get("message") or {}
+ content = message.get("content") or []
+ if isinstance(content, list):
+ for block in content:
+ if isinstance(block, dict) and block.get("type") == "tool_result":
+ out.append(
+ make_event(
+ "tool_result",
+ {
+ "turn_id": st.turn_id,
+ "call_id": str(block.get("tool_use_id") or ""),
+ "output": _content_text(block.get("content")),
+ "is_error": bool(block.get("is_error")),
+ "duration_ms": None,
+ },
+ )
+ )
+ return out
+
+ if kind == "result":
+ st.saw_result = True
+ st.result_text = str(obj.get("result") or "")
+ if obj.get("is_error"):
+ st.status = "error"
+ errors = obj.get("errors")
+ detail = "; ".join(str(e) for e in errors if e) if isinstance(errors, list) else ""
+ st.error = st.result_text or detail or str(obj.get("subtype") or "error")
+ usage = obj.get("usage") or {}
+ if isinstance(usage, dict):
+ for k in (
+ "input_tokens",
+ "output_tokens",
+ "cache_read_input_tokens",
+ "cache_creation_input_tokens",
+ ):
+ if isinstance(usage.get(k), int | float):
+ st.usage[k] = int(usage[k])
+ details = usage.get("output_tokens_details")
+ if isinstance(details, dict) and isinstance(
+ details.get("thinking_tokens"), int | float
+ ):
+ st.usage["thinking_tokens"] = int(details["thinking_tokens"])
+ cost = obj.get("total_cost_usd", obj.get("cost_usd"))
+ if isinstance(cost, int | float):
+ st.cost_usd = float(cost)
+ return out
+
+ return out
+
+
+def _cli_tool_summary(name: str, args: Any) -> str:
+ if not isinstance(args, dict):
+ return ""
+ for key in ("command", "file_path", "path", "pattern", "query", "url", "description"):
+ val = args.get(key)
+ if isinstance(val, str) and val.strip():
+ return val.strip().splitlines()[0][:200]
+ return ""
+
+
+@dataclass(slots=True)
+class _CodexState:
+ turn_id: str
+ vendor_session: str | None = None
+ status: str = "done"
+ error: str | None = None
+ usage: dict[str, int] = field(default_factory=dict)
+ emitted_text: bool = False
+ #: item id -> (call_id, name) for items that became tool calls
+ items: dict[str, tuple[str, str]] = field(default_factory=dict)
+ started_at: dict[str, float] = field(default_factory=dict)
+ #: The last top-level ``error`` notification (retryable until turn.failed).
+ last_error: str | None = None
+
+
+def translate_codex_line(obj: dict[str, Any], st: _CodexState) -> list[dict[str, Any]]:
+ out: list[dict[str, Any]] = []
+ kind = str(obj.get("type") or "")
+ if kind == "thread.started":
+ tid = obj.get("thread_id")
+ if tid:
+ st.vendor_session = str(tid)
+ return out
+ if kind == "turn.completed":
+ usage = obj.get("usage") or {}
+ if isinstance(usage, dict):
+ for k in (
+ "input_tokens",
+ "output_tokens",
+ "cached_input_tokens",
+ "cache_write_input_tokens",
+ "reasoning_output_tokens",
+ ):
+ if isinstance(usage.get(k), int | float):
+ st.usage[k] = int(usage[k])
+ # A completed turn wins over a retryable error seen on the way.
+ st.status = "done"
+ st.error = None
+ return out
+ if kind == "turn.failed":
+ st.status = "error"
+ err = obj.get("error")
+ st.error = (
+ str(err.get("message") or err)
+ if isinstance(err, dict)
+ else str(err or st.last_error or "turn failed")
+ )
+ return out
+ if kind == "error":
+ # A server notification — may be retried by the CLI; remembered, and
+ # only terminal when no turn.completed follows (exit code decides).
+ st.last_error = str(obj.get("message") or "error")
+ return out
+ if not kind.startswith("item."):
+ return out
+
+ item = obj.get("item") or {}
+ item_id = str(item.get("id") or uuid.uuid4().hex)
+ itype = str(item.get("type") or "")
+ phase = kind.split(".", 1)[1] # started | updated | completed
+
+ if itype == "agent_message":
+ text = str(item.get("text") or "")
+ if phase == "completed" and text.strip():
+ st.emitted_text = True
+ out.append(
+ make_event(
+ "assistant_text",
+ {"turn_id": st.turn_id, "message_id": item_id, "text": text},
+ )
+ )
+ return out
+ if itype == "reasoning":
+ text = str(item.get("text") or "")
+ if phase == "completed" and text.strip():
+ out.append(
+ make_event(
+ "reasoning",
+ {
+ "turn_id": st.turn_id,
+ "message_id": item_id,
+ "text": text,
+ "duration_ms": None,
+ },
+ )
+ )
+ return out
+ if itype in {"command_execution", "file_change", "mcp_tool_call", "web_search"}:
+ if itype == "command_execution":
+ name, args = "RunCommand", {"command": str(item.get("command") or "")}
+ summary = args["command"].splitlines()[0][:200] if args["command"] else ""
+ elif itype == "file_change":
+ changes = item.get("changes") or []
+ paths = [str(c.get("path") or "") for c in changes if isinstance(c, dict)]
+ name, args = "Edit", {"changes": changes}
+ summary = ", ".join(p for p in paths if p)[:200]
+ elif itype == "mcp_tool_call":
+ name = str(item.get("tool") or item.get("server") or "mcp")
+ args = item.get("arguments") or {}
+ summary = str(item.get("server") or "")
+ else:
+ name, args = "WebSearch", {"query": str(item.get("query") or "")}
+ summary = args["query"]
+ if item_id not in st.items:
+ st.items[item_id] = (item_id, name)
+ st.started_at[item_id] = time.perf_counter()
+ out.append(
+ make_event(
+ "tool_call",
+ {
+ "turn_id": st.turn_id,
+ "call_id": item_id,
+ "name": name,
+ "input": args if isinstance(args, dict) else {"input": args},
+ "summary": summary,
+ },
+ )
+ )
+ if phase == "completed":
+ if itype == "command_execution":
+ output = str(item.get("aggregated_output") or "")
+ code = item.get("exit_code")
+ if code is not None:
+ output = (output.rstrip() + f"\n[exit {code}]").strip()
+ item_status = str(item.get("status") or "")
+ is_error = bool(code) or item_status in {"failed", "declined"}
+ if item_status == "declined":
+ output = (output.rstrip() + "\n[declined by the sandbox / policy]").strip()
+ elif itype == "file_change":
+ output = "\n".join(
+ f"{c.get('kind', 'edit')}: {c.get('path', '')}"
+ for c in (item.get("changes") or [])
+ if isinstance(c, dict)
+ )
+ is_error = str(item.get("status") or "") == "failed"
+ elif itype == "mcp_tool_call":
+ output = json.dumps(
+ item.get("result") or item.get("error") or {}, ensure_ascii=False
+ )
+ is_error = bool(item.get("error"))
+ else:
+ output = "done"
+ is_error = False
+ started = st.started_at.get(item_id)
+ out.append(
+ make_event(
+ "tool_result",
+ {
+ "turn_id": st.turn_id,
+ "call_id": item_id,
+ "output": output,
+ "is_error": is_error,
+ "duration_ms": int((time.perf_counter() - started) * 1000)
+ if started
+ else None,
+ },
+ )
+ )
+ return out
+ if itype == "error":
+ # NOT a failed turn: Codex files warnings here (skills budget, hook
+ # clamps, model reroutes) in every run. Remembered for the error text
+ # should the turn fail without a message of its own.
+ st.last_error = str(item.get("message") or "error")
+ return out
+
+
+# ------------------------------------------------------------ agy translation
+
+
+@dataclass(slots=True)
+class _AgyState:
+ turn_id: str
+ vendor_session: str | None = None
+ status: str = "done"
+ error: str | None = None
+ usage: dict[str, int] = field(default_factory=dict)
+ emitted_text: bool = False
+ result_text: str = ""
+ #: step_index -> wall-clock start, for tool durations
+ started_at: dict[int, float] = field(default_factory=dict)
+ #: step_index of tool steps already announced
+ tool_steps: set[int] = field(default_factory=set)
+ #: text per agent_response step (a DONE step repeats its last delta)
+ text_acc: dict[int, str] = field(default_factory=dict)
+
+
+_AGY_TOOL_SUMMARY_KEYS: Final[tuple[str, ...]] = (
+ "CommandLine",
+ "AbsolutePath",
+ "TargetFile",
+ "Pattern",
+ "SearchDirectory",
+ "DirectoryPath",
+ "Query",
+ "Url",
+)
+
+
+def _agy_summary(params: Any) -> str:
+ if not isinstance(params, dict):
+ return ""
+ for key in _AGY_TOOL_SUMMARY_KEYS:
+ val = params.get(key)
+ if isinstance(val, str) and val.strip():
+ return val.strip().splitlines()[0][:200]
+ first = next((v for v in params.values() if isinstance(v, str) and v.strip()), "")
+ return first.splitlines()[0][:200] if first else ""
+
+
+def translate_agy_line(obj: dict[str, Any], st: _AgyState) -> list[dict[str, Any]]:
+ """One ``agy --output-format stream-json`` object -> agent-chat events.
+
+ Shape (agy 1.1.19): ``{"event": "init" | "step_update" | "result", ...}``.
+ A ``step_update`` carries ``step_index``, ``state`` (ACTIVE / DONE /
+ ERROR / ...), ``step_type`` (``agent_response`` with ``text_delta``;
+ ``tool`` with ``tool_name`` + ``tool_info{name, parameters, output?,
+ error?}``) and, on DONE, ``duration_seconds`` + ``usage``. The final
+ ``result`` carries ``status`` (SUCCESS / ERROR / CANCELED / ...),
+ ``response``, ``error`` and the conversation id.
+ """
+ out: list[dict[str, Any]] = []
+ kind = str(obj.get("event") or "")
+ if kind == "init":
+ cid = obj.get("conversation_id")
+ if cid:
+ st.vendor_session = str(cid)
+ return out
+
+ if kind == "step_update":
+ su = obj.get("step_update") or {}
+ if not isinstance(su, dict):
+ return out
+ cid = su.get("conversation_id")
+ if cid and not st.vendor_session:
+ st.vendor_session = str(cid)
+ try:
+ idx = int(su.get("step_index") or 0)
+ except (TypeError, ValueError):
+ idx = 0
+ state = str(su.get("state") or "")
+ stype = str(su.get("step_type") or "")
+
+ if stype == "agent_response":
+ delta = str(su.get("text_delta") or "")
+ if delta:
+ acc = st.text_acc.get(idx, "")
+ # The DONE step repeats the last delta — do not double it.
+ if state == "DONE" and acc.endswith(delta):
+ delta = ""
+ if delta:
+ st.text_acc[idx] = st.text_acc.get(idx, "") + delta
+ st.emitted_text = True
+ out.append(
+ make_event(
+ "text_delta",
+ {"turn_id": st.turn_id, "message_id": f"agy-{idx}", "text": delta},
+ )
+ )
+ if state in {"DONE", "ERROR"} and st.text_acc.get(idx, "").strip():
+ out.append(
+ make_event(
+ "assistant_text",
+ {
+ "turn_id": st.turn_id,
+ "message_id": f"agy-{idx}",
+ "text": st.text_acc[idx],
+ },
+ )
+ )
+ return out
+
+ if stype == "tool":
+ info = su.get("tool_info") if isinstance(su.get("tool_info"), dict) else {}
+ name = str(su.get("tool_name") or info.get("name") or "tool")
+ params = info.get("parameters") if isinstance(info, dict) else None
+ call_id = f"agy-step-{idx}"
+ if idx not in st.tool_steps:
+ st.tool_steps.add(idx)
+ st.started_at[idx] = time.perf_counter()
+ out.append(
+ make_event(
+ "tool_call",
+ {
+ "turn_id": st.turn_id,
+ "call_id": call_id,
+ "name": name,
+ "input": params if isinstance(params, dict) else {"input": params},
+ "summary": _agy_summary(params),
+ },
+ )
+ )
+ if state in {"DONE", "ERROR", "CANCELED", "INVALID", "HALTED"}:
+ err = info.get("error") if isinstance(info, dict) else None
+ err_text = (
+ str(err.get("message") or err) if isinstance(err, dict) else str(err or "")
+ )
+ output = str(info.get("output") or "") if isinstance(info, dict) else ""
+ is_error = state != "DONE" or bool(err_text)
+ if is_error and err_text:
+ output = (output.rstrip() + ("\n" if output else "") + err_text).strip()
+ dur = su.get("duration_seconds")
+ started = st.started_at.get(idx)
+ duration_ms = (
+ int(float(dur) * 1000)
+ if isinstance(dur, int | float)
+ else int((time.perf_counter() - started) * 1000)
+ if started
+ else None
+ )
+ out.append(
+ make_event(
+ "tool_result",
+ {
+ "turn_id": st.turn_id,
+ "call_id": call_id,
+ "output": output or ("done" if not is_error else "failed"),
+ "is_error": is_error,
+ "duration_ms": duration_ms,
+ },
+ )
+ )
+ return out
+ return out
+
+ if kind == "result":
+ res = obj.get("result") if isinstance(obj.get("result"), dict) else obj
+ cid = res.get("conversation_id")
+ if cid:
+ st.vendor_session = str(cid)
+ status = str(res.get("status") or "SUCCESS").upper()
+ st.result_text = str(res.get("response") or "")
+ usage = res.get("usage") or {}
+ if isinstance(usage, dict):
+ for k in (
+ "input_tokens",
+ "output_tokens",
+ "thinking_tokens",
+ "cache_read_tokens",
+ "total_tokens",
+ ):
+ if isinstance(usage.get(k), int | float):
+ st.usage[k] = int(usage[k])
+ if status == "SUCCESS":
+ st.status = "done"
+ elif status in {"CANCELED", "INTERRUPTED"}:
+ st.status = "error"
+ st.error = str(res.get("error") or f"agy stopped the turn ({status.lower()})")
+ else:
+ st.status = "error"
+ st.error = str(res.get("error") or f"agy reported {status}")
+ return out
+ return out
+
+
+# ------------------------------------------------------------ the turn
+
+
+@dataclass(slots=True)
+class _Outcome:
+ status: str
+ error: str | None
+ usage: dict[str, int]
+ cost_usd: float | None
+ vendor_session: str | None
+
+
+# Error text the CLIs print when the conversation we try to resume is gone
+# (a fresh install, a pruned session store, a first turn that died before
+# the CLI wrote anything). The turn is then re-run once without resume.
+_RESUME_LOST_MARKERS: Final[tuple[str, ...]] = (
+ "no conversation found",
+ "session not found",
+ "no session found",
+ "could not find session",
+ "unknown session",
+ "not found: ",
+ "does not exist",
+)
+
+
+def _resume_was_lost(error: str | None) -> bool:
+ low = (error or "").lower()
+ return any(m in low for m in _RESUME_LOST_MARKERS)
+
+
+async def run_cli_turn(handle: TurnHandle, user_text: str, runner: str) -> str | None:
+ """Run one CLI turn. Returns the vendor session id to persist (or None).
+
+ A resume the CLI no longer knows is retried once as a fresh conversation
+ (the person keeps typing; only the CLI-side memory is gone, the timeline
+ here is intact).
+ """
+ t0 = time.perf_counter()
+ outcome = await _run_cli_once(handle, user_text, runner, handle.session.vendor_session)
+ # agy answers a lost conversation id with a NEW conversation and exit 0
+ # (only a stderr warning) — the id that came back is the truth.
+ if (
+ outcome.status == "error"
+ and handle.session.vendor_session
+ and _resume_was_lost(outcome.error)
+ and not handle.cancel.is_set()
+ ):
+ log.info("agent chat %s: resume lost (%s) — starting fresh", handle.turn_id, outcome.error)
+ outcome = await _run_cli_once(handle, user_text, runner, None)
+ await handle.emit(
+ make_event(
+ "turn_finished",
+ {
+ "turn_id": handle.turn_id,
+ "status": outcome.status,
+ "duration_ms": int((time.perf_counter() - t0) * 1000),
+ "usage": outcome.usage,
+ "error": outcome.error,
+ "cost_usd": outcome.cost_usd,
+ },
+ )
+ )
+ return outcome.vendor_session
+
+
+async def _run_cli_once(
+ handle: TurnHandle, user_text: str, runner: str, resume: str | None
+) -> _Outcome:
+ session = handle.session
+ cwd = Path(session.cwd or Path.home())
+ effort = normalize_effort(session.provider, session.effort)
+ planner = _PLANNERS[runner]
+ status = "done"
+ error_text: str | None = None
+ usage: dict[str, int] = {}
+ cost_usd: float | None = None
+ vendor_session: str | None = None
+
+ try:
+ plan: CliPlan = planner(
+ prompt=user_text,
+ cwd=cwd,
+ model=session.model,
+ effort=effort,
+ permission_mode=session.permission_mode,
+ resume=resume,
+ )
+ except CliUnavailable as exc:
+ return _Outcome("error", str(exc), {}, None, None)
+
+ vendor_session = plan.vendor_session
+ log.info("agent chat %s: %s argv=%s", handle.turn_id, runner, plan.argv[:6])
+ try:
+ proc = await asyncio.create_subprocess_exec(
+ *plan.argv,
+ cwd=str(cwd),
+ env=plan.env,
+ stdin=asyncio.subprocess.PIPE
+ if plan.stdin_text is not None
+ else asyncio.subprocess.DEVNULL,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ limit=_READLINE_LIMIT,
+ )
+ except (OSError, ValueError) as exc:
+ return _Outcome("error", f"Could not start {runner}: {exc}", {}, None, None)
+
+ claude_state = _ClaudeState(turn_id=handle.turn_id, vendor_session=vendor_session)
+ codex_state = _CodexState(turn_id=handle.turn_id, vendor_session=vendor_session)
+ agy_state = _AgyState(turn_id=handle.turn_id, vendor_session=vendor_session)
+ stderr_tail: list[str] = []
+
+ async def _drain_stderr() -> None:
+ assert proc.stderr is not None
+ while True:
+ line = await proc.stderr.readline()
+ if not line:
+ return
+ text = line.decode("utf-8", errors="replace").rstrip()
+ if text:
+ stderr_tail.append(text)
+ del stderr_tail[:-40]
+
+ async def _pump_stdout() -> None:
+ assert proc.stdout is not None
+ while True:
+ raw = await proc.stdout.readline()
+ if not raw:
+ return
+ line = raw.decode("utf-8", errors="replace").strip()
+ if not line:
+ continue
+ try:
+ obj = json.loads(line)
+ except ValueError:
+ # A plain-text line (agy without JSON, a banner): show it.
+ await handle.emit(
+ make_event(
+ "text_delta",
+ {
+ "turn_id": handle.turn_id,
+ "message_id": f"plain-{handle.turn_id}",
+ "text": line + "\n",
+ },
+ )
+ )
+ claude_state.text_acc[f"plain-{handle.turn_id}"] = (
+ claude_state.text_acc.get(f"plain-{handle.turn_id}", "") + line + "\n"
+ )
+ continue
+ if not isinstance(obj, dict):
+ continue
+ if plan.shape == "codex":
+ events = translate_codex_line(obj, codex_state)
+ elif plan.shape == "agy":
+ events = translate_agy_line(obj, agy_state)
+ else:
+ if obj.get("type") == "control_request":
+ await _answer_control_request(obj)
+ continue
+ events = translate_claude_line(obj, claude_state)
+ for ev in events:
+ await handle.emit(ev)
+ if plan.keep_stdin and claude_state.saw_result:
+ # The turn is over; closing stdin lets the CLI exit.
+ _close_stdin()
+
+ def _close_stdin() -> None:
+ if proc.stdin is None or proc.stdin.is_closing():
+ return
+ try:
+ proc.stdin.close()
+ except OSError as exc:
+ log.debug("agent chat %s: stdin close failed: %s", handle.turn_id, exc)
+
+ async def _write_stdin(text: str) -> None:
+ if proc.stdin is None or proc.stdin.is_closing():
+ return
+ try:
+ proc.stdin.write(text.encode("utf-8"))
+ await proc.stdin.drain()
+ except (BrokenPipeError, ConnectionResetError, OSError) as exc:
+ log.debug("agent chat %s: stdin write failed: %s", handle.turn_id, exc)
+
+ async def _answer_control_request(obj: dict[str, Any]) -> None:
+ """A Claude Code ``control_request`` — a permission prompt — answered
+ from the chat's approval card. Anything that is not ``can_use_tool``
+ is declined (the CLI asks nothing else of a stdio prompt tool today)."""
+ request_id = str(obj.get("request_id") or "")
+ req = obj.get("request") if isinstance(obj.get("request"), dict) else {}
+ subtype = str(req.get("subtype") or "")
+ decision = "deny"
+ message = "Not supported by this chat."
+ if subtype == "can_use_tool":
+ tool_name = str(req.get("tool_name") or req.get("display_name") or "tool")
+ tool_input = req.get("input") if isinstance(req.get("input"), dict) else {}
+ call_id = str(req.get("tool_use_id") or uuid.uuid4().hex)
+ summary = str(req.get("description") or "") or _claude_request_summary(
+ tool_name, tool_input
+ )
+ # The card sits on the tool row the assistant line announced; a
+ # plan's ExitPlanMode has no row yet, so it gets one here.
+ if tool_name == "ExitPlanMode" and call_id not in claude_state.emitted_tool_ids:
+ claude_state.emitted_tool_ids.add(call_id)
+ await handle.emit(
+ make_event(
+ "tool_call",
+ {
+ "turn_id": handle.turn_id,
+ "call_id": call_id,
+ "name": tool_name,
+ "input": tool_input,
+ "summary": "Plan ready — approve to start building",
+ },
+ )
+ )
+ summary = "Plan ready — approve to start building"
+ decision = await handle.request_approval(call_id, tool_name, tool_input, summary)
+ message = (
+ "The person declined this action."
+ if decision == "deny"
+ else "The turn was stopped."
+ )
+ if decision in {"allow", "allow_always"}:
+ body: dict[str, Any] = {"behavior": "allow", "updatedInput": req.get("input") or {}}
+ else:
+ body = {"behavior": "deny", "message": message}
+ frame = {
+ "type": "control_response",
+ "response": {"subtype": "success", "request_id": request_id, "response": body},
+ }
+ await _write_stdin(json.dumps(frame, ensure_ascii=False) + "\n")
+
+ async def _feed_stdin() -> None:
+ if proc.stdin is None:
+ return
+ try:
+ if plan.stdin_text is not None:
+ proc.stdin.write(plan.stdin_text.encode("utf-8"))
+ await proc.stdin.drain()
+ except (BrokenPipeError, ConnectionResetError, OSError) as exc:
+ log.debug("agent chat %s: stdin closed early: %s", handle.turn_id, exc)
+ finally:
+ # A CLI that talks back on stdin keeps it until its result line.
+ if not plan.keep_stdin:
+ _close_stdin()
+
+ async def _watch_cancel() -> None:
+ await handle.cancel.wait()
+ _kill(proc)
+
+ pump = asyncio.create_task(_pump_stdout())
+ drain = asyncio.create_task(_drain_stderr())
+ feeder = asyncio.create_task(_feed_stdin())
+ watcher = asyncio.create_task(_watch_cancel())
+ try:
+ await asyncio.wait_for(asyncio.gather(pump, drain, feeder), timeout=_TURN_TIMEOUT_S)
+ await proc.wait()
+ except TimeoutError:
+ _kill(proc)
+ status = "error"
+ error_text = f"{runner} did not finish within {int(_TURN_TIMEOUT_S)} s."
+ except asyncio.CancelledError:
+ _kill(proc)
+ raise
+ finally:
+ watcher.cancel()
+ for task in (pump, drain, feeder):
+ if not task.done():
+ task.cancel()
+
+ shape_state: Any = (
+ codex_state if plan.shape == "codex" else agy_state if plan.shape == "agy" else claude_state
+ )
+ if handle.cancel.is_set():
+ status = "cancelled"
+ elif status == "done":
+ st_status = shape_state.status
+ st_error = shape_state.error
+ if st_status == "error":
+ status, error_text = "error", st_error
+ elif proc.returncode not in (0, None):
+ status = "error"
+ error_text = (
+ st_error
+ or getattr(shape_state, "last_error", None)
+ or "\n".join(stderr_tail[-8:]).strip()
+ or f"{runner} exited with code {proc.returncode}."
+ )
+
+ if plan.shape == "codex":
+ usage = codex_state.usage
+ vendor_session = codex_state.vendor_session or vendor_session
+ emitted_text = codex_state.emitted_text
+ plain_tail = ""
+ elif plan.shape == "agy":
+ usage = agy_state.usage
+ vendor_session = agy_state.vendor_session or vendor_session
+ emitted_text = agy_state.emitted_text
+ plain_tail = claude_state.text_acc.get(f"plain-{handle.turn_id}", "")
+ if not emitted_text and agy_state.result_text.strip():
+ emitted_text = True
+ await handle.emit(
+ make_event(
+ "assistant_text",
+ {
+ "turn_id": handle.turn_id,
+ "message_id": f"result-{handle.turn_id}",
+ "text": agy_state.result_text,
+ },
+ )
+ )
+ else:
+ usage = claude_state.usage
+ cost_usd = claude_state.cost_usd
+ vendor_session = claude_state.vendor_session or vendor_session
+ emitted_text = claude_state.emitted_text
+ plain_tail = claude_state.text_acc.get(f"plain-{handle.turn_id}", "")
+ if not emitted_text and claude_state.result_text.strip():
+ emitted_text = True
+ await handle.emit(
+ make_event(
+ "assistant_text",
+ {
+ "turn_id": handle.turn_id,
+ "message_id": f"result-{handle.turn_id}",
+ "text": claude_state.result_text,
+ },
+ )
+ )
+ if not emitted_text and plain_tail.strip():
+ await handle.emit(
+ make_event(
+ "assistant_text",
+ {
+ "turn_id": handle.turn_id,
+ "message_id": f"plain-{handle.turn_id}",
+ "text": plain_tail.strip(),
+ },
+ )
+ )
+
+ return _Outcome(status, error_text, usage, cost_usd, vendor_session)
+
+
+def _kill(proc: asyncio.subprocess.Process) -> None:
+ if proc.returncode is not None:
+ return
+ try:
+ proc.kill()
+ except (ProcessLookupError, OSError) as exc:
+ log.debug("agent chat: killing the CLI failed: %s", exc)
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
new file mode 100644
index 0000000000..fdbce29041
--- /dev/null
+++ b/jarvis/agent_chat/service.py
@@ -0,0 +1,359 @@
+"""Sessions in flight: who is running, who is listening, who is waiting.
+
+:class:`AgentChatService` is the one object the routes talk to. It owns the
+store, keeps at most ONE running turn per session, fans every event out to
+the session's live subscribers (the WebSocket handlers) after persisting it,
+and parks a turn on an ``asyncio.Future`` while the person decides on an
+approval card. Cancel sets the turn's event and awaits the task; a runner
+that is mid-tool or mid-stream ends at the next boundary (the API loop
+between deltas, the CLI by killing the child).
+
+The runner is picked per turn from the provider row: a CLI-backed provider
+uses :mod:`runner_cli`; ``claude-api`` uses the CLI when the ``claude``
+binary is on PATH and the API otherwise; everything else uses
+:mod:`runner_api`. The choice is recorded in ``turn_started`` so the
+timeline can say what answered.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import shutil
+import uuid
+from collections.abc import Callable
+from pathlib import Path
+from typing import Any
+
+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 normalize_permission
+from jarvis.agent_chat.runner_api import TurnHandle, run_api_turn, supports_api_runner
+from jarvis.agent_chat.runner_cli import run_cli_turn, supports_cli_runner
+from jarvis.agent_chat.store import AgentChatSession, AgentChatStore
+
+log = logging.getLogger(__name__)
+
+Subscriber = asyncio.Queue[dict[str, Any]]
+DECISIONS: tuple[str, ...] = ("allow", "allow_always", "deny")
+
+
+class SessionBusy(RuntimeError):
+ """A turn is already running in this session."""
+
+
+class NoSuchSession(KeyError):
+ pass
+
+
+def resolve_runner(provider: str) -> str:
+ """Which runner answers for ``provider`` on this machine, right now.
+
+ ``claude-api`` is dual: Claude Code (the CLI) when it is installed — that
+ is the subscription path and the one with the CLI's own tools — else the
+ Anthropic API in the in-process loop. Every other provider row names its
+ runner outright.
+ """
+ row = provider_row(provider)
+ if row is None:
+ return "api" if supports_api_runner(provider) else "unknown"
+ if row.id == "claude-api":
+ if shutil.which("claude") or shutil.which("claude.cmd") or shutil.which("claude.exe"):
+ return "claude-cli"
+ return "api"
+ return row.runner
+
+
+class _Running:
+ __slots__ = ("task", "cancel", "turn_id")
+
+ def __init__(self, turn_id: str, cancel: asyncio.Event) -> None:
+ self.turn_id = turn_id
+ self.cancel = cancel
+ self.task: asyncio.Task[None] | None = None
+
+
+class AgentChatService:
+ def __init__(
+ self,
+ store: AgentChatStore,
+ *,
+ assistant_name: Callable[[], str] | None = None,
+ default_cwd: Callable[[], str] | None = None,
+ ) -> None:
+ self.store = store
+ self._assistant_name = assistant_name or (lambda: "Jarvis")
+ self._default_cwd = default_cwd or (lambda: str(Path.home()))
+ self._running: dict[str, _Running] = {}
+ self._subscribers: dict[str, set[Subscriber]] = {}
+ self._approvals: dict[str, asyncio.Future[str]] = {}
+ self._approval_session: dict[str, str] = {}
+
+ # ------------------------------------------------------------ sessions
+
+ def default_cwd(self) -> str:
+ return self._default_cwd()
+
+ def create_session(
+ self,
+ *,
+ provider: str,
+ model: str = "",
+ effort: str | None = None,
+ cwd: str | None = None,
+ permission_mode: str = "",
+ title: str = "",
+ ) -> AgentChatSession:
+ row = provider_row(provider)
+ if row is None and not supports_api_runner(provider):
+ raise ValueError(f"Unknown agent-chat provider: {provider!r}")
+ permission_mode = normalize_permission(resolve_runner(provider), permission_mode)
+ eff = normalize_effort(provider, effort) if effort is not None else ""
+ if effort is None:
+ from jarvis.agent_chat.effort import default_effort
+
+ eff = default_effort(provider)
+ return self.store.create_session(
+ provider=provider,
+ model=model or (row.default_model if row else ""),
+ effort=eff,
+ cwd=cwd or self.default_cwd(),
+ permission_mode=permission_mode,
+ title=title,
+ )
+
+ def is_running(self, session_id: str) -> bool:
+ run = self._running.get(session_id)
+ return bool(run and run.task and not run.task.done())
+
+ def pending_approvals(self, session_id: str) -> list[str]:
+ return [aid for aid, sid in self._approval_session.items() if sid == session_id]
+
+ # ----------------------------------------------------------- subscribe
+
+ def subscribe(self, session_id: str) -> Subscriber:
+ q: Subscriber = asyncio.Queue(maxsize=4096)
+ self._subscribers.setdefault(session_id, set()).add(q)
+ return q
+
+ def unsubscribe(self, session_id: str, q: Subscriber) -> None:
+ subs = self._subscribers.get(session_id)
+ if subs is None:
+ return
+ subs.discard(q)
+ if not subs:
+ self._subscribers.pop(session_id, None)
+
+ async def _emit(self, session_id: str, event: dict[str, Any]) -> None:
+ stored = self.store.append_event(session_id, event)
+ for q in list(self._subscribers.get(session_id, ())):
+ try:
+ q.put_nowait(stored)
+ except asyncio.QueueFull:
+ # A reader that stopped draining is dropped: the WS handler
+ # re-syncs from the store when it reconnects.
+ log.debug("agent chat: subscriber queue full for %s — dropping it", session_id)
+ self.unsubscribe(session_id, q)
+
+ # ---------------------------------------------------------------- turns
+
+ async def send(self, session_id: str, text: str) -> str:
+ """Persist the person's message and start the turn. Returns turn_id."""
+ session = self.store.get_session(session_id)
+ if session is None:
+ raise NoSuchSession(session_id)
+ if self.is_running(session_id):
+ raise SessionBusy(session_id)
+ text = text.strip()
+ if not text:
+ raise ValueError("empty message")
+
+ turn_id = uuid.uuid4().hex
+ cancel = asyncio.Event()
+ run = _Running(turn_id, cancel)
+ self._running[session_id] = run
+
+ history = self.store.list_events(session_id)
+ await self._emit(session_id, make_event("user_message", {"text": text}))
+ runner = resolve_runner(session.provider)
+ await self._emit(
+ session_id,
+ make_event(
+ "turn_started",
+ {
+ "turn_id": turn_id,
+ "provider": session.provider,
+ "model": session.model,
+ "effort": normalize_effort(session.provider, session.effort),
+ "runner": runner,
+ },
+ ),
+ )
+
+ handle = TurnHandle(
+ session=session,
+ turn_id=turn_id,
+ emit=lambda ev: self._emit(session_id, ev),
+ request_approval=lambda call_id, name, args, summary: self._ask(
+ session_id, turn_id, call_id, name, args, summary
+ ),
+ cancel=cancel,
+ history=history,
+ assistant_name=self._assistant_name(),
+ )
+
+ async def _body() -> None:
+ try:
+ if 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)
+ elif runner == "api" and supports_api_runner(session.provider):
+ await run_api_turn(handle, text)
+ else:
+ await self._emit(
+ session_id,
+ make_event(
+ "turn_finished",
+ {
+ "turn_id": turn_id,
+ "status": "error",
+ "duration_ms": 0,
+ "usage": {},
+ "error": (
+ f"No runner for provider {session.provider!r} on this "
+ "machine. Connect it under API Keys → Agents."
+ ),
+ },
+ ),
+ )
+ except asyncio.CancelledError:
+ await self._emit(
+ session_id,
+ make_event(
+ "turn_finished",
+ {
+ "turn_id": turn_id,
+ "status": "cancelled",
+ "duration_ms": 0,
+ "usage": {},
+ "error": None,
+ },
+ ),
+ )
+ raise
+ except Exception as exc: # noqa: BLE001 — a runner bug must not leave the UI spinning
+ log.exception("agent chat turn %s crashed", turn_id)
+ await self._emit(
+ session_id,
+ make_event(
+ "turn_finished",
+ {
+ "turn_id": turn_id,
+ "status": "error",
+ "duration_ms": 0,
+ "usage": {},
+ "error": f"{type(exc).__name__}: {exc}",
+ },
+ ),
+ )
+ finally:
+ self._running.pop(session_id, None)
+ for aid in self.pending_approvals(session_id):
+ fut = self._approvals.pop(aid, None)
+ self._approval_session.pop(aid, None)
+ if fut is not None and not fut.done():
+ fut.set_result("cancel")
+
+ run.task = asyncio.create_task(_body(), name=f"agent-chat-{turn_id[:8]}")
+ return turn_id
+
+ async def cancel(self, session_id: str) -> bool:
+ run = self._running.get(session_id)
+ if run is None or run.task is None or run.task.done():
+ return False
+ run.cancel.set()
+ for aid in self.pending_approvals(session_id):
+ fut = self._approvals.get(aid)
+ if fut is not None and not fut.done():
+ fut.set_result("cancel")
+ try:
+ await asyncio.wait_for(asyncio.shield(run.task), timeout=15.0)
+ except TimeoutError:
+ run.task.cancel()
+ except Exception as exc: # noqa: BLE001 — the task reported its own end already
+ log.debug("agent chat cancel: task ended with %s", exc)
+ return True
+
+ async def cancel_all(self) -> None:
+ for sid in list(self._running):
+ await self.cancel(sid)
+
+ # ------------------------------------------------------------ approvals
+
+ async def _ask(
+ self,
+ session_id: str,
+ turn_id: str,
+ call_id: str,
+ name: str,
+ args: dict[str, Any],
+ summary: str,
+ ) -> str:
+ approval_id = uuid.uuid4().hex
+ loop = asyncio.get_running_loop()
+ fut: asyncio.Future[str] = loop.create_future()
+ self._approvals[approval_id] = fut
+ self._approval_session[approval_id] = session_id
+ await self._emit(
+ session_id,
+ make_event(
+ "approval_required",
+ {
+ "turn_id": turn_id,
+ "approval_id": approval_id,
+ "call_id": call_id,
+ "name": name,
+ "input": args,
+ "summary": summary,
+ },
+ ),
+ )
+ try:
+ decision = await fut
+ finally:
+ self._approvals.pop(approval_id, None)
+ self._approval_session.pop(approval_id, None)
+ await self._emit(
+ session_id,
+ make_event(
+ "approval_resolved",
+ {"turn_id": turn_id, "approval_id": approval_id, "decision": decision},
+ ),
+ )
+ if decision == "allow_always":
+ self.store.update_session(session_id, permission_mode="auto")
+ await self._emit(session_id, make_event("session_updated", {"permission_mode": "auto"}))
+ return decision
+
+ def resolve_approval(self, session_id: str, approval_id: str, decision: str) -> bool:
+ if decision not in DECISIONS:
+ raise ValueError(f"decision must be one of {DECISIONS}")
+ if self._approval_session.get(approval_id) != session_id:
+ return False
+ fut = self._approvals.get(approval_id)
+ if fut is None or fut.done():
+ return False
+ fut.set_result(decision)
+ return True
+
+
+__all__ = [
+ "AgentChatService",
+ "DECISIONS",
+ "NoSuchSession",
+ "SessionBusy",
+ "Subscriber",
+ "resolve_runner",
+]
diff --git a/jarvis/agent_chat/store.py b/jarvis/agent_chat/store.py
new file mode 100644
index 0000000000..44b6ca3d5f
--- /dev/null
+++ b/jarvis/agent_chat/store.py
@@ -0,0 +1,285 @@
+"""SQLite persistence for agent-chat sessions.
+
+Mirrors ``jarvis/state/chat_store.py``: one ``sqlite3`` connection in WAL
+mode behind a ``threading.Lock`` (route handlers and the runner share the
+asyncio loop; the lock keeps a future worker-thread caller safe). Two tables:
+
+``agent_chat_sessions``
+ One row per session — title, the provider / model / effort the composer
+ last used in it, the working directory, the permission mode and, for the
+ CLI runners, the vendor's own session id so a later turn can resume it.
+
+``agent_chat_events``
+ The append-only event log (see :mod:`jarvis.agent_chat.events`), ordered
+ by ``seq`` per session. Transient kinds are never written.
+
+Ordering by ``seq`` (our own counter), not by wall clock: Windows ``time()``
+resolution can tie two fast appends.
+"""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+import threading
+import uuid
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any
+
+from jarvis.agent_chat.events import is_transient, now_ms
+
+_SCHEMA = """
+CREATE TABLE IF NOT EXISTS agent_chat_sessions (
+ session_id TEXT PRIMARY KEY,
+ title TEXT NOT NULL DEFAULT '',
+ provider TEXT NOT NULL DEFAULT '',
+ model TEXT NOT NULL DEFAULT '',
+ effort TEXT NOT NULL DEFAULT '',
+ cwd TEXT NOT NULL DEFAULT '',
+ permission_mode TEXT NOT NULL DEFAULT 'ask',
+ vendor_session TEXT,
+ created_ms INTEGER NOT NULL,
+ updated_ms INTEGER NOT NULL,
+ message_count INTEGER NOT NULL DEFAULT 0,
+ preview TEXT NOT NULL DEFAULT ''
+);
+CREATE TABLE IF NOT EXISTS agent_chat_events (
+ session_id TEXT NOT NULL,
+ seq INTEGER NOT NULL,
+ ts_ms INTEGER NOT NULL,
+ kind TEXT NOT NULL,
+ payload TEXT NOT NULL,
+ PRIMARY KEY (session_id, seq)
+);
+CREATE INDEX IF NOT EXISTS idx_agent_chat_sessions_updated
+ ON agent_chat_sessions(updated_ms DESC);
+"""
+
+_TITLE_MAX_CHARS = 80
+_PREVIEW_MAX_CHARS = 120
+# The permission ladders live in jarvis/agent_chat/permissions.py (per
+# runner); the store keeps whatever id the route validated.
+
+
+@dataclass(slots=True)
+class AgentChatSession:
+ session_id: str
+ title: str
+ provider: str
+ model: str
+ effort: str
+ cwd: str
+ permission_mode: str
+ vendor_session: str | None
+ created_ms: int
+ updated_ms: int
+ message_count: int
+ preview: str
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+def _title_from(text: str) -> str:
+ line = " ".join((text or "").split())
+ if len(line) > _TITLE_MAX_CHARS:
+ return line[: _TITLE_MAX_CHARS - 1].rstrip() + "…"
+ return line
+
+
+class AgentChatStore:
+ """Sessions + event log. ``db_path=":memory:"`` for tests."""
+
+ def __init__(self, db_path: str | Path = ":memory:") -> None:
+ self._path = str(db_path)
+ if self._path != ":memory:":
+ Path(self._path).parent.mkdir(parents=True, exist_ok=True)
+ self._conn = sqlite3.connect(self._path, check_same_thread=False)
+ self._conn.row_factory = sqlite3.Row
+ self._lock = threading.Lock()
+ with self._lock:
+ if self._path != ":memory:":
+ self._conn.execute("PRAGMA journal_mode=WAL")
+ self._conn.executescript(_SCHEMA)
+ self._conn.commit()
+
+ def close(self) -> None:
+ with self._lock:
+ self._conn.close()
+
+ # ------------------------------------------------------------ sessions
+
+ def create_session(
+ self,
+ *,
+ provider: str,
+ model: str,
+ effort: str,
+ cwd: str,
+ permission_mode: str = "",
+ title: str = "",
+ session_id: str | None = None,
+ ) -> AgentChatSession:
+ sid = session_id or uuid.uuid4().hex
+ now = now_ms()
+ # The route validated the mode against the runner's ladder; the store
+ # keeps the id as given.
+ mode = (permission_mode or "").strip()
+ with self._lock:
+ self._conn.execute(
+ "INSERT INTO agent_chat_sessions (session_id, title, provider, model, effort, "
+ "cwd, permission_mode, vendor_session, created_ms, updated_ms, message_count, "
+ "preview) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, 0, '')",
+ (sid, title, provider, model, effort, cwd, mode, now, now),
+ )
+ self._conn.commit()
+ session = self.get_session(sid)
+ assert session is not None
+ return session
+
+ def get_session(self, session_id: str) -> AgentChatSession | None:
+ with self._lock:
+ row = self._conn.execute(
+ "SELECT * FROM agent_chat_sessions WHERE session_id = ?", (session_id,)
+ ).fetchone()
+ return self._row_to_session(row) if row else None
+
+ def list_sessions(self, limit: int = 200) -> list[AgentChatSession]:
+ with self._lock:
+ rows = self._conn.execute(
+ "SELECT * FROM agent_chat_sessions ORDER BY updated_ms DESC LIMIT ?",
+ (int(limit),),
+ ).fetchall()
+ return [self._row_to_session(r) for r in rows]
+
+ def update_session(self, session_id: str, **fields: Any) -> AgentChatSession | None:
+ """Set any of title / provider / model / effort / cwd / permission_mode /
+ vendor_session. Unknown keys are ignored so a route can pass its body
+ through after validation."""
+ allowed = {
+ "title",
+ "provider",
+ "model",
+ "effort",
+ "cwd",
+ "permission_mode",
+ "vendor_session",
+ }
+ updates = {k: v for k, v in fields.items() if k in allowed and v is not None}
+ if not updates:
+ return self.get_session(session_id)
+ updates["updated_ms"] = now_ms()
+ cols = ", ".join(f"{k} = ?" for k in updates)
+ with self._lock:
+ self._conn.execute(
+ f"UPDATE agent_chat_sessions SET {cols} WHERE session_id = ?", # noqa: S608 — column names are from the allow-list above
+ (*updates.values(), session_id),
+ )
+ self._conn.commit()
+ return self.get_session(session_id)
+
+ def delete_session(self, session_id: str) -> bool:
+ with self._lock:
+ cur = self._conn.execute(
+ "DELETE FROM agent_chat_sessions WHERE session_id = ?", (session_id,)
+ )
+ self._conn.execute("DELETE FROM agent_chat_events WHERE session_id = ?", (session_id,))
+ self._conn.commit()
+ return cur.rowcount > 0
+
+ # -------------------------------------------------------------- events
+
+ def append_event(self, session_id: str, event: dict[str, Any]) -> dict[str, Any]:
+ """Persist ``event`` (assigning ``seq``) and return it with the seq set.
+
+ Transient kinds are returned unchanged and never written. A
+ ``user_message`` bumps the session's counters and, on the first one,
+ becomes its title; an ``assistant_text`` refreshes the preview.
+ """
+ if is_transient(event):
+ return event
+ kind = str(event.get("kind") or "")
+ payload = event.get("payload") or {}
+ ts_ms = int(event.get("ts_ms") or now_ms())
+ with self._lock:
+ row = self._conn.execute(
+ "SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM agent_chat_events "
+ "WHERE session_id = ?",
+ (session_id,),
+ ).fetchone()
+ seq = int(row["next"]) if row else 1
+ self._conn.execute(
+ "INSERT INTO agent_chat_events (session_id, seq, ts_ms, kind, payload) "
+ "VALUES (?, ?, ?, ?, ?)",
+ (session_id, seq, ts_ms, kind, json.dumps(payload, ensure_ascii=False)),
+ )
+ if kind == "user_message":
+ text = str(payload.get("text") or "")
+ self._conn.execute(
+ "UPDATE agent_chat_sessions SET message_count = message_count + 1, "
+ "updated_ms = ?, preview = ?, "
+ "title = CASE WHEN title = '' THEN ? ELSE title END "
+ "WHERE session_id = ?",
+ (ts_ms, text[:_PREVIEW_MAX_CHARS], _title_from(text), session_id),
+ )
+ elif kind == "assistant_text":
+ text = " ".join(str(payload.get("text") or "").split())
+ if text:
+ self._conn.execute(
+ "UPDATE agent_chat_sessions SET updated_ms = ?, preview = ? "
+ "WHERE session_id = ?",
+ (ts_ms, text[:_PREVIEW_MAX_CHARS], session_id),
+ )
+ else:
+ self._conn.execute(
+ "UPDATE agent_chat_sessions SET updated_ms = ? WHERE session_id = ?",
+ (ts_ms, session_id),
+ )
+ self._conn.commit()
+ out = dict(event)
+ out["seq"] = seq
+ out["ts_ms"] = ts_ms
+ return out
+
+ def list_events(self, session_id: str, *, after_seq: int = 0) -> list[dict[str, Any]]:
+ with self._lock:
+ rows = self._conn.execute(
+ "SELECT seq, ts_ms, kind, payload FROM agent_chat_events "
+ "WHERE session_id = ? AND seq > ? ORDER BY seq ASC",
+ (session_id, int(after_seq)),
+ ).fetchall()
+ out: list[dict[str, Any]] = []
+ for r in rows:
+ try:
+ payload = json.loads(r["payload"])
+ except (TypeError, ValueError):
+ payload = {}
+ out.append(
+ {
+ "seq": int(r["seq"]),
+ "ts_ms": int(r["ts_ms"]),
+ "kind": r["kind"],
+ "payload": payload,
+ }
+ )
+ return out
+
+ # ------------------------------------------------------------- helpers
+
+ @staticmethod
+ def _row_to_session(row: sqlite3.Row) -> AgentChatSession:
+ return AgentChatSession(
+ session_id=row["session_id"],
+ title=row["title"],
+ provider=row["provider"],
+ model=row["model"],
+ effort=row["effort"],
+ cwd=row["cwd"],
+ permission_mode=row["permission_mode"],
+ vendor_session=row["vendor_session"],
+ created_ms=int(row["created_ms"]),
+ updated_ms=int(row["updated_ms"]),
+ message_count=int(row["message_count"]),
+ preview=row["preview"],
+ )
diff --git a/jarvis/agent_chat/tools.py b/jarvis/agent_chat/tools.py
new file mode 100644
index 0000000000..1c0205b16c
--- /dev/null
+++ b/jarvis/agent_chat/tools.py
@@ -0,0 +1,460 @@
+"""The hands of the in-process agent chat.
+
+A deliberately small set in the Claude Code shape — ``Read``, ``Write``,
+``Edit``, ``Ls``, ``Glob``, ``Grep``, ``RunCommand`` — scoped to the
+session's working directory: relative paths resolve against it, absolute
+paths are allowed (the chat is the person's own session on their own
+machine, not a mission worktree), and anything that changes state is gated
+by the session's permission mode in :mod:`jarvis.agent_chat.runner_api`:
+
+* ``READ_ONLY_TOOLS`` run without asking;
+* the rest ask first in ``ask`` mode (the default) and run straight away in
+ ``auto`` mode — the same two stances Claude Code offers as "ask" and
+ "accept edits / bypass".
+
+Commands run through the platform shell the person would use themselves
+(Git Bash where it exists, PowerShell on a bare Windows, ``bash``/``sh`` on
+POSIX) with the output capped so a noisy build cannot flood the model's
+context. ``NO_WINDOW_CREATIONFLAGS`` keeps the console window away (AP-1) and
+the child's stdout is read as UTF-8.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import fnmatch
+import logging
+import os
+import re
+import shutil
+import sys
+import time
+from pathlib import Path
+from typing import Any, Final
+
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+log = logging.getLogger(__name__)
+
+READ_ONLY_TOOLS: Final[frozenset[str]] = frozenset({"Read", "Ls", "Glob", "Grep"})
+#: Tools that change files but run nothing — "Auto-accept edits" lets these through.
+EDIT_TOOLS: Final[frozenset[str]] = frozenset({"Write", "Edit"})
+MUTATING_TOOLS: Final[frozenset[str]] = frozenset({"Write", "Edit", "RunCommand"})
+
+_READ_CAP_CHARS = 60_000
+_COMMAND_CAP_CHARS = 30_000
+_GREP_MAX_RESULTS = 200
+_GLOB_MAX_RESULTS = 500
+_DEFAULT_COMMAND_TIMEOUT_S = 120.0
+_MAX_COMMAND_TIMEOUT_S = 900.0
+
+# Directories no search should descend into — the usual dependency and
+# build folders that make a Grep over a project take minutes.
+_SKIP_DIRS: Final[frozenset[str]] = frozenset(
+ {".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", ".next", ".tox"}
+)
+
+TOOL_SPECS: Final[tuple[dict[str, Any], ...]] = (
+ {
+ "name": "Read",
+ "description": (
+ "Read a text file. Paths are relative to the working directory unless "
+ "absolute. Use offset/limit (1-based line numbers) for long files."
+ ),
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "file_path": {"type": "string"},
+ "offset": {"type": "integer", "description": "First line to return (1-based)."},
+ "limit": {"type": "integer", "description": "How many lines to return."},
+ },
+ "required": ["file_path"],
+ },
+ },
+ {
+ "name": "Write",
+ "description": "Create or overwrite a file with the given full content.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "file_path": {"type": "string"},
+ "content": {"type": "string"},
+ },
+ "required": ["file_path", "content"],
+ },
+ },
+ {
+ "name": "Edit",
+ "description": (
+ "Replace old_string with new_string in a file. old_string must match "
+ "exactly; it must be unique unless replace_all is true."
+ ),
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "file_path": {"type": "string"},
+ "old_string": {"type": "string"},
+ "new_string": {"type": "string"},
+ "replace_all": {"type": "boolean"},
+ },
+ "required": ["file_path", "old_string", "new_string"],
+ },
+ },
+ {
+ "name": "Ls",
+ "description": "List a directory (default: the working directory).",
+ "input_schema": {
+ "type": "object",
+ "properties": {"path": {"type": "string"}},
+ },
+ },
+ {
+ "name": "Glob",
+ "description": (
+ "Find files by glob pattern, e.g. '**/*.py' or 'src/**/*.tsx', under "
+ "path (default: the working directory)."
+ ),
+ "input_schema": {
+ "type": "object",
+ "properties": {"pattern": {"type": "string"}, "path": {"type": "string"}},
+ "required": ["pattern"],
+ },
+ },
+ {
+ "name": "Grep",
+ "description": (
+ "Search file contents with a regular expression under path (default: "
+ "the working directory). Optional glob filters file names."
+ ),
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "pattern": {"type": "string"},
+ "path": {"type": "string"},
+ "glob": {"type": "string"},
+ "max_results": {"type": "integer"},
+ },
+ "required": ["pattern"],
+ },
+ },
+ {
+ "name": "RunCommand",
+ "description": (
+ "Run a shell command in the working directory and return its output. "
+ "Use for git, tests, builds, package managers and anything the other "
+ "tools cannot do. Commands that need a terminal UI will not work."
+ ),
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "command": {"type": "string"},
+ "timeout_s": {"type": "integer", "description": "Seconds, default 120."},
+ },
+ "required": ["command"],
+ },
+ },
+)
+
+
+def tool_names() -> tuple[str, ...]:
+ return tuple(str(spec["name"]) for spec in TOOL_SPECS)
+
+
+def summarize_call(name: str, args: dict[str, Any]) -> str:
+ """The one-line label a tool call gets in the timeline and approval card."""
+ if name == "RunCommand":
+ command = str(args.get("command") or "").strip()
+ return command.splitlines()[0][:200] if command else ""
+ if name in {"Read", "Write", "Edit"}:
+ return str(args.get("file_path") or "")
+ if name == "Glob":
+ return str(args.get("pattern") or "")
+ if name == "Grep":
+ return str(args.get("pattern") or "")
+ if name == "Ls":
+ return str(args.get("path") or ".")
+ return ""
+
+
+# ---------------------------------------------------------------- shell
+
+
+def shell_argv() -> list[str]:
+ """The argv prefix a command string is appended to.
+
+ Git Bash first on Windows (what a developer there has and what the
+ models write for), then PowerShell; ``bash`` then ``sh`` elsewhere.
+ """
+ if sys.platform == "win32":
+ for candidate in (
+ Path(os.environ.get("ProgramFiles", r"C:\Program Files")) / "Git" / "bin" / "bash.exe",
+ Path(os.environ.get("ProgramW6432", r"C:\Program Files")) / "Git" / "bin" / "bash.exe",
+ Path(os.environ.get("LOCALAPPDATA", "")) / "Programs" / "Git" / "bin" / "bash.exe",
+ ):
+ try:
+ if candidate.is_file():
+ return [str(candidate), "-c"]
+ except OSError:
+ continue
+ pwsh = shutil.which("pwsh") or shutil.which("powershell")
+ if pwsh:
+ return [pwsh, "-NoProfile", "-NonInteractive", "-Command"]
+ return ["cmd.exe", "/d", "/s", "/c"]
+ for name in ("bash", "sh"):
+ found = shutil.which(name)
+ if found:
+ return [found, "-c"]
+ return ["/bin/sh", "-c"]
+
+
+def shell_label() -> str:
+ argv = shell_argv()
+ name = Path(argv[0]).stem.lower()
+ if name == "bash":
+ return "bash"
+ if name in {"pwsh", "powershell"}:
+ return "PowerShell"
+ if name == "cmd":
+ return "cmd.exe"
+ return name
+
+
+# ---------------------------------------------------------------- paths
+
+
+def resolve_path(cwd: Path, raw: str | None) -> Path:
+ text = (raw or "").strip() or "."
+ p = Path(os.path.expanduser(text))
+ if not p.is_absolute():
+ p = cwd / p
+ return p.resolve()
+
+
+def _display(path: Path, cwd: Path) -> str:
+ try:
+ return str(path.relative_to(cwd))
+ except ValueError:
+ return str(path)
+
+
+def _cap(text: str, limit: int) -> str:
+ if len(text) <= limit:
+ return text
+ return text[:limit] + f"\n…[truncated, {len(text) - limit} more characters]"
+
+
+# ---------------------------------------------------------------- tools
+
+
+async def execute_tool(name: str, args: dict[str, Any], *, cwd: Path) -> tuple[str, bool]:
+ """Run one tool. Returns ``(output, is_error)`` — never raises."""
+ try:
+ if name == "Read":
+ return await asyncio.to_thread(_read, args, cwd)
+ if name == "Write":
+ return await asyncio.to_thread(_write, args, cwd)
+ if name == "Edit":
+ return await asyncio.to_thread(_edit, args, cwd)
+ if name == "Ls":
+ return await asyncio.to_thread(_ls, args, cwd)
+ if name == "Glob":
+ return await asyncio.to_thread(_glob, args, cwd)
+ if name == "Grep":
+ return await asyncio.to_thread(_grep, args, cwd)
+ if name == "RunCommand":
+ return await _run_command(args, cwd)
+ return f"Unknown tool: {name}", True
+ except Exception as exc: # noqa: BLE001 — a tool failure is data for the model, not a crash
+ log.debug("agent chat tool %s failed: %s", name, exc)
+ return f"{type(exc).__name__}: {exc}", True
+
+
+def _read(args: dict[str, Any], cwd: Path) -> tuple[str, bool]:
+ path = resolve_path(cwd, args.get("file_path"))
+ if not path.is_file():
+ return f"File not found: {_display(path, cwd)}", True
+ try:
+ text = path.read_text(encoding="utf-8", errors="replace")
+ except OSError as exc:
+ return f"Cannot read {_display(path, cwd)}: {exc}", True
+ lines = text.splitlines()
+ offset = int(args.get("offset") or 1)
+ limit = args.get("limit")
+ start = max(0, offset - 1)
+ end = start + int(limit) if limit else len(lines)
+ chunk = lines[start:end]
+ body = "\n".join(f"{start + i + 1}\t{line}" for i, line in enumerate(chunk))
+ header = f"{_display(path, cwd)} ({len(lines)} lines"
+ if start or end < len(lines):
+ header += f", showing {start + 1}-{min(end, len(lines))}"
+ header += ")"
+ return _cap(header + "\n" + body, _READ_CAP_CHARS), False
+
+
+def _write(args: dict[str, Any], cwd: Path) -> tuple[str, bool]:
+ path = resolve_path(cwd, args.get("file_path"))
+ content = str(args.get("content") or "")
+ path.parent.mkdir(parents=True, exist_ok=True)
+ existed = path.exists()
+ path.write_text(content, encoding="utf-8")
+ verb = "Updated" if existed else "Created"
+ return f"{verb} {_display(path, cwd)} ({len(content)} chars)", False
+
+
+def _edit(args: dict[str, Any], cwd: Path) -> tuple[str, bool]:
+ path = resolve_path(cwd, args.get("file_path"))
+ if not path.is_file():
+ return f"File not found: {_display(path, cwd)}", True
+ old = str(args.get("old_string") or "")
+ new = str(args.get("new_string") or "")
+ if not old:
+ return "old_string must not be empty", True
+ text = path.read_text(encoding="utf-8", errors="replace")
+ count = text.count(old)
+ if count == 0:
+ return f"old_string not found in {_display(path, cwd)}", True
+ if count > 1 and not args.get("replace_all"):
+ return (
+ f"old_string occurs {count} times in {_display(path, cwd)}; make it unique "
+ "or set replace_all",
+ True,
+ )
+ updated = text.replace(old, new) if args.get("replace_all") else text.replace(old, new, 1)
+ path.write_text(updated, encoding="utf-8")
+ n = count if args.get("replace_all") else 1
+ return f"Edited {_display(path, cwd)} ({n} replacement{'s' if n != 1 else ''})", False
+
+
+def _ls(args: dict[str, Any], cwd: Path) -> tuple[str, bool]:
+ path = resolve_path(cwd, args.get("path"))
+ if not path.is_dir():
+ return f"Not a directory: {_display(path, cwd)}", True
+ try:
+ entries = sorted(path.iterdir(), key=lambda p: (not p.is_dir(), p.name.lower()))
+ except OSError as exc:
+ return f"Cannot list {_display(path, cwd)}: {exc}", True
+ lines = [f"{p.name}/" if p.is_dir() else p.name for p in entries[:_GLOB_MAX_RESULTS]]
+ more = len(entries) - len(lines)
+ out = f"{path}\n" + "\n".join(lines)
+ if more > 0:
+ out += f"\n…and {more} more"
+ return out, False
+
+
+def _iter_files(root: Path):
+ for dirpath, dirnames, filenames in os.walk(root):
+ dirnames[:] = [d for d in dirnames if d not in _SKIP_DIRS]
+ for fn in filenames:
+ yield Path(dirpath) / fn
+
+
+def _glob(args: dict[str, Any], cwd: Path) -> tuple[str, bool]:
+ root = resolve_path(cwd, args.get("path"))
+ pattern = str(args.get("pattern") or "").strip()
+ if not pattern:
+ return "pattern is required", True
+ if not root.is_dir():
+ return f"Not a directory: {_display(root, cwd)}", True
+ hits: list[str] = []
+ for p in _iter_files(root):
+ rel = p.relative_to(root).as_posix()
+ if fnmatch.fnmatch(rel, pattern) or fnmatch.fnmatch(p.name, pattern):
+ hits.append(rel)
+ if len(hits) >= _GLOB_MAX_RESULTS:
+ break
+ if not hits:
+ return f"No files match {pattern!r} under {root}", False
+ return "\n".join(hits), False
+
+
+def _grep(args: dict[str, Any], cwd: Path) -> tuple[str, bool]:
+ root = resolve_path(cwd, args.get("path"))
+ pattern = str(args.get("pattern") or "")
+ if not pattern:
+ return "pattern is required", True
+ try:
+ rx = re.compile(pattern)
+ except re.error as exc:
+ return f"Invalid regular expression: {exc}", True
+ name_glob = str(args.get("glob") or "").strip() or None
+ limit = min(int(args.get("max_results") or _GREP_MAX_RESULTS), _GREP_MAX_RESULTS)
+ files = [root] if root.is_file() else list(_iter_files(root)) if root.is_dir() else []
+ if not files:
+ return f"Nothing to search at {_display(root, cwd)}", True
+ hits: list[str] = []
+ for p in files:
+ rel_name = p.relative_to(root).as_posix() if root.is_dir() else p.name
+ if name_glob and not (
+ fnmatch.fnmatch(p.name, name_glob) or fnmatch.fnmatch(rel_name, name_glob)
+ ):
+ continue
+ try:
+ with p.open("r", encoding="utf-8", errors="replace") as fh:
+ for no, line in enumerate(fh, start=1):
+ if rx.search(line):
+ rel = p.relative_to(root).as_posix() if root.is_dir() else p.name
+ hits.append(f"{rel}:{no}:{line.rstrip()[:300]}")
+ if len(hits) >= limit:
+ break
+ except (OSError, UnicodeError):
+ continue
+ if len(hits) >= limit:
+ break
+ if not hits:
+ return f"No matches for {pattern!r}", False
+ out = "\n".join(hits)
+ if len(hits) >= limit:
+ out += f"\n…stopped at {limit} matches"
+ return out, False
+
+
+async def _run_command(args: dict[str, Any], cwd: Path) -> tuple[str, bool]:
+ command = str(args.get("command") or "").strip()
+ if not command:
+ return "command is required", True
+ timeout = float(args.get("timeout_s") or _DEFAULT_COMMAND_TIMEOUT_S)
+ timeout = max(1.0, min(timeout, _MAX_COMMAND_TIMEOUT_S))
+ env = dict(os.environ)
+ env.setdefault("PYTHONIOENCODING", "utf-8")
+ env["CI"] = env.get("CI", "1") # most tools drop interactive prompts/colours on CI
+ env.setdefault("NO_COLOR", "1")
+ argv = [*shell_argv(), command]
+ started = time.perf_counter()
+ try:
+ proc = await asyncio.create_subprocess_exec(
+ *argv,
+ cwd=str(cwd),
+ env=env,
+ stdin=asyncio.subprocess.DEVNULL,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.STDOUT,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ except (OSError, ValueError) as exc:
+ return f"Could not start the shell: {exc}", True
+ try:
+ raw, _ = await asyncio.wait_for(proc.communicate(), timeout=timeout)
+ except TimeoutError:
+ with _suppress_os():
+ proc.kill()
+ with _suppress_os():
+ await proc.wait()
+ return f"Command timed out after {int(timeout)} s: {command}", True
+ except asyncio.CancelledError:
+ with _suppress_os():
+ proc.kill()
+ raise
+ text = raw.decode("utf-8", errors="replace")
+ took = time.perf_counter() - started
+ code = proc.returncode
+ out = _cap(text.rstrip(), _COMMAND_CAP_CHARS)
+ footer = f"\n[exit {code} · {took:.1f}s]"
+ return (out + footer).strip(), code != 0
+
+
+class _suppress_os:
+ def __enter__(self) -> None:
+ return None
+
+ def __exit__(self, exc_type, exc, tb) -> bool:
+ return exc_type is not None and issubclass(exc_type, (OSError, ProcessLookupError))
diff --git a/jarvis/brain/model_catalog.py b/jarvis/brain/model_catalog.py
index 4a9229f673..d4baf3c7a8 100644
--- a/jarvis/brain/model_catalog.py
+++ b/jarvis/brain/model_catalog.py
@@ -190,6 +190,7 @@ CURATED_MODELS: dict[str, list[ModelInfo]] = {
"claude-api": _curated(
[
("claude-fable-5", "Claude Fable 5"),
+ ("claude-opus-5", "Claude Opus 5"),
("claude-opus-4-8", "Claude Opus 4.8"),
("claude-sonnet-5", "Claude Sonnet 5"),
("claude-haiku-4-5-20251001", "Claude Haiku 4.5"),
@@ -211,6 +212,8 @@ CURATED_MODELS: dict[str, list[ModelInfo]] = {
),
"gemini": _curated(
[
+ ("gemini-3.7-flash", "Gemini 3.7 Flash"),
+ ("gemini-3.6-flash", "Gemini 3.6 Flash"),
("gemini-3.5-flash", "Gemini 3.5 Flash"),
("gemini-3.1-pro-preview", "Gemini 3.1 Pro"),
("gemini-3-flash-preview", "Gemini 3 Flash"),
diff --git a/jarvis/plugins/brain/_anthropic_base.py b/jarvis/plugins/brain/_anthropic_base.py
index 3266a2f925..3e38311734 100644
--- a/jarvis/plugins/brain/_anthropic_base.py
+++ b/jarvis/plugins/brain/_anthropic_base.py
@@ -1,14 +1,15 @@
-"""Shared Anthropic logic for claude-api & claude-api.
+"""Shared Anthropic logic for claude-api & claude-api.
The two providers differ almost only in their key sources. All
streaming + tool-use logic is identical (Anthropic API format).
"""
+
from __future__ import annotations
import json
import os
from collections.abc import AsyncIterator
-from typing import Any
+from typing import Any, Final
from jarvis.core.protocols import BrainDelta, BrainMessage, BrainRequest
@@ -49,12 +50,20 @@ def _to_anthropic_messages(messages: tuple[BrainMessage, ...]) -> list[dict[str,
if role == "tool":
# Tool result becomes a user message with tool_result content
- out.append({
- "role": "user",
- "content": content if isinstance(content, list) else [
- {"type": "tool_result", "tool_use_id": m.tool_call_id or "", "content": str(content)}
- ],
- })
+ out.append(
+ {
+ "role": "user",
+ "content": content
+ if isinstance(content, list)
+ else [
+ {
+ "type": "tool_result",
+ "tool_use_id": m.tool_call_id or "",
+ "content": str(content),
+ }
+ ],
+ }
+ )
continue
# role: user | assistant — multimodal only for user (Anthropic accepts
@@ -72,14 +81,16 @@ def _to_anthropic_messages(messages: tuple[BrainMessage, ...]) -> list[dict[str,
# Already blocks (e.g. tool_result passthrough) — keep as-is.
content_blocks.extend(content)
for img in images:
- content_blocks.append({
- "type": "image",
- "source": {
- "type": "base64",
- "media_type": img.mime,
- "data": img.data_b64,
- },
- })
+ content_blocks.append(
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": img.mime,
+ "data": img.data_b64,
+ },
+ }
+ )
out.append({"role": role, "content": content_blocks})
continue
@@ -112,18 +123,109 @@ def _tools_anthropic_format(
for t in tools:
schema = t.get("input_schema") or t.get("parameters") or t.get("schema") or {}
original = t.get("name", "")
- out.append({
- "name": name_map.get(original, original),
- "description": t.get("description", ""),
- "input_schema": schema if schema else {"type": "object", "properties": {}},
- })
+ out.append(
+ {
+ "name": name_map.get(original, original),
+ "description": t.get("description", ""),
+ "input_schema": schema if schema else {"type": "object", "properties": {}},
+ }
+ )
return out
def _is_reasoning_model(model: str) -> bool:
- """Claude Opus-4.x and Sonnet-4.x no longer accept `temperature`."""
+ """Models that no longer take `temperature` (the 4.x and 5 families)."""
+ m = (model or "").lower()
+ return (
+ "opus-4" in m
+ or "sonnet-4" in m
+ or "haiku-4" in m
+ or "opus-5" in m
+ or "sonnet-5" in m
+ or "fable-5" in m
+ or "mythos" in m
+ )
+
+
+# Effort ladders per family (Anthropic Messages API ``output_config.effort``).
+# Opus 4.6 / Sonnet 4.6 stop at ``max`` with no ``xhigh``; Opus 4.5 knows
+# only low/medium/high; Haiku 4.5 and Sonnet 4.5 reject the parameter.
+_EFFORT_ALL: Final[tuple[str, ...]] = ("low", "medium", "high", "xhigh", "max")
+_EFFORT_46: Final[tuple[str, ...]] = ("low", "medium", "high", "max")
+_EFFORT_45: Final[tuple[str, ...]] = ("low", "medium", "high")
+
+
+def _effort_ladder(model: str) -> tuple[str, ...]:
m = (model or "").lower()
- return "opus-4" in m or "sonnet-4" in m or "haiku-4" in m
+ if "haiku" in m or "sonnet-4-5" in m or "sonnet-4-0" in m or "opus-4-0" in m or "opus-4-1" in m:
+ return ()
+ if "opus-4-5" in m:
+ return _EFFORT_45
+ if "opus-4-6" in m or "sonnet-4-6" in m:
+ return _EFFORT_46
+ if (
+ "fable-5" in m
+ or "mythos" in m
+ or "opus-5" in m
+ or "sonnet-5" in m
+ or "opus-4-7" in m
+ or "opus-4-8" in m
+ ):
+ return _EFFORT_ALL
+ return ()
+
+
+def _adaptive_thinking_model(model: str) -> bool:
+ """Models whose thinking is switched on with ``{"type": "adaptive"}``.
+
+ Opus 4.7 / 4.8 and Sonnet 5 run WITHOUT thinking unless told; Opus 5 and
+ Fable 5 think by default and accept the same value. Pre-4.6 models take
+ ``budget_tokens`` instead, which this adapter leaves alone.
+ """
+ m = (model or "").lower()
+ return any(
+ tag in m
+ for tag in (
+ "fable-5",
+ "mythos",
+ "opus-5",
+ "sonnet-5",
+ "opus-4-8",
+ "opus-4-7",
+ "opus-4-6",
+ "sonnet-4-6",
+ )
+ )
+
+
+def reasoning_kwargs(model: str, effort: str | None) -> dict[str, Any]:
+ """The ``output_config`` / ``thinking`` arguments for a requested effort.
+
+ ``effort`` is the caller's level (``BrainRequest.reasoning_effort``); a
+ level the model does not offer snaps to the nearest lower one it does
+ (``xhigh`` on Opus 4.6 -> ``high``; ``none``/``minimal`` -> ``low``).
+ No effort requested -> nothing is added, so the voice brain's requests
+ are byte-for-byte what they were.
+ """
+ picked = (effort or "").strip().lower()
+ if not picked:
+ return {}
+ ladder = _effort_ladder(model)
+ if not ladder:
+ return {}
+ if picked in ("none", "minimal"):
+ level = ladder[0]
+ elif picked in ladder:
+ level = picked
+ else:
+ order = ("low", "medium", "high", "xhigh", "max")
+ idx = order.index(picked) if picked in order else 0
+ lower = [lvl for lvl in ladder if order.index(lvl) <= idx]
+ level = lower[-1] if lower else ladder[0]
+ out: dict[str, Any] = {"output_config": {"effort": level}}
+ if _adaptive_thinking_model(model):
+ out["thinking"] = {"type": "adaptive"}
+ return out
async def stream_complete(
@@ -175,6 +277,10 @@ async def stream_complete(
# temperature=1 is hardcoded on the backend anyway.
if not _is_reasoning_model(model):
kwargs["temperature"] = req.temperature
+ # A requested reasoning effort (the agent chat's picker) becomes
+ # ``output_config.effort`` plus adaptive thinking on the models that
+ # take it; the voice brain never sets one and sends exactly what it did.
+ kwargs.update(reasoning_kwargs(model, getattr(req, "reasoning_effort", None)))
if system_payload:
kwargs["system"] = system_payload
if tools_payload:
@@ -243,7 +349,6 @@ async def stream_complete(
# cache_read_input_tokens, which no consumer reads, so
# cache hits were invisible in cost and telemetry and
# cache regressions could not be measured.
- "cache_hit_tokens": int(
- getattr(usage, "cache_read_input_tokens", 0) or 0),
+ "cache_hit_tokens": int(getattr(usage, "cache_read_input_tokens", 0) or 0),
}
yield BrainDelta(finish_reason=finish, usage=usage_d or None)
diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.py
new file mode 100644
index 0000000000..867dace75b
--- /dev/null
+++ b/jarvis/ui/web/agent_chat_routes.py
@@ -0,0 +1,475 @@
+"""REST + WebSocket routes for the agent chat (the typed front-page chat).
+
+Prefix ``/api/agent-chat``:
+
+ GET /catalog provider rows + effort + permission ladders
+ GET /sessions newest first
+ POST /sessions create (provider, model, effort, cwd, permission_mode)
+ GET /sessions/{id} session + its persisted events
+ PATCH /sessions/{id} title/provider/model/effort/cwd/permission_mode
+ DELETE /sessions/{id}
+ POST /sessions/{id}/messages {text} -> starts a turn, returns turn_id
+ POST /sessions/{id}/cancel
+ POST /sessions/{id}/approvals/{aid} {decision: allow | allow_always | deny}
+ WS /sessions/{id}/ws?after=<seq> snapshot, then live events
+ POST /pick-folder the system folder dialog (desktop only)
+ GET /check-folder?path= does the folder exist / is it a directory
+
+The service lives on ``app.state.agent_chat`` (built in ``server.py``); a
+missing service answers 503 like every other optional subsystem.
+Loopback-only like the rest of the web UI — no auth token.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import os
+from pathlib import Path
+from typing import Any
+
+from fastapi import APIRouter, HTTPException, Query, Request, WebSocket, WebSocketDisconnect
+from pydantic import BaseModel, Field
+
+from jarvis.agent_chat.catalog import CLAUDE_CODE_MODELS, PROVIDER_ROWS
+from jarvis.agent_chat.effort import normalize_effort
+from jarvis.agent_chat.events import make_event
+from jarvis.agent_chat.permissions import (
+ default_permission,
+ is_permission_mode,
+ normalize_permission,
+ permission_modes,
+)
+from jarvis.agent_chat.service import (
+ DECISIONS,
+ AgentChatService,
+ NoSuchSession,
+ SessionBusy,
+ resolve_runner,
+)
+from jarvis.agent_chat.tools import shell_label
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/agent-chat", tags=["agent-chat"])
+
+_WS_PING_S = 20.0
+
+
+# ------------------------------------------------------------------ bodies
+
+
+class CreateSessionBody(BaseModel):
+ provider: str
+ model: str = ""
+ effort: str | None = None
+ cwd: str | None = None
+ #: "" = the runner's default mode (jarvis/agent_chat/permissions.py).
+ permission_mode: str = ""
+ title: str = ""
+
+
+class PatchSessionBody(BaseModel):
+ title: str | None = None
+ provider: str | None = None
+ model: str | None = None
+ effort: str | None = None
+ cwd: str | None = None
+ permission_mode: str | None = None
+
+
+class MessageBody(BaseModel):
+ text: str = Field(min_length=1, max_length=200_000)
+
+
+class ApprovalBody(BaseModel):
+ decision: str
+
+
+class PickFolderBody(BaseModel):
+ start: str | None = None
+
+
+# ------------------------------------------------------------------ helpers
+
+
+def _service_from_state(state: Any) -> AgentChatService | None:
+ """The service, built on first use from ``app.state.agent_chat_factory``."""
+ svc = getattr(state, "agent_chat", None)
+ if svc is not None:
+ return svc
+ factory = getattr(state, "agent_chat_factory", None)
+ if factory is None:
+ return None
+ try:
+ svc = factory()
+ except Exception as exc: # noqa: BLE001 — surfaces as 503 with the reason in the log
+ log.warning("agent chat: service could not be built: %s", exc)
+ return None
+ state.agent_chat = svc
+ return svc
+
+
+def _service(request: Request) -> AgentChatService:
+ svc = _service_from_state(request.app.state)
+ if svc is None:
+ raise HTTPException(status_code=503, detail="agent-chat-unavailable")
+ return svc
+
+
+def _ws_service(ws: WebSocket) -> AgentChatService | None:
+ app = ws.scope.get("app")
+ return _service_from_state(app.state) if app is not None else None
+
+
+def _cli_installed(runner: str) -> bool:
+ import shutil
+
+ names = {
+ "claude-cli": ("claude", "claude.cmd", "claude.exe"),
+ "codex-cli": ("codex", "codex.cmd", "codex.exe"),
+ "agy-cli": ("agy", "agy.exe"),
+ "grok-cli": ("grok", "grok.exe", "grok.cmd"),
+ }.get(runner, ())
+ return any(shutil.which(n) for n in names)
+
+
+async def _live_cli_models() -> dict[str, list[dict[str, Any]]]:
+ """The model lists the installed CLIs publish, keyed by runner.
+
+ agy answers ``agy models`` (a ~2 s subprocess, cached 10 min in the
+ runner module); Codex keeps ``models_cache.json`` in its home. Both are
+ read off the event loop; a failure just keeps the curated fallback.
+ """
+ from jarvis.agent_chat.runner_cli import read_agy_models, read_codex_models
+
+ out: dict[str, list[dict[str, Any]]] = {}
+ if _cli_installed("agy-cli"):
+ try:
+ out["agy-cli"] = await asyncio.wait_for(asyncio.to_thread(read_agy_models), 10.0)
+ except (TimeoutError, Exception) as exc: # noqa: BLE001 — the fallback list stands in
+ log.debug("agent chat: agy model list unavailable: %s", exc)
+ if _cli_installed("codex-cli"):
+ try:
+ rows = await asyncio.to_thread(read_codex_models)
+ except Exception as exc: # noqa: BLE001 — the fallback list stands in
+ log.debug("agent chat: codex model list unavailable: %s", exc)
+ rows = None
+ if rows:
+ out["codex-cli"] = rows
+ return out
+
+
+def _validate_cwd(raw: str | None) -> str | None:
+ if raw is None:
+ return None
+ text = raw.strip()
+ if not text:
+ return None
+ p = Path(os.path.expanduser(text))
+ if not p.is_dir():
+ raise HTTPException(status_code=400, detail=f"Not a folder: {text}")
+ return str(p.resolve())
+
+
+# ------------------------------------------------------------------ catalog
+
+
[email protected]("/catalog")
+async def get_catalog(request: Request) -> dict[str, Any]:
+ """Provider rows for the composer's picker.
+
+ Static shape from ``jarvis.agent_chat.catalog`` plus two live facts per
+ row: which runner answers on this machine and whether that runner's
+ binary is installed. Credential state is NOT repeated here — the
+ picker reads it from ``/api/jarvis-agent/status`` like the Agents tab,
+ so the two never disagree.
+ """
+ svc = _service(request)
+ rows: list[dict[str, Any]] = []
+ live_models = await _live_cli_models()
+ for row in PROVIDER_ROWS:
+ d = row.to_dict()
+ runner = resolve_runner(row.id)
+ d["runner"] = runner
+ d["cli_installed"] = _cli_installed(runner) if runner != "api" else None
+ # A CLI that publishes its own model list (agy, Codex) overrides the
+ # curated fallback with what THIS account can actually pick.
+ if d["cli_installed"] and runner in live_models and live_models[runner]:
+ d["curated_models"] = live_models[runner]
+ # The dual row: Claude Code takes its own ids and aliases; with only
+ # an API key the Anthropic catalog route lists the models live.
+ if row.id == "claude-api":
+ if runner == "claude-cli":
+ d["curated_models"] = [m.to_dict() for m in CLAUDE_CODE_MODELS]
+ d["models_source"] = "curated"
+ else:
+ d["models_source"] = "live"
+ # The permission ladder is the RUNNER's (Claude Code's modes when the
+ # CLI answers, the API runner's when only a key is there), so the
+ # composer shows the words the thing that runs actually understands.
+ d["permission_modes"] = [m.to_dict() for m in permission_modes(runner)]
+ d["default_permission_mode"] = default_permission(runner)
+ rows.append(d)
+ return {
+ "providers": rows,
+ "default_cwd": svc.default_cwd(),
+ "shell": shell_label(),
+ }
+
+
+# ------------------------------------------------------------------ sessions
+
+
[email protected]("/sessions")
+async def list_sessions(request: Request, limit: int = Query(200, ge=1, le=1000)) -> dict[str, Any]:
+ svc = _service(request)
+ out = []
+ for s in svc.store.list_sessions(limit=limit):
+ d = s.to_dict()
+ d["running"] = svc.is_running(s.session_id)
+ out.append(d)
+ return {"sessions": out}
+
+
[email protected]("/sessions", status_code=201)
+async def create_session(body: CreateSessionBody, request: Request) -> dict[str, Any]:
+ svc = _service(request)
+ runner = resolve_runner(body.provider)
+ if body.permission_mode and not is_permission_mode(runner, body.permission_mode):
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ "permission_mode must be one of "
+ + ", ".join(m.id for m in permission_modes(runner))
+ ),
+ )
+ cwd = _validate_cwd(body.cwd)
+ try:
+ session = svc.create_session(
+ provider=body.provider,
+ model=body.model,
+ effort=body.effort,
+ cwd=cwd,
+ permission_mode=normalize_permission(runner, body.permission_mode),
+ title=body.title,
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ d = session.to_dict()
+ d["running"] = False
+ return d
+
+
[email protected]("/sessions/{session_id}")
+async def get_session(session_id: str, request: Request) -> dict[str, Any]:
+ svc = _service(request)
+ session = svc.store.get_session(session_id)
+ if session is None:
+ raise HTTPException(status_code=404, detail="session not found")
+ d = session.to_dict()
+ d["running"] = svc.is_running(session_id)
+ return {"session": d, "events": svc.store.list_events(session_id)}
+
+
[email protected]("/sessions/{session_id}")
+async def patch_session(
+ session_id: str, body: PatchSessionBody, request: Request
+) -> dict[str, Any]:
+ svc = _service(request)
+ if svc.store.get_session(session_id) is None:
+ raise HTTPException(status_code=404, detail="session not found")
+ fields: dict[str, Any] = {}
+ if body.title is not None:
+ fields["title"] = body.title.strip()[:120]
+ if body.provider is not None:
+ fields["provider"] = body.provider.strip().lower()
+ # A provider change resets the vendor conversation: the new CLI cannot
+ # resume the old one's id.
+ fields["vendor_session"] = ""
+ if body.model is not None:
+ fields["model"] = body.model.strip()
+ if body.effort is not None:
+ provider = fields.get("provider") or svc.store.get_session(session_id).provider # type: ignore[union-attr]
+ fields["effort"] = normalize_effort(provider, body.effort)
+ if body.cwd is not None:
+ fields["cwd"] = _validate_cwd(body.cwd) or svc.default_cwd()
+ current = svc.store.get_session(session_id)
+ assert current is not None
+ runner = resolve_runner(fields.get("provider") or current.provider)
+ if body.permission_mode is not None:
+ if not is_permission_mode(runner, body.permission_mode):
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ "permission_mode must be one of "
+ + ", ".join(m.id for m in permission_modes(runner))
+ ),
+ )
+ fields["permission_mode"] = body.permission_mode
+ elif "provider" in fields:
+ # A provider change folds the old mode onto the new runner's ladder.
+ fields["permission_mode"] = normalize_permission(runner, current.permission_mode)
+ session = svc.store.update_session(session_id, **fields)
+ assert session is not None
+ changed = {k: v for k, v in fields.items() if k != "vendor_session"}
+ if changed:
+ await svc._emit(session_id, make_event("session_updated", changed)) # noqa: SLF001 — same package boundary
+ d = session.to_dict()
+ d["running"] = svc.is_running(session_id)
+ return d
+
+
[email protected]("/sessions/{session_id}")
+async def delete_session(session_id: str, request: Request) -> dict[str, Any]:
+ svc = _service(request)
+ await svc.cancel(session_id)
+ if not svc.store.delete_session(session_id):
+ raise HTTPException(status_code=404, detail="session not found")
+ return {"ok": True, "session_id": session_id}
+
+
+# ------------------------------------------------------------------ turns
+
+
[email protected]("/sessions/{session_id}/messages", status_code=202)
+async def post_message(session_id: str, body: MessageBody, request: Request) -> dict[str, Any]:
+ svc = _service(request)
+ try:
+ turn_id = await svc.send(session_id, body.text)
+ except NoSuchSession as exc:
+ raise HTTPException(status_code=404, detail="session not found") from exc
+ except SessionBusy as exc:
+ raise HTTPException(status_code=409, detail="a turn is already running") from exc
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ return {"turn_id": turn_id, "session_id": session_id}
+
+
[email protected]("/sessions/{session_id}/cancel")
+async def cancel_turn(session_id: str, request: Request) -> dict[str, Any]:
+ svc = _service(request)
+ if svc.store.get_session(session_id) is None:
+ raise HTTPException(status_code=404, detail="session not found")
+ cancelled = await svc.cancel(session_id)
+ return {"cancelled": cancelled, "session_id": session_id}
+
+
[email protected]("/sessions/{session_id}/approvals/{approval_id}")
+async def resolve_approval(
+ session_id: str, approval_id: str, body: ApprovalBody, request: Request
+) -> dict[str, Any]:
+ svc = _service(request)
+ if body.decision not in DECISIONS:
+ raise HTTPException(status_code=400, detail=f"decision must be one of {list(DECISIONS)}")
+ ok = svc.resolve_approval(session_id, approval_id, body.decision)
+ if not ok:
+ raise HTTPException(status_code=404, detail="no such pending approval")
+ return {"ok": True, "approval_id": approval_id, "decision": body.decision}
+
+
+# ------------------------------------------------------------------ folders
+
+
[email protected]("/pick-folder")
+async def pick_folder(body: PickFolderBody, request: Request) -> dict[str, Any]:
+ """Open the system folder dialog (desktop only) and return the choice."""
+ _service(request)
+ try:
+ from jarvis.agentic_ide import native_picker
+ except Exception as exc: # noqa: BLE001 — no picker module on this install
+ raise HTTPException(status_code=501, detail="no folder dialog here") from exc
+ result = await asyncio.to_thread(native_picker.choose_folder, start=body.start)
+ if result.error:
+ raise HTTPException(status_code=501, detail=result.error)
+ return {"path": result.path, "cancelled": result.cancelled}
+
+
+def _folder_check(path: str) -> dict[str, Any]:
+ p = Path(os.path.expanduser(path.strip())) if path.strip() else None
+ ok = bool(p and p.is_dir())
+ return {"ok": ok, "path": str(p.resolve()) if ok and p else path}
+
+
[email protected]("/check-folder")
+async def check_folder(path: str = Query(...)) -> dict[str, Any]:
+ return await asyncio.to_thread(_folder_check, path)
+
+
+# ------------------------------------------------------------------ stream
+
+
[email protected]("/sessions/{session_id}/ws")
+async def session_stream(ws: WebSocket, session_id: str) -> None:
+ """Snapshot + live events for one session.
+
+ First frame: ``{"type": "snapshot", "session": {...}, "events": [...]}``
+ with every persisted event after ``?after=<seq>`` (default 0 = all).
+ Then ``{"type": "event", "event": {...}}`` per live event, and a
+ ``{"type": "ping"}`` every 20 s of silence so a proxy keeps the socket.
+ """
+ await ws.accept()
+ svc = _ws_service(ws)
+ if svc is None:
+ await ws.close(code=1011, reason="agent chat not ready")
+ return
+ session = svc.store.get_session(session_id)
+ if session is None:
+ await ws.close(code=4404, reason="session not found")
+ return
+ try:
+ after = int(ws.query_params.get("after") or 0)
+ except ValueError:
+ after = 0
+
+ # Subscribe BEFORE reading the snapshot so nothing falls between the two.
+ q = svc.subscribe(session_id)
+ try:
+ events = svc.store.list_events(session_id, after_seq=after)
+ d = session.to_dict()
+ d["running"] = svc.is_running(session_id)
+ d["pending_approvals"] = svc.pending_approvals(session_id)
+ await ws.send_json({"type": "snapshot", "session": d, "events": events})
+ last_seq = events[-1]["seq"] if events else after
+
+ async def _reader() -> None:
+ # The client sends nothing meaningful; reading detects the close.
+ # Any receive error ends the stream (AP-20) — swallowed here so
+ # the task never carries an unretrieved exception; the loop below
+ # sees ``reader.done()`` and stops.
+ try:
+ while True:
+ await ws.receive_text()
+ except Exception as exc: # noqa: BLE001 — a closed socket is the normal end
+ log.debug("agent chat ws %s reader ended: %s", session_id, exc)
+
+ reader = asyncio.create_task(_reader())
+ try:
+ while not reader.done():
+ getter = asyncio.ensure_future(q.get())
+ done, _ = await asyncio.wait(
+ {getter, reader}, timeout=_WS_PING_S, return_when=asyncio.FIRST_COMPLETED
+ )
+ if getter not in done:
+ getter.cancel()
+ if reader in done:
+ break
+ await ws.send_json({"type": "ping"})
+ continue
+ ev = getter.result()
+ # Persisted events carry seq; transient deltas carry 0. Skip
+ # persisted ones the snapshot already had.
+ seq = int(ev.get("seq") or 0)
+ if seq and seq <= last_seq:
+ continue
+ if seq:
+ last_seq = seq
+ await ws.send_json({"type": "event", "event": ev})
+ finally:
+ reader.cancel()
+ except WebSocketDisconnect:
+ pass
+ except Exception as exc: # noqa: BLE001 — any socket error ends the stream (AP-20)
+ log.debug("agent chat ws %s ended: %s", session_id, exc)
+ finally:
+ svc.unsubscribe(session_id, q)
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx
new file mode 100644
index 0000000000..567aa52257
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx
@@ -0,0 +1,498 @@
+import { useCallback, useEffect, useMemo, useState, type KeyboardEvent } from "react";
+import {
+ ArrowUp,
+ Bot,
+ Brain,
+ FolderOpen,
+ Gauge,
+ Hammer,
+ Mic,
+ NotebookPen,
+ ShieldCheck,
+ Square,
+} from "lucide-react";
+
+import { Combobox, type ComboboxGroup, type ComboboxOption } from "@/components/ui/combobox";
+import { ProviderLogo } from "@/components/providers/ProviderLogo";
+import { useAgentChatStore, type ProviderOption } from "@/store/agentChat";
+import { useEventStore } from "@/store/events";
+import { pickAgentChatFolder } from "@/lib/agentChatApi";
+import { runningTurn } from "@/components/agentchat/reduce";
+import { useComposerDictation } from "@/components/agentchat/useComposerDictation";
+import { fill, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+
+/**
+ * The agent composer — the typed front page's one control.
+ *
+ * One card (maintainer sketch, 2026-08-23): the text box on top and, under
+ * it, the four picks that decide who answers and how —
+ *
+ * Provider · Model · Reasoning effort │ Permission mode · Build | Plan
+ *
+ * — then dictation and Send on the right. The picks are the backend's
+ * catalog, never a list typed here: the provider column is every sub-agent
+ * the Agents tab knows (connected ones pickable, the rest greyed with a
+ * "connect" hint), the model column is the provider's own list (live from
+ * its catalog route, or the curated list for a CLI), the effort ladder and
+ * the permission ladder are whatever that provider's runner accepts
+ * (jarvis/agent_chat/effort.py, permissions.py). Build | Plan is the
+ * permission ladder's `plan` entry drawn as a switch, shown only when the
+ * runner has one.
+ *
+ * A pick applies to the open session at once (the backend patches it and
+ * the next turn runs on it); with no session open it seeds the next one.
+ */
+export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {
+ const t = useT();
+ const [value, setValueState] = useState("");
+ const setValue = useCallback(
+ (next: string | ((current: string) => string)) => setValueState(next),
+ [],
+ );
+ const connected = useEventStore((s) => s.connected);
+ const wsWarming = useEventStore((s) => s.wsWarming);
+ const setActiveSection = useEventStore((s) => s.setActiveSection);
+
+ const catalog = useAgentChatStore((s) => s.catalog);
+ const catalogError = useAgentChatStore((s) => s.catalogError);
+ const connections = useAgentChatStore((s) => s.connections);
+ const liveModels = useAgentChatStore((s) => s.liveModels);
+ const draft = useAgentChatStore((s) => s.draft);
+ const timeline = useAgentChatStore((s) => s.timeline);
+ const busy = useAgentChatStore((s) => s.busy);
+ const lastError = useAgentChatStore((s) => s.lastError);
+ const setDraft = useAgentChatStore((s) => s.setDraft);
+ const setPlan = useAgentChatStore((s) => s.setPlan);
+ const send = useAgentChatStore((s) => s.send);
+ const cancel = useAgentChatStore((s) => s.cancel);
+ const loadCatalog = useAgentChatStore((s) => s.loadCatalog);
+
+ useEffect(() => {
+ if (!catalog) void loadCatalog();
+ }, [catalog, loadCatalog]);
+
+ const providers = useMemo<ProviderOption[]>(
+ () => useAgentChatStore.getState().providerOptions(),
+ // Recompute when either half of the join changes.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [catalog, connections],
+ );
+ const provider = providers.find((p) => p.id === draft.provider) ?? null;
+
+ const { dictating, stop: stopDictation, toggle: toggleDictation } = useComposerDictation(
+ value,
+ setValue,
+ );
+
+ const running = runningTurn(timeline) !== null;
+
+ async function onSend() {
+ const content = value.trim();
+ if (!content || running || busy) return;
+ if (dictating) stopDictation();
+ setValueState("");
+ await send(content);
+ }
+
+ function onKeyDown(ev: KeyboardEvent<HTMLTextAreaElement>) {
+ if (ev.key === "Enter" && !ev.shiftKey) {
+ ev.preventDefault();
+ void onSend();
+ }
+ }
+
+ async function onPickFolder() {
+ try {
+ const path = await pickAgentChatFolder(draft.cwd || undefined);
+ if (path) await setDraft({ cwd: path });
+ } catch {
+ /* no dialog on this install — the folder stays */
+ }
+ }
+
+ // ---- option lists -------------------------------------------------
+
+ const providerGroups = useMemo<ComboboxGroup[]>(() => {
+ const toOption = (p: ProviderOption): ComboboxOption => ({
+ value: p.id,
+ label: p.label,
+ hint: !p.connected
+ ? p.cli_installed === false
+ ? t("agent_chat.provider_not_installed")
+ : t("agent_chat.provider_connect")
+ : p.active
+ ? t("agent_chat.provider_active")
+ : undefined,
+ disabled: !p.connected,
+ icon: <ProviderLogo providerId={p.id} label={p.label} size="sm" />,
+ searchText: `${p.family} ${p.runner}`,
+ });
+ const ready = providers.filter((p) => p.connected).map(toOption);
+ const rest = providers.filter((p) => !p.connected).map(toOption);
+ const groups: ComboboxGroup[] = [];
+ if (ready.length) groups.push({ id: "ready", label: t("agent_chat.group_connected"), options: ready });
+ if (rest.length) groups.push({ id: "rest", label: t("agent_chat.group_not_connected"), options: rest });
+ return groups;
+ }, [providers, t]);
+
+ const modelList = useMemo(() => {
+ if (!provider) return [];
+ const live = liveModels[provider.id];
+ return provider.models_source === "live" && live && live.length ? live : provider.curated_models;
+ }, [provider, liveModels]);
+
+ const modelGroups = useMemo<ComboboxGroup[]>(() => {
+ if (!provider) return [];
+ const options: ComboboxOption[] = [
+ { value: "", label: t("agent_chat.model_default"), hint: provider.label },
+ ...modelList
+ .filter((m) => m.id)
+ .map((m) => ({
+ value: m.id,
+ label: m.label || m.id,
+ hint: m.note || (m.label && m.label !== m.id ? m.id : undefined),
+ searchText: m.id,
+ })),
+ ];
+ return [{ id: "models", options }];
+ }, [provider, modelList, t]);
+
+ // The effort ladder is the provider's, narrowed to the chosen model's own
+ // levels when the catalog knows them (agy's Pro: low/high; its Claude
+ // models: none at all, so the pick disappears).
+ const effortLevels = useMemo<string[]>(() => {
+ if (!provider) return [];
+ const model = modelList.find((m) => m.id === draft.model);
+ if (model && Array.isArray(model.efforts)) return model.efforts;
+ return provider.effort_levels;
+ }, [provider, modelList, draft.model]);
+
+ useEffect(() => {
+ // A model change can leave the picked effort off that model's ladder;
+ // snap to the nearest lower level (else the first) like the backend does.
+ if (!provider || !effortLevels.length || effortLevels.includes(draft.effort)) return;
+ const order = ["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"];
+ const idx = order.indexOf(draft.effort);
+ const lower = effortLevels.filter((l) => order.indexOf(l) <= idx && order.indexOf(l) >= 0);
+ const next = lower.length ? lower[lower.length - 1] : effortLevels[0];
+ if (next !== draft.effort) void setDraft({ effort: next });
+ }, [provider, effortLevels, draft.effort, setDraft]);
+
+ const effortGroups = useMemo<ComboboxGroup[]>(
+ () => [
+ {
+ id: "effort",
+ options: effortLevels.map((lvl) => ({ value: lvl, label: effortLabel(lvl, t) })),
+ },
+ ],
+ [effortLevels, t],
+ );
+
+ const permissionModes = useMemo(
+ () => (provider ? provider.permission_modes.filter((m) => m.id !== "plan") : []),
+ [provider],
+ );
+ const hasPlan = Boolean(provider?.permission_modes.some((m) => m.id === "plan"));
+ const planOn = draft.permissionMode === "plan";
+ const permissionGroups = useMemo<ComboboxGroup[]>(
+ () => [
+ {
+ id: "permission",
+ options: permissionModes.map((m) => ({ value: m.id, label: m.label, searchText: m.description })),
+ },
+ ],
+ [permissionModes],
+ );
+ // While Plan is on, the permission pill shows the mode Build would return to.
+ const permissionValue = planOn ? draft.buildMode || provider?.default_permission_mode || "" : draft.permissionMode;
+ const permissionDescription =
+ provider?.permission_modes.find((m) => m.id === draft.permissionMode)?.description ?? "";
+
+ const canSend = connected && Boolean(value.trim()) && !running && !busy && Boolean(provider?.connected);
+ const placeholder = connected
+ ? t("agent_chat.placeholder")
+ : wsWarming
+ ? t("voice_state.booting")
+ : t("voice_state.offline");
+
+ return (
+ <div
+ data-testid="agent-composer"
+ className={cn(
+ "flex flex-col gap-2 rounded-2xl border border-border bg-card p-3 shadow-[0_1px_2px_rgb(var(--scrim-rgb)/0.05),0_8px_24px_rgb(var(--scrim-rgb)/0.06)] transition-[border-color,box-shadow]",
+ "focus-within:border-primary/40",
+ )}
+ >
+ {dictating && (
+ <div
+ className="flex items-center gap-2 rounded-lg border border-primary/30 bg-primary/10 px-3 py-1.5 text-xs text-primary"
+ role="status"
+ aria-live="polite"
+ >
+ <span className="relative flex h-2 w-2" aria-hidden>
+ <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-primary/70" />
+ <span className="relative inline-flex h-2 w-2 rounded-full bg-primary" />
+ </span>
+ <span className="font-medium">{t("chats_view.dictation_listening")}</span>
+ </div>
+ )}
+ <textarea
+ data-jarvis-chat-input=""
+ autoFocus={autoFocus}
+ value={value}
+ onChange={(e) => setValueState(e.target.value)}
+ onKeyDown={onKeyDown}
+ placeholder={placeholder}
+ disabled={!connected}
+ rows={2}
+ className="max-h-48 w-full resize-none bg-transparent px-1 py-1 text-[15px] leading-relaxed text-foreground placeholder:text-muted-foreground focus-visible:outline-none disabled:opacity-50"
+ />
+ <div className="flex flex-wrap items-center gap-1">
+ <Pick
+ testId="composer-provider"
+ ariaLabel={t("agent_chat.pick_provider")}
+ value={draft.provider}
+ groups={providerGroups}
+ onChange={(v) => void setDraft({ provider: v })}
+ fallbackLabel={catalogError ? t("agent_chat.catalog_unavailable") : t("agent_chat.pick_provider")}
+ searchPlaceholder={t("agent_chat.search_providers")}
+ icon={provider ? undefined : <Bot className="h-3.5 w-3.5" aria-hidden />}
+ disabled={!catalog}
+ />
+ <Pick
+ testId="composer-model"
+ ariaLabel={t("agent_chat.pick_model")}
+ value={draft.model}
+ groups={modelGroups}
+ onChange={(v) => void setDraft({ model: v })}
+ fallbackLabel={draft.model || t("agent_chat.model_default")}
+ searchPlaceholder={t("agent_chat.search_models")}
+ icon={<Brain className="h-3.5 w-3.5" aria-hidden />}
+ disabled={!provider}
+ className="max-w-[220px]"
+ />
+ {provider && effortLevels.length > 1 && (
+ <Pick
+ testId="composer-effort"
+ ariaLabel={t("agent_chat.pick_effort")}
+ value={draft.effort}
+ groups={effortGroups}
+ onChange={(v) => void setDraft({ effort: v })}
+ fallbackLabel={effortLabel(draft.effort, t)}
+ icon={<Gauge className="h-3.5 w-3.5" aria-hidden />}
+ />
+ )}
+ {provider && permissionModes.length > 0 && (
+ <>
+ <span className="mx-1 h-4 w-px bg-border" aria-hidden />
+ <Pick
+ testId="composer-permission"
+ ariaLabel={t("agent_chat.pick_permission")}
+ value={permissionValue}
+ groups={permissionGroups}
+ onChange={(v) => void setDraft({ permissionMode: v })}
+ fallbackLabel={t("agent_chat.pick_permission")}
+ icon={<ShieldCheck className="h-3.5 w-3.5" aria-hidden />}
+ title={permissionDescription}
+ className="max-w-[220px]"
+ />
+ </>
+ )}
+ {hasPlan && (
+ <button
+ type="button"
+ role="switch"
+ aria-checked={planOn}
+ data-testid="composer-plan"
+ onClick={() => void setPlan(!planOn)}
+ title={planOn ? t("agent_chat.plan_hint") : t("agent_chat.build_hint")}
+ className={cn(
+ "inline-flex h-7 items-center gap-1.5 rounded-lg px-2 text-xs font-medium transition-colors",
+ planOn
+ ? "bg-primary/15 text-primary hover:bg-primary/20"
+ : "text-muted-foreground hover:bg-secondary hover:text-foreground",
+ )}
+ >
+ {planOn ? (
+ <NotebookPen className="h-3.5 w-3.5" aria-hidden />
+ ) : (
+ <Hammer className="h-3.5 w-3.5" aria-hidden />
+ )}
+ {planOn ? t("agent_chat.mode_plan") : t("agent_chat.mode_build")}
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={() => void onPickFolder()}
+ title={draft.cwd ? `${t("agent_chat.folder")}: ${draft.cwd}` : t("agent_chat.folder")}
+ aria-label={t("agent_chat.folder")}
+ data-testid="composer-folder"
+ className="inline-flex h-7 max-w-[180px] items-center gap-1.5 rounded-lg px-2 text-xs text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
+ >
+ <FolderOpen className="h-3.5 w-3.5 shrink-0" aria-hidden />
+ <span className="truncate font-mono text-[11px]">{folderLeaf(draft.cwd)}</span>
+ </button>
+ <span className="flex-1" />
+ <button
+ type="button"
+ data-jarvis-dictation-trigger
+ onClick={toggleDictation}
+ disabled={!connected}
+ aria-label={dictating ? t("chats_view.dictation_stop") : t("chats_view.dictation_start")}
+ title={dictating ? t("chats_view.dictation_stop") : t("chats_view.dictation_start")}
+ className={cn(
+ "inline-flex h-8 w-8 items-center justify-center rounded-lg border transition-colors disabled:opacity-50",
+ dictating
+ ? "animate-jarvis-pulse border-primary/50 bg-primary/15 text-primary"
+ : "border-transparent text-muted-foreground hover:bg-secondary hover:text-foreground",
+ )}
+ >
+ {dictating ? <Square className="h-4 w-4" /> : <Mic className="h-4 w-4" />}
+ </button>
+ {running ? (
+ <button
+ type="button"
+ onClick={() => void cancel()}
+ aria-label={t("agent_chat.stop")}
+ title={t("agent_chat.stop")}
+ data-testid="composer-stop"
+ className="inline-flex h-8 w-8 items-center justify-center rounded-lg bg-foreground text-background transition-colors hover:bg-foreground/90"
+ >
+ <Square className="h-3.5 w-3.5" />
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={() => void onSend()}
+ disabled={!canSend}
+ aria-label={t("agent_chat.send")}
+ data-testid="composer-send"
+ className={cn(
+ "inline-flex h-8 w-8 items-center justify-center rounded-lg transition-colors",
+ canSend
+ ? "bg-primary text-primary-foreground hover:bg-primary/90"
+ : "bg-secondary text-muted-foreground/60",
+ )}
+ >
+ <ArrowUp className="h-4 w-4" />
+ </button>
+ )}
+ </div>
+ {provider && !provider.connected && (
+ <div
+ className="flex items-center gap-2 px-1 text-xs text-muted-foreground"
+ data-testid="composer-connect-hint"
+ >
+ <span>
+ {fill(
+ provider.cli_installed === false
+ ? t("agent_chat.hint_not_installed")
+ : t("agent_chat.hint_connect"),
+ { provider: provider.label },
+ )}
+ </span>
+ <button
+ type="button"
+ onClick={() => setActiveSection("apikeys")}
+ className="font-medium text-primary hover:underline"
+ >
+ {t("agent_chat.open_api_keys")}
+ </button>
+ </div>
+ )}
+ {lastError && (
+ <div className="px-1 text-xs text-destructive" role="alert" data-testid="composer-error">
+ {lastError}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** One compact pick on the composer's bottom row — a pill-sized Combobox. */
+function Pick({
+ testId,
+ ariaLabel,
+ value,
+ groups,
+ onChange,
+ fallbackLabel,
+ searchPlaceholder,
+ icon,
+ disabled,
+ title,
+ className,
+}: {
+ testId: string;
+ ariaLabel: string;
+ value: string;
+ groups: ComboboxGroup[];
+ onChange: (value: string) => void;
+ fallbackLabel?: string;
+ searchPlaceholder?: string;
+ icon?: React.ReactNode;
+ disabled?: boolean;
+ title?: string;
+ className?: string;
+}) {
+ // The Combobox draws the selected option's own icon; the leading glyph here
+ // is the column's, shown when the option has none (model, effort, permission).
+ const selectedHasIcon = groups.some((g) => g.options.some((o) => o.value === value && o.icon));
+ return (
+ <span className={cn("inline-flex min-w-0 items-center", className)} title={title}>
+ {icon && !selectedHasIcon && (
+ <span className="-mr-6 ml-2 shrink-0 text-muted-foreground" aria-hidden>
+ {icon}
+ </span>
+ )}
+ <Combobox
+ value={value}
+ groups={groups}
+ onChange={onChange}
+ ariaLabel={ariaLabel}
+ fallbackLabel={fallbackLabel}
+ searchPlaceholder={searchPlaceholder}
+ disabled={disabled}
+ testId={testId}
+ className={cn(
+ "h-7 w-auto max-w-[200px] gap-1.5 rounded-lg border-transparent bg-transparent py-0 pr-1.5 text-xs font-medium text-foreground shadow-none",
+ "hover:border-transparent hover:bg-secondary focus-visible:ring-1",
+ icon && !selectedHasIcon ? "pl-7" : "pl-1.5",
+ )}
+ />
+ </span>
+ );
+}
+
+export function effortLabel(level: string, t: (key: string) => string): string {
+ switch (level) {
+ case "":
+ return t("agent_chat.effort_default");
+ case "none":
+ return t("agent_chat.effort_none");
+ case "minimal":
+ return t("agent_chat.effort_minimal");
+ case "low":
+ return t("agent_chat.effort_low");
+ case "medium":
+ return t("agent_chat.effort_medium");
+ case "high":
+ return t("agent_chat.effort_high");
+ case "xhigh":
+ return t("agent_chat.effort_xhigh");
+ case "max":
+ return t("agent_chat.effort_max");
+ case "ultra":
+ return t("agent_chat.effort_ultra");
+ default:
+ return level;
+ }
+}
+
+function folderLeaf(path: string): string {
+ if (!path) return "~";
+ const trimmed = path.replace(/[\\/]+$/, "");
+ const parts = trimmed.split(/[\\/]/);
+ return parts[parts.length - 1] || trimmed;
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx
new file mode 100644
index 0000000000..af23d099b4
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx
@@ -0,0 +1,447 @@
+import { memo, useEffect, useState } from "react";
+import ReactMarkdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import {
+ Check,
+ ChevronRight,
+ CircleAlert,
+ FileDiff,
+ FilePen,
+ FileText,
+ FolderSearch,
+ Globe,
+ ShieldQuestion,
+ TerminalSquare,
+ Wrench,
+ X,
+ type LucideIcon,
+} from "lucide-react";
+
+import { ProviderLogo } from "@/components/providers/ProviderLogo";
+import { formatThoughtDuration } from "@/components/home/TurnSteps";
+import type {
+ ReasoningBlock,
+ TextBlock,
+ TimelineItem,
+ ToolBlock,
+ TurnItem,
+} from "@/components/agentchat/reduce";
+import type { ApprovalDecision } from "@/lib/agentChatApi";
+import { effortLabel } from "@/components/agentchat/AgentComposer";
+import { fill, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+
+/**
+ * The agent chat column — the person's lines in a quiet bubble on the
+ * right, each assistant turn flush-left under a byline that says who
+ * answered (the provider's mark, the model, the effort). Inside a turn, in
+ * the order they happened: reasoning folded to "Thought for Ns", tool
+ * calls as rows you can open to read the input and output, approval cards
+ * where the runner asked, and the answer as Markdown.
+ */
+export function AgentTimeline({
+ items,
+ assistantName,
+ providerLabel,
+ onDecide,
+}: {
+ items: TimelineItem[];
+ assistantName: string;
+ providerLabel: (providerId: string) => string;
+ onDecide: (approvalId: string, decision: ApprovalDecision) => void;
+}) {
+ return (
+ <>
+ {items.map((item) => {
+ if (item.type === "user") {
+ return (
+ <div
+ key={item.id}
+ className="flex justify-end"
+ data-testid="agent-message-user"
+ data-message-id={item.id}
+ >
+ <div className="max-w-[78%] rounded-2xl rounded-br-md border border-border bg-secondary px-4 py-2.5 text-[15px] leading-relaxed text-foreground">
+ <div className="whitespace-pre-wrap">{item.text}</div>
+ </div>
+ </div>
+ );
+ }
+ if (item.type === "error") {
+ return (
+ <div
+ key={item.id}
+ data-message-id={item.id}
+ className="mx-auto flex max-w-[85%] items-center gap-2 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive"
+ >
+ <CircleAlert className="h-3.5 w-3.5 shrink-0" aria-hidden />
+ <span>{item.text}</span>
+ </div>
+ );
+ }
+ return (
+ <Turn
+ key={item.id}
+ turn={item}
+ assistantName={assistantName}
+ providerLabel={providerLabel(item.provider)}
+ onDecide={onDecide}
+ />
+ );
+ })}
+ </>
+ );
+}
+
+const Turn = memo(function Turn({
+ turn,
+ assistantName,
+ providerLabel,
+ onDecide,
+}: {
+ turn: TurnItem;
+ assistantName: string;
+ providerLabel: string;
+ onDecide: (approvalId: string, decision: ApprovalDecision) => void;
+}) {
+ const t = useT();
+ const live = turn.status === "running";
+ const elapsed = useElapsedMs(live ? turn.startedMs : null);
+ const hasText = turn.blocks.some((b) => b.kind === "text" && b.text.trim());
+
+ return (
+ <div
+ className="flex flex-col gap-1.5 px-1"
+ data-testid="agent-turn"
+ data-message-id={turn.id}
+ data-status={turn.status}
+ >
+ <div className="flex items-center gap-2 font-mono text-[10px] uppercase tracking-[0.14em] text-primary">
+ <span className="h-1 w-1 rounded-full bg-primary" aria-hidden />
+ <span>{assistantName}</span>
+ <span className="inline-flex items-center gap-1.5 normal-case tracking-normal text-muted-foreground">
+ <ProviderLogo providerId={turn.provider} label={providerLabel} size="sm" />
+ <span>{providerLabel}</span>
+ {turn.model && <span className="text-muted-foreground/70">· {turn.model}</span>}
+ {turn.effort && (
+ <span className="text-muted-foreground/70">· {effortLabel(turn.effort, t)}</span>
+ )}
+ </span>
+ </div>
+
+ {turn.blocks.length > 0 && (
+ <div className="flex flex-col gap-1">
+ {turn.blocks.map((block) => {
+ if (block.kind === "text") return <Prose key={block.id} block={block} />;
+ if (block.kind === "reasoning") return <Reasoning key={block.id} block={block} />;
+ return <ToolRow key={block.callId} block={block} onDecide={onDecide} />;
+ })}
+ </div>
+ )}
+
+ {live && !hasText && (
+ <div
+ className="flex items-center gap-2 text-xs text-muted-foreground"
+ data-testid="agent-turn-live"
+ >
+ <Spinner />
+ <span>
+ {elapsed > 0
+ ? fill(t("agent_chat.working_for"), { duration: formatThoughtDuration(elapsed) })
+ : t("agent_chat.working")}
+ </span>
+ </div>
+ )}
+
+ {turn.status === "error" && turn.error && (
+ <div
+ className="flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive"
+ role="alert"
+ data-testid="agent-turn-error"
+ >
+ <CircleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden />
+ <span className="whitespace-pre-wrap break-words">{turn.error}</span>
+ </div>
+ )}
+ {turn.status === "cancelled" && (
+ <div className="text-xs italic text-muted-foreground">{t("agent_chat.turn_cancelled")}</div>
+ )}
+ {turn.status !== "running" && (turn.durationMs || turn.costUsd !== null) && (
+ <div className="flex items-center gap-2 font-mono text-[10px] text-muted-foreground/70">
+ {turn.durationMs ? <span>{formatThoughtDuration(turn.durationMs)}</span> : null}
+ {usageLine(turn.usage) && <span>· {usageLine(turn.usage)}</span>}
+ {turn.costUsd !== null && turn.costUsd > 0 && <span>· ${turn.costUsd.toFixed(4)}</span>}
+ </div>
+ )}
+ </div>
+ );
+});
+
+function usageLine(usage: Record<string, unknown> | null): string {
+ if (!usage) return "";
+ const inp = num(usage.input_tokens ?? usage.input);
+ const out = num(usage.output_tokens ?? usage.output);
+ if (inp === null && out === null) return "";
+ return `${inp ?? 0} in · ${out ?? 0} out`;
+}
+
+function num(v: unknown): number | null {
+ return typeof v === "number" && Number.isFinite(v) ? v : null;
+}
+
+function Prose({ block }: { block: TextBlock }) {
+ if (!block.text.trim()) return null;
+ return (
+ <div
+ data-testid="agent-text"
+ className={cn(
+ "prose prose-neutral max-w-none text-[15px] leading-relaxed dark:prose-invert [overflow-wrap:anywhere]",
+ "prose-p:my-2 prose-headings:font-display prose-headings:tracking-tight prose-h1:text-xl prose-h2:text-lg prose-h3:text-base",
+ "prose-a:text-primary prose-a:no-underline hover:prose-a:underline",
+ "prose-code:rounded prose-code:bg-muted/60 prose-code:px-1 prose-code:py-0.5 prose-code:font-mono prose-code:text-[0.85em] prose-code:font-normal prose-code:before:hidden prose-code:after:hidden",
+ "prose-pre:my-2 prose-pre:border prose-pre:border-border prose-pre:bg-card/80 prose-pre:text-[13px]",
+ "prose-li:my-0.5 prose-ul:my-2 prose-ol:my-2",
+ )}
+ >
+ <ReactMarkdown remarkPlugins={[remarkGfm]}>{block.text}</ReactMarkdown>
+ </div>
+ );
+}
+
+function Reasoning({ block }: { block: ReasoningBlock }) {
+ const t = useT();
+ const [open, setOpen] = useState(false);
+ const header = block.live
+ ? t("agent_chat.thinking")
+ : block.durationMs
+ ? fill(t("agent_chat.thought_for"), { duration: formatThoughtDuration(block.durationMs) })
+ : t("agent_chat.thought");
+ return (
+ <div data-testid="agent-reasoning" data-live={block.live || undefined}>
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ aria-expanded={open}
+ className="inline-flex items-center gap-1.5 rounded-md py-0.5 pr-2 text-xs text-muted-foreground transition-colors hover:text-foreground"
+ >
+ {block.live ? (
+ <Spinner />
+ ) : (
+ <ChevronRight
+ className={cn("h-3.5 w-3.5 transition-transform", open && "rotate-90")}
+ aria-hidden
+ />
+ )}
+ <span>{header}</span>
+ </button>
+ {open && block.text && (
+ <div className="ml-2 mt-1 border-l border-border pl-3 text-xs italic leading-relaxed text-muted-foreground whitespace-pre-wrap">
+ {block.text}
+ </div>
+ )}
+ </div>
+ );
+}
+
+const TOOL_ICON: Array<[RegExp, LucideIcon]> = [
+ [/^(bash|run_?command|shell|command|exec)/i, TerminalSquare],
+ [/^(edit|multi_?edit|apply_?patch|str_replace)/i, FileDiff],
+ [/^(write|create_?file|notebook_?edit)/i, FilePen],
+ [/^(read|cat|view|open_?file)/i, FileText],
+ [/^(glob|grep|ls|list|search|find)/i, FolderSearch],
+ [/^(web_?fetch|web_?search|fetch|browse)/i, Globe],
+];
+
+function toolIcon(name: string): LucideIcon {
+ for (const [re, icon] of TOOL_ICON) if (re.test(name)) return icon;
+ return Wrench;
+}
+
+/** A one-line gist of a tool's input: the command, the path, the pattern. */
+function inputSummary(input: unknown): string {
+ if (input === null || input === undefined) return "";
+ if (typeof input === "string") return input;
+ if (typeof input !== "object") return String(input);
+ const obj = input as Record<string, unknown>;
+ for (const key of ["command", "cmd", "file_path", "path", "pattern", "query", "url", "description"]) {
+ const v = obj[key];
+ if (typeof v === "string" && v.trim()) return v;
+ }
+ const first = Object.values(obj).find((v) => typeof v === "string" && v.trim());
+ return typeof first === "string" ? first : "";
+}
+
+function pretty(value: unknown): string {
+ if (typeof value === "string") return value;
+ try {
+ return JSON.stringify(value, null, 2);
+ } catch {
+ return String(value);
+ }
+}
+
+function ToolRow({
+ block,
+ onDecide,
+}: {
+ block: ToolBlock;
+ onDecide: (approvalId: string, decision: ApprovalDecision) => void;
+}) {
+ const t = useT();
+ const [open, setOpen] = useState(false);
+ const pending = Boolean(block.approval && block.approval.decision === null);
+ const denied = block.approval?.decision === "deny" || block.approval?.decision === "cancel";
+ const done = block.output !== null;
+ const Icon = toolIcon(block.name);
+ const summary = inputSummary(block.input);
+
+ return (
+ <div
+ data-testid="agent-tool"
+ data-tool={block.name}
+ data-state={pending ? "pending" : denied ? "denied" : done ? (block.isError ? "error" : "done") : "running"}
+ className={cn(
+ "rounded-lg border text-xs",
+ pending ? "border-primary/40 bg-primary/5" : "border-border/70 bg-secondary/30",
+ )}
+ >
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ aria-expanded={open}
+ className="flex w-full min-w-0 items-center gap-2 px-2.5 py-1.5 text-left"
+ >
+ <span className="grid h-5 w-5 shrink-0 place-items-center">
+ {!done && !pending && !denied ? (
+ <Spinner />
+ ) : block.isError ? (
+ <CircleAlert className="h-3.5 w-3.5 text-destructive" aria-hidden />
+ ) : pending ? (
+ <ShieldQuestion className="h-3.5 w-3.5 text-primary" aria-hidden />
+ ) : (
+ <Icon className="h-3.5 w-3.5 text-muted-foreground" aria-hidden />
+ )}
+ </span>
+ <span className="shrink-0 font-medium text-foreground">{block.name}</span>
+ {summary && (
+ <span className="min-w-0 flex-1 truncate font-mono text-[11px] text-muted-foreground">
+ {summary}
+ </span>
+ )}
+ {!summary && <span className="flex-1" />}
+ {block.durationMs !== null && (
+ <span className="shrink-0 font-mono text-[10px] text-muted-foreground/70">
+ {formatStepDuration(block.durationMs)}
+ </span>
+ )}
+ <ChevronRight
+ className={cn("h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform", open && "rotate-90")}
+ aria-hidden
+ />
+ </button>
+
+ {pending && block.approval && (
+ <div
+ className="flex flex-col gap-2 border-t border-primary/20 px-2.5 py-2"
+ data-testid="agent-approval"
+ >
+ <div className="text-foreground">
+ <span className="font-medium">{t("agent_chat.approval_title")}</span>{" "}
+ <span className="text-muted-foreground">{block.approval.summary || summary}</span>
+ </div>
+ <div className="flex flex-wrap items-center gap-1.5">
+ <button
+ type="button"
+ onClick={() => onDecide(block.approval!.approvalId, "allow")}
+ className="inline-flex h-7 items-center gap-1 rounded-md bg-primary px-2.5 text-xs font-medium text-primary-foreground hover:bg-primary/90"
+ data-testid="approval-allow"
+ >
+ <Check className="h-3.5 w-3.5" aria-hidden />
+ {t("agent_chat.approval_allow")}
+ </button>
+ <button
+ type="button"
+ onClick={() => onDecide(block.approval!.approvalId, "allow_always")}
+ className="inline-flex h-7 items-center rounded-md border border-border px-2.5 text-xs font-medium text-foreground hover:bg-secondary"
+ data-testid="approval-always"
+ >
+ {t("agent_chat.approval_always")}
+ </button>
+ <button
+ type="button"
+ onClick={() => onDecide(block.approval!.approvalId, "deny")}
+ className="inline-flex h-7 items-center gap-1 rounded-md border border-border px-2.5 text-xs font-medium text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
+ data-testid="approval-deny"
+ >
+ <X className="h-3.5 w-3.5" aria-hidden />
+ {t("agent_chat.approval_deny")}
+ </button>
+ </div>
+ </div>
+ )}
+
+ {open && (
+ <div className="flex flex-col gap-2 border-t border-border/60 px-2.5 py-2">
+ {block.input !== undefined && block.input !== null && (
+ <Detail label={t("agent_chat.tool_input")} text={pretty(block.input)} />
+ )}
+ {denied && (
+ <div className="text-muted-foreground">{t("agent_chat.approval_denied")}</div>
+ )}
+ {block.output !== null && (
+ <Detail
+ label={block.isError ? t("agent_chat.tool_error") : t("agent_chat.tool_output")}
+ text={block.output}
+ error={block.isError}
+ />
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function Detail({ label, text, error }: { label: string; text: string; error?: boolean }) {
+ return (
+ <div className="flex flex-col gap-1">
+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-muted-foreground/70">
+ {label}
+ </span>
+ <pre
+ className={cn(
+ "scrollbar-jarvis max-h-72 overflow-auto whitespace-pre-wrap break-words rounded-md border border-border/60 bg-background/60 p-2 font-mono text-[11.5px] leading-relaxed",
+ error ? "text-destructive" : "text-foreground",
+ )}
+ >
+ {text}
+ </pre>
+ </div>
+ );
+}
+
+function formatStepDuration(ms: number): string {
+ if (ms < 10_000) return `${(ms / 1000).toFixed(1)}s`;
+ return formatThoughtDuration(ms);
+}
+
+function Spinner() {
+ return (
+ <span
+ aria-hidden
+ data-testid="agent-spinner"
+ className="inline-block h-3.5 w-3.5 rounded-full border-2 border-primary/25 border-t-primary motion-safe:animate-spin"
+ />
+ );
+}
+
+/** Elapsed wall-clock since `startedTs`, ticking once a second while set. */
+function useElapsedMs(startedTs: number | null): number {
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ if (startedTs === null) return;
+ setNow(Date.now());
+ const id = window.setInterval(() => setNow(Date.now()), 1000);
+ return () => window.clearInterval(id);
+ }, [startedTs]);
+ return startedTs === null ? 0 : Math.max(0, now - startedTs);
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.ts
new file mode 100644
index 0000000000..6edf747439
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/reduce.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from "vitest";
+
+import type { AgentChatEvent } from "@/lib/agentChatApi";
+import { EMPTY_TIMELINE, reduceEvent, reduceEvents, runningTurn, type TurnItem } from "./reduce";
+
+let seq = 0;
+function ev(kind: string, payload: Record<string, unknown>, persisted = true): AgentChatEvent {
+ if (persisted) seq += 1;
+ return { seq: persisted ? seq : 0, ts_ms: 1_000 + seq, kind, payload };
+}
+
+describe("agent-chat reduce", () => {
+ it("folds a full turn: user line, deltas into one text block, tool call + result, finish", () => {
+ const tl = reduceEvents(EMPTY_TIMELINE, [
+ ev("user_message", { text: "hi" }),
+ ev("turn_started", { turn_id: "t1", provider: "claude-api", model: "opus", effort: "high", runner: "claude-cli" }),
+ ev("text_delta", { turn_id: "t1", message_id: "m1", text: "Hel" }, false),
+ ev("text_delta", { turn_id: "t1", message_id: "m1", text: "lo" }, false),
+ ev("tool_call", { turn_id: "t1", call_id: "c1", name: "Read", input: { file_path: "a.py" } }),
+ ev("tool_result", { turn_id: "t1", call_id: "c1", output: "print(1)", is_error: false, duration_ms: 12 }),
+ ev("assistant_text", { turn_id: "t1", message_id: "m1", text: "Hello" }),
+ ev("turn_finished", { turn_id: "t1", status: "done", duration_ms: 900, usage: { input_tokens: 3 } }),
+ ]);
+ expect(tl.items).toHaveLength(2);
+ expect(tl.items[0]).toMatchObject({ type: "user", text: "hi" });
+ const turn = tl.items[1] as TurnItem;
+ expect(turn.status).toBe("done");
+ expect(turn.blocks.map((b) => b.kind)).toEqual(["text", "tool"]);
+ expect(turn.blocks[0]).toMatchObject({ kind: "text", text: "Hello" });
+ expect(turn.blocks[1]).toMatchObject({ kind: "tool", name: "Read", output: "print(1)", durationMs: 12 });
+ expect(turn.durationMs).toBe(900);
+ expect(tl.lastSeq).toBeGreaterThan(0);
+ expect(runningTurn(tl)).toBeNull();
+ });
+
+ it("tracks approvals: pending until resolved, and the tool row carries the decision", () => {
+ let tl = reduceEvents(EMPTY_TIMELINE, [
+ ev("turn_started", { turn_id: "t2", provider: "openai", model: "", effort: "", runner: "api" }),
+ ev("approval_required", { turn_id: "t2", approval_id: "a1", call_id: "c2", name: "RunCommand", input: { command: "rm x" }, summary: "rm x" }),
+ ]);
+ expect(tl.pendingApprovals).toHaveLength(1);
+ expect(runningTurn(tl)?.id).toBe("t2");
+ tl = reduceEvent(tl, ev("approval_resolved", { turn_id: "t2", approval_id: "a1", decision: "deny" }));
+ expect(tl.pendingApprovals).toHaveLength(0);
+ const turn = tl.items[0] as TurnItem;
+ expect(turn.blocks[0]).toMatchObject({ kind: "tool", approval: { approvalId: "a1", decision: "deny" } });
+ });
+
+ it("returns the same object when an event changes nothing", () => {
+ const tl = reduceEvents(EMPTY_TIMELINE, [ev("turn_started", { turn_id: "t3" })]);
+ const same = reduceEvent(tl, ev("text_delta", { turn_id: "t3", message_id: "m", text: "" }, false));
+ expect(same).toBe(tl);
+ const unknownTurn = reduceEvent(tl, ev("tool_call", { turn_id: "nope", call_id: "c" }));
+ expect(unknownTurn.items).toEqual(tl.items);
+ });
+
+ it("closes live reasoning on the finished block and exposes session patches once", () => {
+ let tl = reduceEvents(EMPTY_TIMELINE, [
+ ev("turn_started", { turn_id: "t4" }),
+ ev("reasoning_delta", { turn_id: "t4", text: "hm" }, false),
+ ev("reasoning_delta", { turn_id: "t4", text: "m" }, false),
+ ]);
+ expect((tl.items[0] as TurnItem).blocks[0]).toMatchObject({ kind: "reasoning", text: "hmm", live: true });
+ tl = reduceEvent(tl, ev("reasoning", { turn_id: "t4", text: "hmm!", duration_ms: 400 }));
+ expect((tl.items[0] as TurnItem).blocks[0]).toMatchObject({ kind: "reasoning", text: "hmm!", live: false, durationMs: 400 });
+ tl = reduceEvent(tl, ev("session_updated", { permission_mode: "auto" }));
+ expect(tl.sessionPatch).toEqual({ permission_mode: "auto" });
+ tl = reduceEvent(tl, ev("turn_finished", { turn_id: "t4", status: "cancelled" }));
+ expect(tl.sessionPatch).toBeNull();
+ expect((tl.items[0] as TurnItem).status).toBe("cancelled");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts b/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts
new file mode 100644
index 0000000000..baf382b855
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts
@@ -0,0 +1,430 @@
+import type { AgentChatEvent } from "@/lib/agentChatApi";
+
+/**
+ * Fold the agent-chat event log into the timeline the column renders.
+ *
+ * The backend speaks ONE vocabulary for the persisted log and the live
+ * stream (jarvis/agent_chat/events.py), so this reducer serves both: a
+ * reopened session replays its stored events through it, and the socket
+ * keeps feeding it live ones. The result is immutable per step — an event
+ * that changes nothing returns the same object, so the store can skip the
+ * re-render.
+ *
+ * Shape: a list of items, each either the person's message or one assistant
+ * turn. A turn holds ordered blocks — text, reasoning, tool calls (with
+ * their result and, when the runner asked, the approval card) — plus the
+ * turn's status and the usage the runner reported at the end.
+ */
+
+export interface TextBlock {
+ kind: "text";
+ id: string;
+ text: string;
+}
+
+export interface ReasoningBlock {
+ kind: "reasoning";
+ id: string;
+ text: string;
+ durationMs: number | null;
+ /** Still streaming — the finished block carries the duration. */
+ live: boolean;
+}
+
+export interface ApprovalState {
+ approvalId: string;
+ summary: string;
+ /** Set once the person (or a cancel) decided. */
+ decision: string | null;
+}
+
+export interface ToolBlock {
+ kind: "tool";
+ callId: string;
+ name: string;
+ input: unknown;
+ output: string | null;
+ isError: boolean;
+ durationMs: number | null;
+ approval: ApprovalState | null;
+}
+
+export type TurnBlock = TextBlock | ReasoningBlock | ToolBlock;
+
+export type TurnStatus = "running" | "done" | "cancelled" | "error";
+
+export interface UserItem {
+ type: "user";
+ id: string;
+ text: string;
+ tsMs: number;
+}
+
+export interface TurnItem {
+ type: "turn";
+ id: string;
+ provider: string;
+ model: string;
+ effort: string;
+ runner: string;
+ status: TurnStatus;
+ blocks: TurnBlock[];
+ startedMs: number;
+ durationMs: number | null;
+ usage: Record<string, unknown> | null;
+ costUsd: number | null;
+ error: string | null;
+}
+
+export interface ErrorItem {
+ type: "error";
+ id: string;
+ text: string;
+ tsMs: number;
+}
+
+export type TimelineItem = UserItem | TurnItem | ErrorItem;
+
+export interface PendingApproval {
+ approvalId: string;
+ turnId: string;
+ callId: string;
+ name: string;
+ input: unknown;
+ summary: string;
+}
+
+export interface Timeline {
+ items: TimelineItem[];
+ pendingApprovals: PendingApproval[];
+ /** Highest persisted seq folded so far — the `?after=` for a reconnect. */
+ lastSeq: number;
+ /** Fields a `session_updated` event changed, applied by the store. */
+ sessionPatch: Record<string, unknown> | null;
+}
+
+export const EMPTY_TIMELINE: Timeline = {
+ items: [],
+ pendingApprovals: [],
+ lastSeq: 0,
+ sessionPatch: null,
+};
+
+function str(v: unknown, fallback = ""): string {
+ return typeof v === "string" ? v : fallback;
+}
+
+function num(v: unknown): number | null {
+ return typeof v === "number" && Number.isFinite(v) ? v : null;
+}
+
+function findTurn(items: TimelineItem[], turnId: string): number {
+ for (let i = items.length - 1; i >= 0; i -= 1) {
+ const it = items[i];
+ if (it.type === "turn" && it.id === turnId) return i;
+ }
+ return -1;
+}
+
+function replaceAt<T>(arr: T[], index: number, value: T): T[] {
+ const next = arr.slice();
+ next[index] = value;
+ return next;
+}
+
+function updateTurn(
+ tl: Timeline,
+ turnId: string,
+ fn: (turn: TurnItem) => TurnItem,
+): Timeline {
+ const idx = findTurn(tl.items, turnId);
+ if (idx < 0) return tl;
+ const turn = tl.items[idx] as TurnItem;
+ const next = fn(turn);
+ if (next === turn) return tl;
+ return { ...tl, items: replaceAt(tl.items, idx, next) };
+}
+
+function upsertBlock<B extends TurnBlock>(
+ turn: TurnItem,
+ match: (b: TurnBlock) => boolean,
+ make: (existing: B | null) => B,
+): TurnItem {
+ const i = turn.blocks.findIndex(match);
+ if (i < 0) return { ...turn, blocks: [...turn.blocks, make(null)] };
+ const existing = turn.blocks[i] as B;
+ const next = make(existing);
+ if (next === existing) return turn;
+ return { ...turn, blocks: replaceAt(turn.blocks, i, next) };
+}
+
+/** Fold one event. Pure; returns `tl` itself when nothing changed. */
+export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {
+ const p = ev.payload ?? {};
+ const seq = typeof ev.seq === "number" ? ev.seq : 0;
+ const base: Timeline =
+ seq > tl.lastSeq ? { ...tl, lastSeq: seq, sessionPatch: null } : tl.sessionPatch ? { ...tl, sessionPatch: null } : tl;
+ const turnId = str(p.turn_id);
+
+ switch (ev.kind) {
+ case "user_message":
+ return {
+ ...base,
+ items: [
+ ...base.items,
+ { type: "user", id: `u-${seq || ev.ts_ms}`, text: str(p.text), tsMs: ev.ts_ms },
+ ],
+ };
+
+ case "turn_started":
+ return {
+ ...base,
+ items: [
+ ...base.items,
+ {
+ type: "turn",
+ id: turnId,
+ provider: str(p.provider),
+ model: str(p.model),
+ effort: str(p.effort),
+ runner: str(p.runner),
+ status: "running",
+ blocks: [],
+ startedMs: ev.ts_ms,
+ durationMs: null,
+ usage: null,
+ costUsd: null,
+ error: null,
+ },
+ ],
+ };
+
+ case "text_delta": {
+ const id = str(p.message_id, "live");
+ const delta = str(p.text);
+ if (!delta) return base;
+ return updateTurn(base, turnId, (turn) =>
+ upsertBlock<TextBlock>(
+ turn,
+ (b) => b.kind === "text" && b.id === id,
+ (ex) => ({ kind: "text", id, text: (ex?.text ?? "") + delta }),
+ ),
+ );
+ }
+
+ case "assistant_text": {
+ const id = str(p.message_id, "live");
+ const text = str(p.text);
+ return updateTurn(base, turnId, (turn) =>
+ upsertBlock<TextBlock>(
+ turn,
+ (b) => b.kind === "text" && b.id === id,
+ (ex) => (ex && ex.text === text ? ex : { kind: "text", id, text }),
+ ),
+ );
+ }
+
+ case "reasoning_delta": {
+ const delta = str(p.text);
+ if (!delta) return base;
+ return updateTurn(base, turnId, (turn) => {
+ // Deltas grow the newest live reasoning block; a finished one starts a new block.
+ const last = turn.blocks[turn.blocks.length - 1];
+ if (last && last.kind === "reasoning" && last.live) {
+ return {
+ ...turn,
+ blocks: replaceAt(turn.blocks, turn.blocks.length - 1, {
+ ...last,
+ text: last.text + delta,
+ }),
+ };
+ }
+ return {
+ ...turn,
+ blocks: [
+ ...turn.blocks,
+ { kind: "reasoning", id: `r-${turn.blocks.length}`, text: delta, durationMs: null, live: true },
+ ],
+ };
+ });
+ }
+
+ case "reasoning": {
+ const text = str(p.text);
+ const durationMs = num(p.duration_ms);
+ return updateTurn(base, turnId, (turn) => {
+ const last = turn.blocks[turn.blocks.length - 1];
+ if (last && last.kind === "reasoning" && last.live) {
+ return {
+ ...turn,
+ blocks: replaceAt(turn.blocks, turn.blocks.length - 1, {
+ ...last,
+ text: text || last.text,
+ durationMs,
+ live: false,
+ }),
+ };
+ }
+ if (!text) return turn;
+ return {
+ ...turn,
+ blocks: [
+ ...turn.blocks,
+ { kind: "reasoning", id: `r-${turn.blocks.length}`, text, durationMs, live: false },
+ ],
+ };
+ });
+ }
+
+ case "tool_call": {
+ const callId = str(p.call_id);
+ return updateTurn(base, turnId, (turn) =>
+ upsertBlock<ToolBlock>(
+ turn,
+ (b) => b.kind === "tool" && b.callId === callId,
+ (ex) =>
+ ex ?? {
+ kind: "tool",
+ callId,
+ name: str(p.name),
+ input: p.input,
+ output: null,
+ isError: false,
+ durationMs: null,
+ approval: null,
+ },
+ ),
+ );
+ }
+
+ case "tool_result": {
+ const callId = str(p.call_id);
+ return updateTurn(base, turnId, (turn) =>
+ upsertBlock<ToolBlock>(
+ turn,
+ (b) => b.kind === "tool" && b.callId === callId,
+ (ex) => ({
+ kind: "tool",
+ callId,
+ name: ex?.name ?? str(p.name),
+ input: ex?.input,
+ output: str(p.output, ""),
+ isError: Boolean(p.is_error),
+ durationMs: num(p.duration_ms),
+ approval: ex?.approval ?? null,
+ }),
+ ),
+ );
+ }
+
+ case "approval_required": {
+ const approvalId = str(p.approval_id);
+ const callId = str(p.call_id);
+ const pending: PendingApproval = {
+ approvalId,
+ turnId,
+ callId,
+ name: str(p.name),
+ input: p.input,
+ summary: str(p.summary),
+ };
+ const withTurn = updateTurn(base, turnId, (turn) =>
+ upsertBlock<ToolBlock>(
+ turn,
+ (b) => b.kind === "tool" && b.callId === callId,
+ (ex) => ({
+ kind: "tool",
+ callId,
+ name: ex?.name ?? pending.name,
+ input: ex?.input ?? pending.input,
+ output: ex?.output ?? null,
+ isError: ex?.isError ?? false,
+ durationMs: ex?.durationMs ?? null,
+ approval: { approvalId, summary: pending.summary, decision: null },
+ }),
+ ),
+ );
+ return {
+ ...withTurn,
+ pendingApprovals: [
+ ...withTurn.pendingApprovals.filter((a) => a.approvalId !== approvalId),
+ pending,
+ ],
+ };
+ }
+
+ case "approval_resolved": {
+ const approvalId = str(p.approval_id);
+ const decision = str(p.decision);
+ const withTurn = updateTurn(base, turnId, (turn) => {
+ const i = turn.blocks.findIndex(
+ (b) => b.kind === "tool" && b.approval?.approvalId === approvalId,
+ );
+ if (i < 0) return turn;
+ const block = turn.blocks[i] as ToolBlock;
+ return {
+ ...turn,
+ blocks: replaceAt(turn.blocks, i, {
+ ...block,
+ approval: block.approval ? { ...block.approval, decision } : null,
+ }),
+ };
+ });
+ return {
+ ...withTurn,
+ pendingApprovals: withTurn.pendingApprovals.filter((a) => a.approvalId !== approvalId),
+ };
+ }
+
+ case "turn_finished": {
+ const status = str(p.status, "done") as TurnStatus;
+ const finished = updateTurn(base, turnId, (turn) => ({
+ ...turn,
+ status: status === "running" ? "done" : status,
+ // A turn that ended mid-stream closes its live reasoning block.
+ blocks: turn.blocks.map((b) => (b.kind === "reasoning" && b.live ? { ...b, live: false } : b)),
+ durationMs: num(p.duration_ms),
+ usage: p.usage && typeof p.usage === "object" ? (p.usage as Record<string, unknown>) : null,
+ costUsd: num(p.cost_usd),
+ error: str(p.error, "") || null,
+ }));
+ return {
+ ...finished,
+ pendingApprovals: finished.pendingApprovals.filter((a) => a.turnId !== turnId),
+ };
+ }
+
+ case "session_updated":
+ return { ...base, sessionPatch: { ...p } };
+
+ case "error": {
+ const text = str(p.message);
+ if (!text) return base;
+ if (turnId && findTurn(base.items, turnId) >= 0) {
+ return updateTurn(base, turnId, (turn) => ({ ...turn, error: text }));
+ }
+ return {
+ ...base,
+ items: [...base.items, { type: "error", id: `e-${seq || ev.ts_ms}`, text, tsMs: ev.ts_ms }],
+ };
+ }
+
+ default:
+ return base;
+ }
+}
+
+export function reduceEvents(tl: Timeline, events: AgentChatEvent[]): Timeline {
+ let cur = tl;
+ for (const ev of events) cur = reduceEvent(cur, ev);
+ return cur;
+}
+
+/** The turn still running, if any. */
+export function runningTurn(tl: Timeline): TurnItem | null {
+ for (let i = tl.items.length - 1; i >= 0; i -= 1) {
+ const it = tl.items[i];
+ if (it.type === "turn") return it.status === "running" ? it : null;
+ }
+ return null;
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/useComposerDictation.ts b/jarvis/ui/web/frontend/src/components/agentchat/useComposerDictation.ts
new file mode 100644
index 0000000000..cec9be8426
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/useComposerDictation.ts
@@ -0,0 +1,69 @@
+import { useCallback, useEffect, useRef } from "react";
+
+import { getWSClient } from "@/hooks/useWebSocket";
+import { useEventStore } from "@/store/events";
+
+/**
+ * Microphone dictation into a composer's text box — the live interim
+ * transcript mirrored while speaking, the final transcript appended once.
+ *
+ * Lifted from components/ChatInput.tsx so the agent composer dictates the
+ * same way the classic one does: the same `stt_dictate` command, the same
+ * store flags, the same one-shot commit on `dictationCommitSeq`.
+ *
+ * The base is the snapshot taken at dictation START only while the live
+ * mirror is running — i.e. for a dictation this composer began. A dictation
+ * started by the keyboard shortcut never calls `start`, so its final text
+ * appends to whatever the box holds at that moment (the functional update
+ * reads it without dragging `value` into a dependency array).
+ */
+export function useComposerDictation(
+ value: string,
+ setValue: (next: string | ((current: string) => string)) => void,
+) {
+ const dictating = useEventStore((s) => s.dictating);
+ const dictationText = useEventStore((s) => s.dictationText);
+ const dictationCommitSeq = useEventStore((s) => s.dictationCommitSeq);
+ const setDictating = useEventStore((s) => s.setDictating);
+ const baseRef = useRef("");
+ const mirroringRef = useRef(false);
+ const lastCommitSeqRef = useRef(dictationCommitSeq);
+
+ useEffect(() => {
+ if (!dictating) return;
+ const base = baseRef.current;
+ const sep = base && dictationText ? " " : "";
+ setValue(base + sep + dictationText);
+ }, [dictating, dictationText, setValue]);
+
+ useEffect(() => {
+ if (dictationCommitSeq === lastCommitSeqRef.current) return;
+ lastCommitSeqRef.current = dictationCommitSeq;
+ const finalText = useEventStore.getState().dictationCommitText;
+ setValue((current) => {
+ const base = mirroringRef.current ? baseRef.current : current;
+ const sep = base && finalText ? " " : "";
+ return base + sep + finalText;
+ });
+ mirroringRef.current = false;
+ }, [dictationCommitSeq, setValue]);
+
+ const start = useCallback(() => {
+ baseRef.current = value;
+ mirroringRef.current = true;
+ setDictating(true);
+ getWSClient()?.send({ type: "command", action: "stt_dictate", payload: { mode: "start" } });
+ }, [value, setDictating]);
+
+ const stop = useCallback(() => {
+ getWSClient()?.send({ type: "command", action: "stt_dictate", payload: { mode: "stop" } });
+ setDictating(false);
+ }, [setDictating]);
+
+ const toggle = useCallback(() => {
+ if (dictating) stop();
+ else start();
+ }, [dictating, start, stop]);
+
+ return { dictating, start, stop, toggle };
+}
diff --git a/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx b/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx
index bdd5858100..def86b5d9d 100644
--- a/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/ChatStage.test.tsx
@@ -1,13 +1,66 @@
-import { act, cleanup, render as rtlRender, screen, within } from "@testing-library/react";
+import { act, cleanup, fireEvent, render as rtlRender, screen, within } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ChatStage } from "@/components/home/ChatStage";
-import type { ThinkingStep } from "@/lib/thinkingSteps";
-import { useEventStore, type ChatMessage } from "@/store/events";
+import { EMPTY_TIMELINE, reduceEvents } from "@/components/agentchat/reduce";
+import type { AgentChatCatalog, AgentChatEvent } from "@/lib/agentChatApi";
+import { useAgentChatStore } from "@/store/agentChat";
+import { useEventStore } from "@/store/events";
-// The composer inside the stage names the model that will answer (a query),
-// so the stage mounts under a query client like the app.
+const CATALOG: AgentChatCatalog = {
+ default_cwd: "C:\\work",
+ shell: "pwsh",
+ providers: [
+ {
+ id: "claude-api",
+ label: "Anthropic Claude",
+ family: "claude",
+ runner: "claude-cli",
+ models_source: "curated",
+ curated_models: [
+ { id: "claude-opus-5", label: "Claude Opus 5" },
+ { id: "claude-sonnet-5", label: "Claude Sonnet 5" },
+ ],
+ default_model: "",
+ keyless: false,
+ native_resume: true,
+ effort_levels: ["low", "medium", "high", "xhigh", "max"],
+ default_effort: "high",
+ permission_modes: [
+ { id: "default", label: "Ask before acting", description: "" },
+ { id: "acceptEdits", label: "Auto-accept edits", description: "" },
+ { id: "plan", label: "Plan", description: "" },
+ { id: "bypassPermissions", label: "Bypass permissions", description: "" },
+ ],
+ default_permission_mode: "acceptEdits",
+ cli_installed: true,
+ },
+ {
+ id: "openai-codex",
+ label: "OpenAI Codex",
+ family: "openai",
+ runner: "codex-cli",
+ models_source: "curated",
+ curated_models: [{ id: "gpt-5.4", label: "GPT-5.4" }],
+ default_model: "",
+ keyless: false,
+ native_resume: true,
+ effort_levels: ["minimal", "low", "medium", "high", "xhigh"],
+ default_effort: "medium",
+ permission_modes: [
+ { id: "read-only", label: "Read only", description: "" },
+ { id: "auto", label: "Auto", description: "" },
+ { id: "full-access", label: "Full access", description: "" },
+ ],
+ default_permission_mode: "auto",
+ cli_installed: false,
+ },
+ ],
+};
+
+// The greeting reads the profile name (a query), so the stage mounts under a
+// query client like the app.
function render(ui: React.ReactElement) {
const client = new QueryClient({
defaultOptions: { queries: { retry: false, staleTime: Infinity } },
@@ -15,143 +68,128 @@ function render(ui: React.ReactElement) {
return rtlRender(<QueryClientProvider client={client}>{ui}</QueryClientProvider>);
}
-function msg(id: string, role: ChatMessage["role"], content: string): ChatMessage {
- return { id, role, content, ts: Number(id.replace(/\D/g, "")) || 0 };
-}
-
-function toolStep(id: string, tool: string, status: ThinkingStep["status"] = "done"): ThinkingStep {
- return {
- id,
- kind: "tool",
- labelKey: "thinking.step_tool",
- detail: tool,
- status,
- startedTs: 0,
- durationMs: status === "active" ? undefined : 500,
- };
+let seq = 0;
+function ev(kind: string, payload: Record<string, unknown>): AgentChatEvent {
+ seq += 1;
+ return { seq, ts_ms: 1_000 + seq, kind, payload };
}
-describe("ChatStage", () => {
+describe("ChatStage (agent chat)", () => {
let scrollTo: ReturnType<typeof vi.fn>;
beforeEach(() => {
- // jsdom has no element scrolling; the stage must call the standard API.
scrollTo = vi.fn();
Object.defineProperty(HTMLElement.prototype, "scrollTo", {
configurable: true,
writable: true,
value: scrollTo,
});
- useEventStore.setState({
- connected: true,
- wsWarming: false,
- messages: [],
- chatThinking: false,
- thinkingSteps: [],
- thinkingStartedTs: null,
- thinkingTraces: {},
- activeThreadId: null,
- assistantName: "Jarvis",
+ window.localStorage.clear();
+ useEventStore.setState({ connected: true, wsWarming: false, assistantName: "Jarvis" });
+ useAgentChatStore.setState({
+ catalog: CATALOG,
+ connections: [
+ { jarvis: "claude-api", key_set: true, is_active_brain: true },
+ { jarvis: "openai-codex", key_set: true, is_active_brain: false },
+ ],
+ catalogError: null,
+ liveModels: {},
+ sessions: [],
+ activeSessionId: null,
+ activeSession: null,
+ timeline: EMPTY_TIMELINE,
+ draft: {
+ provider: "claude-api",
+ model: "",
+ effort: "high",
+ permissionMode: "acceptEdits",
+ buildMode: "acceptEdits",
+ cwd: "C:\\work",
+ },
+ busy: false,
+ lastError: null,
+ // The stage's mount effects fetch; keep them inert here.
+ loadCatalog: async () => {},
+ loadSessions: async () => {},
+ loadModels: async () => {},
});
});
afterEach(() => {
cleanup();
- vi.useRealTimers();
});
- it("shows the empty state with greeting and composer when there is nothing yet", () => {
+ it("shows the greeting and the composer with the four picks when there is nothing yet", () => {
render(<ChatStage />);
expect(screen.getByTestId("chat-stage").getAttribute("data-empty")).toBe("true");
- expect(screen.getByTestId("chat-composer")).toBeTruthy();
+ const composer = screen.getByTestId("agent-composer");
+ expect(within(composer).getByTestId("composer-provider").getAttribute("data-value")).toBe("claude-api");
+ expect(within(composer).getByTestId("composer-model")).toBeTruthy();
+ expect(within(composer).getByTestId("composer-effort").getAttribute("data-value")).toBe("high");
+ expect(within(composer).getByTestId("composer-permission").getAttribute("data-value")).toBe("acceptEdits");
+ // Claude Code has a plan entry, so the Build | Plan switch is drawn.
+ expect(within(composer).getByTestId("composer-plan").getAttribute("aria-checked")).toBe("false");
});
- it("renders the live turn with its steps while the assistant is thinking", () => {
- useEventStore.setState({
- messages: [msg("m1", "user", "find my invoices")],
- chatThinking: true,
- thinkingStartedTs: Date.now() - 4000,
- thinkingSteps: [
- { id: "s1", kind: "brain", labelKey: "thinking.step_brain", status: "done", startedTs: 0, durationMs: 700 },
- toolStep("s2", "gmail_search", "active"),
- ],
- });
+ it("hides the Build | Plan switch for a provider whose ladder has no plan entry", () => {
+ useAgentChatStore.setState((s) => ({ draft: { ...s.draft, provider: "openai-codex", permissionMode: "auto" } }));
render(<ChatStage />);
- const live = screen.getByTestId("chat-turn-live");
- expect(live.textContent).toContain("Jarvis");
- const steps = within(live).getByTestId("turn-steps");
- expect(steps.getAttribute("data-live")).toBe("true");
- expect(steps.getAttribute("data-open")).toBe("true");
- const rows = within(steps).getAllByTestId("turn-step");
- expect(rows).toHaveLength(2);
- expect(rows[1].textContent).toContain("Gmail · search");
- expect(within(rows[1]).getByTestId("turn-step-spinner")).toBeTruthy();
+ expect(screen.queryByTestId("composer-plan")).toBeNull();
});
- it("renders a finished trace folded above the answer, tool rows still visible", () => {
- useEventStore.setState({
- messages: [msg("m1", "user", "any github issues?"), msg("m2", "assistant", "Three open issues.")],
- thinkingTraces: {
- m2: {
- durationMs: 6_200,
- steps: [
- { id: "s1", kind: "brain", labelKey: "thinking.step_brain", status: "done", startedTs: 0, durationMs: 900 },
- toolStep("s2", "github_issues"),
- ],
- },
- },
+ it("greys out a provider that is not connected and says how to fix it", () => {
+ useAgentChatStore.setState({
+ connections: [{ jarvis: "claude-api", key_set: false, is_active_brain: true }],
});
render(<ChatStage />);
- const answer = screen.getByTestId("chat-message-assistant");
- const steps = within(answer).getByTestId("turn-steps");
- expect(steps.getAttribute("data-open")).toBe("false");
- expect(within(steps).getByTestId("turn-steps-toggle").textContent).toContain("6s");
- const rows = within(steps).getAllByTestId("turn-step");
- expect(rows).toHaveLength(1);
- expect(rows[0].textContent).toContain("GitHub · issues");
- expect(within(rows[0]).getByTestId("turn-step-brand").getAttribute("data-brand-tier")).toBe("logo");
- // The steps sit above the answer text.
- expect(answer.textContent!.indexOf("GitHub · issues")).toBeLessThan(
- answer.textContent!.indexOf("Three open issues."),
- );
+ const hint = screen.getByTestId("composer-connect-hint");
+ expect(hint.textContent).toContain("Anthropic Claude");
+ // Send stays off until the provider is usable.
+ expect((screen.getByTestId("composer-send") as HTMLButtonElement).disabled).toBe(true);
});
- it("scrolls a new user message to the top and keeps a spacer under the turn", () => {
- useEventStore.setState({
- messages: [msg("m1", "user", "hello"), msg("m2", "assistant", "hi")],
- });
+ it("renders the folded timeline: user bubble, byline with provider + model, tool row, answer", () => {
+ const timeline = reduceEvents(EMPTY_TIMELINE, [
+ ev("user_message", { text: "list the files" }),
+ ev("turn_started", { turn_id: "t1", provider: "claude-api", model: "claude-opus-5", effort: "high", runner: "claude-cli" }),
+ ev("tool_call", { turn_id: "t1", call_id: "c1", name: "Bash", input: { command: "ls" } }),
+ ev("tool_result", { turn_id: "t1", call_id: "c1", output: "a.py\nb.py", is_error: false, duration_ms: 40 }),
+ ev("assistant_text", { turn_id: "t1", message_id: "m1", text: "Two files: **a.py** and b.py." }),
+ ev("turn_finished", { turn_id: "t1", status: "done", duration_ms: 1200, usage: {} }),
+ ]);
+ useAgentChatStore.setState({ activeSessionId: "s1", timeline });
render(<ChatStage />);
- // Opening a conversation: follow the end, once.
- expect(scrollTo).toHaveBeenCalledTimes(1);
- scrollTo.mockClear();
-
- act(() => {
- useEventStore.getState().pushMessage(msg("m3", "user", "and now?"));
- useEventStore.getState().setChatThinking(true);
- });
- expect(screen.getByTestId("chat-bottom-spacer")).toBeTruthy();
- // The user message is brought to the top (one scroll, smooth or instant).
- expect(scrollTo).toHaveBeenCalledTimes(1);
- const arg = scrollTo.mock.calls[0][0] as { top: number; behavior: string };
- expect(arg.top).toBe(0); // jsdom lays everything out at 0 — the top edge
- expect(["smooth", "auto"]).toContain(arg.behavior);
- scrollTo.mockClear();
-
- // The answer landing does NOT move the page.
- act(() => {
- useEventStore.getState().finishThinking("m4");
- useEventStore.getState().pushMessage(msg("m4", "assistant", "here you go"));
- });
- expect(scrollTo).not.toHaveBeenCalled();
- expect(screen.queryByTestId("chat-turn-live")).toBeNull();
- expect(screen.getAllByTestId("chat-message-assistant")).toHaveLength(2);
+ expect(screen.getByTestId("chat-stage").getAttribute("data-empty")).toBe("false");
+ expect(screen.getByTestId("agent-message-user").textContent).toContain("list the files");
+ const turn = screen.getByTestId("agent-turn");
+ expect(turn.textContent).toContain("Anthropic Claude");
+ expect(turn.textContent).toContain("claude-opus-5");
+ const tool = within(turn).getByTestId("agent-tool");
+ expect(tool.getAttribute("data-tool")).toBe("Bash");
+ expect(tool.getAttribute("data-state")).toBe("done");
+ // The row opens to show input and output.
+ fireEvent.click(within(tool).getByRole("button"));
+ expect(tool.textContent).toContain("a.py");
+ expect(within(turn).getByTestId("agent-text").querySelector("strong")?.textContent).toBe("a.py");
+ // The person's message was pinned to the top of the scroll area.
+ expect(scrollTo).toHaveBeenCalled();
});
- it("does not render the old thinking card anymore", () => {
- useEventStore.setState({ messages: [msg("m1", "user", "x")], chatThinking: true, thinkingStartedTs: Date.now() });
+ it("shows the approval card while the runner waits and routes the click to the store", () => {
+ const decide = vi.fn(async () => {});
+ const timeline = reduceEvents(EMPTY_TIMELINE, [
+ ev("user_message", { text: "delete it" }),
+ ev("turn_started", { turn_id: "t2", provider: "openai", model: "", effort: "", runner: "api" }),
+ ev("approval_required", { turn_id: "t2", approval_id: "a1", call_id: "c2", name: "RunCommand", input: { command: "rm x" }, summary: "rm x" }),
+ ]);
+ useAgentChatStore.setState({ activeSessionId: "s2", timeline, decide });
render(<ChatStage />);
- // The composer no longer carries a status pill; the live turn does the talking.
- const composer = screen.getByTestId("chat-composer");
- expect(within(composer).queryByRole("status")).toBeNull();
- expect(screen.getByTestId("chat-turn-live")).toBeTruthy();
+ const card = screen.getByTestId("agent-approval");
+ expect(card.textContent).toContain("rm x");
+ act(() => {
+ fireEvent.click(within(card).getByTestId("approval-allow"));
+ });
+ expect(decide).toHaveBeenCalledWith("a1", "allow");
+ // The composer offers Stop while the turn runs.
+ expect(screen.getByTestId("composer-stop")).toBeTruthy();
});
});
diff --git a/jarvis/ui/web/frontend/src/components/home/ChatStage.tsx b/jarvis/ui/web/frontend/src/components/home/ChatStage.tsx
index e76d4a24e1..4fde7384c5 100644
--- a/jarvis/ui/web/frontend/src/components/home/ChatStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/ChatStage.tsx
@@ -1,39 +1,60 @@
-import { useEffect, useLayoutEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";
-import { useEventStore, type ChatMessage } from "@/store/events";
+import { useEventStore } from "@/store/events";
+import { useAgentChatStore } from "@/store/agentChat";
import { ScrollArea } from "@/components/ui/scroll-area";
-import { ChatInput } from "@/components/ChatInput";
-import { TurnSteps } from "@/components/home/TurnSteps";
+import { AgentComposer } from "@/components/agentchat/AgentComposer";
+import { AgentTimeline } from "@/components/agentchat/AgentTimeline";
import { Greeting } from "@/components/home/Greeting";
+import type { ApprovalDecision } from "@/lib/agentChatApi";
import { useT } from "@/i18n";
-import { cn } from "@/lib/utils";
/**
* The chat stage — the typed half of the front page.
*
+ * Since 2026-08-23 this is the AGENT chat (jarvis/agent_chat): a coding-agent
+ * session on whichever sub-agent — Claude Code, Codex, Antigravity, Grok
+ * Build, or an API-key provider — the composer picks, with the model, the
+ * reasoning effort and the permission mode dialled in the composer itself.
+ * The voice stage next door still talks to the voice brain; this stage does
+ * not (AP-9: nothing here touches the voice path).
+ *
* One centred column, like a document: the greeting and the composer sit
* in the middle of an empty page; once there are messages the column
- * scrolls and the composer docks to the bottom. No second pane — the
- * history moved into the sidebar (components/home/RecentChats), where it is
- * visible from every section instead of only this one.
- *
- * The composer is the one the classic view used (ChatInput): same send
- * path, same dictation, same thread routing. Only the room around it
- * changed.
+ * scrolls and the composer docks to the bottom. The history is the
+ * sidebar's (components/home/RecentChats), visible from every section.
*
* Scrolling follows the Claude app: when the person sends, their message
* is brought to the TOP of the scroll area and the answer grows below it —
* the eye stays where the new turn begins instead of chasing the bottom.
* A spacer under the last turn makes that possible even when the turn is
- * short; it shrinks as the answer fills the viewport, so a finished answer
- * never trails a screen of blank paper. Nothing jumps on assistant output.
+ * short; it shrinks as the answer fills the viewport. Nothing jumps on
+ * assistant output.
*/
export function ChatStage() {
const t = useT();
- const messages = useEventStore((s) => s.messages);
- const chatThinking = useEventStore((s) => s.chatThinking);
- const activeThreadId = useEventStore((s) => s.activeThreadId);
- const hasContent = messages.length > 0 || chatThinking;
+ const assistantName = useEventStore((s) => s.assistantName);
+ const items = useAgentChatStore((s) => s.timeline.items);
+ const activeSessionId = useAgentChatStore((s) => s.activeSessionId);
+ const catalog = useAgentChatStore((s) => s.catalog);
+ const decide = useAgentChatStore((s) => s.decide);
+ const loadCatalog = useAgentChatStore((s) => s.loadCatalog);
+ const loadSessions = useAgentChatStore((s) => s.loadSessions);
+ const hasContent = items.length > 0;
+
+ useEffect(() => {
+ if (!catalog) void loadCatalog();
+ void loadSessions();
+ }, [catalog, loadCatalog, loadSessions]);
+
+ const providerLabel = useCallback(
+ (id: string) => catalog?.providers.find((p) => p.id === id)?.label ?? id,
+ [catalog],
+ );
+ const onDecide = useCallback(
+ (approvalId: string, decision: ApprovalDecision) => void decide(approvalId, decision),
+ [decide],
+ );
const rootRef = useRef<HTMLDivElement | null>(null);
const columnRef = useRef<HTMLDivElement | null>(null);
@@ -42,8 +63,8 @@ export function ChatStage() {
// turn. Null until the person sends in this mounted column — opening an
// old conversation lands at its end like before, with no spacer.
const anchorIdRef = useRef<string | null>(null);
- const lastMessageIdRef = useRef<string | null>(null);
- const threadRef = useRef<string | null>(activeThreadId);
+ const lastItemIdRef = useRef<string | null>(null);
+ const sessionRef = useRef<string | null>(activeSessionId);
// Refs, not state, on purpose: the spacer must be sized BEFORE the scroll
// that relies on it, in the same layout pass — a state round-trip would
@@ -57,44 +78,39 @@ export function ChatStage() {
spacer.style.minHeight = "0px";
return;
}
- // Everything from the anchored message down to the spacer is the turn.
- const turnHeight =
- spacer.getBoundingClientRect().top - anchor.getBoundingClientRect().top;
+ const turnHeight = spacer.getBoundingClientRect().top - anchor.getBoundingClientRect().top;
const room = viewport.clientHeight - turnHeight - TURN_BOTTOM_PAD_PX;
spacer.style.minHeight = `${Math.max(0, Math.round(room))}px`;
};
- // React to the newest message: a user line is the start of a turn and
- // gets pinned to the top; anything else, with no turn in flight, keeps
- // the old "follow the end" behaviour (first render of a conversation).
- // Switching conversations resets the anchor: the new thread is read from
- // its end, not from wherever the previous turn left the scroll position.
+ const lastItem = items[items.length - 1];
+ const lastItemId = lastItem?.id ?? null;
+ const lastItemIsUser = lastItem?.type === "user";
+
useLayoutEffect(() => {
- if (threadRef.current !== activeThreadId) {
- threadRef.current = activeThreadId;
+ if (sessionRef.current !== activeSessionId) {
+ sessionRef.current = activeSessionId;
anchorIdRef.current = null;
- lastMessageIdRef.current = null;
+ lastItemIdRef.current = null;
}
const viewport = viewportOf(rootRef.current);
- const last = messages[messages.length - 1];
- const lastId = last?.id ?? null;
- const isNew = lastId !== lastMessageIdRef.current;
- lastMessageIdRef.current = lastId;
- if (!viewport || !last) return;
- if (isNew && last.role === "user") {
- anchorIdRef.current = last.id;
+ const isNew = lastItemId !== lastItemIdRef.current;
+ lastItemIdRef.current = lastItemId;
+ if (!viewport || !lastItemId) return;
+ if (isNew && lastItemIsUser) {
+ anchorIdRef.current = lastItemId;
applySpacer();
- scrollMessageToTop(viewport, last.id);
+ scrollMessageToTop(viewport, lastItemId);
return;
}
applySpacer();
if (isNew && anchorIdRef.current === null) scrollToEnd(viewport);
// `applySpacer` reads refs only and is recreated per render by design.
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [messages, activeThreadId, chatThinking]);
+ }, [lastItemId, lastItemIsUser, activeSessionId, items.length]);
- // The live steps grow without re-rendering this column, so the spacer
- // also follows the column's size where the platform has ResizeObserver.
+ // The live blocks grow without a new item; the spacer follows the
+ // column's size where the platform has ResizeObserver.
useEffect(() => {
const column = columnRef.current;
const viewport = viewportOf(rootRef.current);
@@ -106,12 +122,14 @@ export function ChatStage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [hasContent]);
+ const subtitle = useMemo(() => t("agent_chat.empty_subtitle"), [t]);
+
if (!hasContent) {
return (
<div className="flex min-h-0 flex-1 flex-col items-center" data-testid="chat-stage" data-empty="true">
<div className="flex w-full max-w-[760px] flex-1 flex-col justify-center gap-8 px-6 pb-20">
- <Greeting subtitle={t("home.chat_empty_title")} />
- <ChatInput />
+ <Greeting subtitle={subtitle} />
+ <AgentComposer autoFocus />
</div>
</div>
);
@@ -124,15 +142,17 @@ export function ChatStage() {
ref={columnRef}
className="relative mx-auto flex w-full max-w-[760px] flex-col gap-5 px-6 pb-6 pt-8"
>
- {messages.map((m) => (
- <MessageRow key={m.id} message={m} />
- ))}
- {chatThinking && <LiveTurn />}
+ <AgentTimeline
+ items={items}
+ assistantName={assistantName}
+ providerLabel={providerLabel}
+ onDecide={onDecide}
+ />
<div ref={spacerRef} aria-hidden data-testid="chat-bottom-spacer" className="shrink-0" />
</div>
</ScrollArea>
<div className="w-full max-w-[760px] px-6 pb-5 pt-2">
- <ChatInput />
+ <AgentComposer />
</div>
</div>
);
@@ -148,8 +168,8 @@ function viewportOf(root: HTMLElement | null): HTMLElement | null {
}
function messageElement(viewport: HTMLElement, id: string): HTMLElement | null {
- // Attribute compare instead of a selector: message ids carry characters
- // (":" , "." ) a CSS selector would need escaping for.
+ // Attribute compare instead of a selector: ids carry characters a CSS
+ // selector would need escaping for.
for (const el of Array.from(viewport.querySelectorAll<HTMLElement>("[data-message-id]"))) {
if (el.dataset.messageId === id) return el;
}
@@ -180,103 +200,3 @@ function scrollMessageToTop(viewport: HTMLElement, id: string) {
function scrollToEnd(viewport: HTMLElement) {
scrollViewport(viewport, viewport.scrollHeight);
}
-
-/** Elapsed wall-clock since `startedTs`, ticking once a second while set. */
-function useElapsedMs(startedTs: number | null): number {
- const [now, setNow] = useState(() => Date.now());
- useEffect(() => {
- if (startedTs === null) return;
- setNow(Date.now());
- const id = window.setInterval(() => setNow(Date.now()), 1000);
- return () => window.clearInterval(id);
- }, [startedTs]);
- return startedTs === null ? 0 : Math.max(0, now - startedTs);
-}
-
-/**
- * The assistant turn still in progress: byline plus the live steps. Reads
- * the store itself so the column does not re-render on every step event —
- * only this block does.
- */
-function LiveTurn() {
- const assistantName = useEventStore((s) => s.assistantName);
- const steps = useEventStore((s) => s.thinkingSteps);
- const startedTs = useEventStore((s) => s.thinkingStartedTs);
- const elapsed = useElapsedMs(startedTs);
- return (
- <div className="flex flex-col gap-1.5 px-1" data-testid="chat-turn-live">
- <Byline name={assistantName} />
- <TurnSteps steps={steps} live durationMs={elapsed} />
- </div>
- );
-}
-
-function Byline({ name }: { name: string }) {
- return (
- <div className="flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.14em] text-primary">
- <span className="h-1 w-1 rounded-full bg-primary" aria-hidden />
- {name}
- </div>
- );
-}
-
-/**
- * One message in the column. The person's lines sit right in a quiet
- * bubble; the assistant's run flush-left with a byline and, when there is
- * one, the turn's steps ("Thought for Ns" + tool calls) above the answer —
- * prose on the page, not a bubble.
- */
-function MessageRow({ message }: { message: ChatMessage }) {
- const assistantName = useEventStore((s) => s.assistantName);
- const trace = useEventStore((s) => s.thinkingTraces[message.id]);
- const isUser = message.role === "user";
-
- if (message.role === "system") {
- return (
- <div
- data-message-id={message.id}
- className="mx-auto max-w-[85%] rounded-lg border border-border bg-secondary/50 px-3 py-2 text-center text-xs italic text-muted-foreground"
- >
- {message.content}
- </div>
- );
- }
-
- if (message.role === "preamble") {
- return (
- <div
- data-message-id={message.id}
- className="flex flex-col gap-1 text-xs italic leading-relaxed text-muted-foreground"
- >
- <span className="font-mono text-[10px] not-italic uppercase tracking-[0.14em] text-muted-foreground">
- {assistantName} · pre-ack
- </span>
- <div className="whitespace-pre-wrap">{message.content}</div>
- </div>
- );
- }
-
- if (isUser) {
- return (
- <div className="flex justify-end" data-testid="chat-message-user" data-message-id={message.id}>
- <div className="max-w-[78%] rounded-2xl rounded-br-md border border-border bg-secondary px-4 py-2.5 text-[15px] leading-relaxed text-foreground">
- <div className="whitespace-pre-wrap">{message.content}</div>
- </div>
- </div>
- );
- }
-
- return (
- <div
- className="flex flex-col gap-1.5 px-1"
- data-testid="chat-message-assistant"
- data-message-id={message.id}
- >
- <Byline name={assistantName} />
- {trace && <TurnSteps steps={trace.steps} durationMs={trace.durationMs} className="mb-1" />}
- <div className={cn("whitespace-pre-wrap text-[15px] leading-relaxed text-foreground")}>
- {message.content}
- </div>
- </div>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx b/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx
index f9a1518a18..8561c15db4 100644
--- a/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx
@@ -2,6 +2,7 @@ import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { RecentChats } from "@/components/home/RecentChats";
+import { useAgentChatStore } from "@/store/agentChat";
import { useEventStore, type ConversationSummary } from "@/store/events";
import { useHomeStore } from "@/store/home";
@@ -44,6 +45,27 @@ describe("RecentChats", () => {
activeSection: "board",
});
useHomeStore.setState({ surface: "voice", transcript: [] });
+ useAgentChatStore.setState({
+ sessions: [
+ {
+ session_id: "s1",
+ title: "Agent chat",
+ provider: "claude-api",
+ model: "",
+ effort: "high",
+ cwd: "C:\work",
+ permission_mode: "acceptEdits",
+ vendor_session: null,
+ created_ms: 500,
+ updated_ms: 900,
+ message_count: 2,
+ preview: "Agent chat",
+ },
+ ],
+ activeSessionId: null,
+ loadSessions: async () => {},
+ openSession: vi.fn((id: string) => useAgentChatStore.setState({ activeSessionId: id })),
+ });
});
afterEach(() => {
cleanup();
@@ -63,11 +85,16 @@ describe("RecentChats", () => {
]);
});
- it("opens a text thread on the chat surface even from the voice stage", async () => {
+ it("opens an agent chat on the chat surface even from the voice stage", async () => {
render(<RecentChats />);
- fireEvent.click(screen.getByTitle("Typed thread"));
+ // The classic brain's text threads are no longer listed — the chat
+ // surface is the agent chat now (components/home/ChatStage).
+ expect(screen.queryByTitle("Typed thread")).toBeNull();
+ fireEvent.click(screen.getByTitle("Agent chat"));
await flush();
expect(useHomeStore.getState().surface).toBe("chat");
+ expect(useEventStore.getState().activeSection).toBe("chats");
+ expect(useAgentChatStore.getState().openSession).toHaveBeenCalledWith("s1");
expect(useHomeStore.getState().transcript).toEqual([]);
});
diff --git a/jarvis/ui/web/frontend/src/components/home/RecentChats.tsx b/jarvis/ui/web/frontend/src/components/home/RecentChats.tsx
index 0abdebff08..819be8fa96 100644
--- a/jarvis/ui/web/frontend/src/components/home/RecentChats.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/RecentChats.tsx
@@ -1,54 +1,90 @@
-import { useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { MessageSquare, Mic, Trash2 } from "lucide-react";
import { useConversations } from "@/hooks/useConversations";
import { useEventStore, type ConversationSummary } from "@/store/events";
+import { useAgentChatStore } from "@/store/agentChat";
import { useHomeStore } from "@/store/home";
import { useT } from "@/i18n";
import { transcriptFromMessages } from "@/lib/homeTranscript";
import { cn } from "@/lib/utils";
import { SidebarGroup } from "@/components/home/SidebarGroup";
+import { CONVERSATIONS_REFRESH_MS } from "@/hooks/useConversations";
export const RECENT_CHATS_FOLDED = 3;
export const RECENT_CHATS_UNFOLDED = 15;
/**
- * The last conversations — text threads and voice sessions in one list —
- * from the sidebar. This block is the one long-lived poller of the history
- * (`useConversations({ poll: true })`); the chat stage reads the same store.
+ * The last conversations — agent chats and voice sessions in one list —
+ * from the sidebar. This block is the one long-lived poller of both
+ * histories (`useConversations({ poll: true })` for the voice sessions,
+ * the agent-chat store's session list for the typed ones).
*
- * Opening a row resumes it — the backend seeds the shared brain, so the next
- * turn continues it whether typed or spoken — and lands on the surface that
- * fits (maintainer, 2026-08-23): a VOICE session opened while the voice
- * stage is up stays there, its words loaded into the transcript lane, so
- * you just keep talking. Everything else (a text thread, or any row opened
- * from the chat surface) goes to the chat surface, where a thread is read
- * and continued by typing. Reading the surface at click time, not via a
+ * Opening a row resumes it and lands on the surface that fits (maintainer,
+ * 2026-08-23): a VOICE session opened while the voice stage is up stays
+ * there, its words loaded into the transcript lane, so you just keep
+ * talking. An agent chat goes to the chat surface, where the session is
+ * read and continued by typing — on the provider and model it was using,
+ * which the composer shows. Reading the surface at click time, not via a
* subscription, keeps the list from re-rendering on every switch.
+ *
+ * The classic brain's text threads are no longer listed: since the chat
+ * surface became the agent chat there is nowhere to open them; the data
+ * stays on disk.
*/
export function RecentChats() {
const t = useT();
- const { conversations, activeThreadId, openConversation, removeConversation } =
- useConversations({ poll: true });
+ const { conversations, openConversation } = useConversations({ poll: true });
+ const sessions = useAgentChatStore((s) => s.sessions);
+ const activeSessionId = useAgentChatStore((s) => s.activeSessionId);
+ const loadSessions = useAgentChatStore((s) => s.loadSessions);
+ const openSession = useAgentChatStore((s) => s.openSession);
+ const removeSession = useAgentChatStore((s) => s.removeSession);
const [open, setOpen] = useState(false);
const setActive = useEventStore((s) => s.setActiveSection);
+ const activeVoiceId = useEventStore((s) => (s.activeKind === "voice" ? s.activeThreadId : null));
const setSurface = useHomeStore((s) => s.setSurface);
const seedTranscript = useHomeStore((s) => s.seedTranscript);
- const openRow = (c: ConversationSummary) => {
- const stayOnVoice = c.kind === "voice" && useHomeStore.getState().surface === "voice";
- const opened = openConversation(c.kind, c.id);
- if (stayOnVoice) {
- void opened.then((messages) => seedTranscript(transcriptFromMessages(messages)));
+ useEffect(() => {
+ void loadSessions();
+ const id = window.setInterval(() => void loadSessions(), CONVERSATIONS_REFRESH_MS);
+ return () => window.clearInterval(id);
+ }, [loadSessions]);
+
+ const rows = useMemo<RecentRow[]>(() => {
+ const voice: RecentRow[] = conversations
+ .filter((c) => c.kind === "voice")
+ .map((c) => ({ kind: "voice", id: c.id, title: c.title || c.preview, updatedMs: c.updated_ms, raw: c }));
+ const agent: RecentRow[] = sessions.map((s) => ({
+ kind: "agent",
+ id: s.session_id,
+ title: s.title || s.preview,
+ updatedMs: s.updated_ms,
+ raw: null,
+ }));
+ return [...voice, ...agent].sort((a, b) => b.updatedMs - a.updatedMs);
+ }, [conversations, sessions]);
+
+ const openRow = (row: RecentRow) => {
+ if (row.kind === "voice" && row.raw) {
+ const stayOnVoice = useHomeStore.getState().surface === "voice";
+ const opened = openConversation("voice", row.id);
+ if (stayOnVoice) {
+ void opened.then((messages) => seedTranscript(transcriptFromMessages(messages)));
+ } else {
+ void opened;
+ setSurface("chat");
+ }
} else {
- void opened;
+ openSession(row.id);
setSurface("chat");
}
setActive("chats");
};
- const shown = conversations.slice(0, open ? RECENT_CHATS_UNFOLDED : RECENT_CHATS_FOLDED);
- const canExpand = conversations.length > RECENT_CHATS_FOLDED;
+ const shown = rows.slice(0, open ? RECENT_CHATS_UNFOLDED : RECENT_CHATS_FOLDED);
+ const canExpand = rows.length > RECENT_CHATS_FOLDED;
return (
<SidebarGroup
@@ -68,13 +104,13 @@ export function RecentChats() {
<p className="px-2 py-1 text-[11px] text-muted-foreground/70">{t("sidebar.no_chats")}</p>
) : (
<ul className="space-y-px">
- {shown.map((c) => (
+ {shown.map((row) => (
<ChatRow
- key={`${c.kind}-${c.id}`}
- conversation={c}
- active={c.id === activeThreadId}
- onOpen={() => openRow(c)}
- onDelete={() => void removeConversation(c.id)}
+ key={`${row.kind}-${row.id}`}
+ row={row}
+ active={row.kind === "agent" ? row.id === activeSessionId : row.id === activeVoiceId}
+ onOpen={() => openRow(row)}
+ onDelete={row.kind === "agent" ? () => void removeSession(row.id) : undefined}
/>
))}
</ul>
@@ -83,21 +119,29 @@ export function RecentChats() {
);
}
+interface RecentRow {
+ kind: "voice" | "agent";
+ id: string;
+ title: string;
+ updatedMs: number;
+ raw: ConversationSummary | null;
+}
+
function ChatRow({
- conversation,
+ row,
active,
onOpen,
onDelete,
}: {
- conversation: ConversationSummary;
+ row: RecentRow;
active: boolean;
onOpen: () => void;
- onDelete: () => void;
+ onDelete?: () => void;
}) {
const t = useT();
- const isVoice = conversation.kind === "voice";
+ const isVoice = row.kind === "voice";
const Icon = isVoice ? Mic : MessageSquare;
- const title = conversation.title || conversation.preview || t("chats_view.new_chat");
+ const title = row.title || t("chats_view.new_chat");
return (
<li className="group relative">
<button
@@ -105,6 +149,7 @@ function ChatRow({
onClick={onOpen}
title={title}
data-testid="recent-chat-row"
+ data-kind={row.kind}
className={cn(
"flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors",
"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
@@ -117,10 +162,10 @@ function ChatRow({
/>
<span className="min-w-0 flex-1 truncate text-xs text-foreground">{title}</span>
<span className="shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground">
- {formatWhen(conversation.updated_ms)}
+ {formatWhen(row.updatedMs)}
</span>
</button>
- {!isVoice && (
+ {onDelete && (
<button
type="button"
onClick={(e) => {
diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
index 0d290a19a0..9cf62a0555 100644
--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx
@@ -26,6 +26,7 @@ import { SurfaceSwitch } from "@/components/home/SurfaceSwitch";
import { RecentChats } from "@/components/home/RecentChats";
import { useConversations } from "@/hooks/useConversations";
import { useHomeStore } from "@/store/home";
+import { useAgentChatStore } from "@/store/agentChat";
import { PRODUCT_NAME } from "@/lib/branding";
import { useAppInstance } from "@/hooks/useAppInstance";
@@ -114,14 +115,18 @@ export function Sidebar({
const appInstance = useAppInstance();
const devTag = appInstance?.isDev ? appInstance.name.toUpperCase() : null;
// "+ New chat" lands on the chat surface of the front page with an empty
- // thread — the sidebar owns the history now, so it owns this too.
+ // agent chat — the sidebar owns the history now, so it owns this too. The
+ // voice thread is cleared as well so a reopened voice session does not
+ // linger behind the fresh page.
const { newChat } = useConversations();
+ const newAgentChat = useAgentChatStore((s) => s.newChat);
const setSurface = useHomeStore((s) => s.setSurface);
// The front page's nav row names the face the switch picked (Voice / Chat),
// see `presentNavItem`.
const surface = useHomeStore((s) => s.surface);
const startNewChat = () => {
newChat();
+ newAgentChat();
setSurface("chat");
setActive("chats");
};
diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderLogo.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderLogo.tsx
index 9cf7fa1603..30853cc759 100644
--- a/jarvis/ui/web/frontend/src/components/providers/ProviderLogo.tsx
+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderLogo.tsx
@@ -94,17 +94,27 @@ export function ProviderLogo({
providerId,
label,
className,
+ size = "md",
}: {
providerId: string;
/** The card's display name — its initial is the monogram fallback. */
label: string;
className?: string;
+ /**
+ * `md` is the provider-row tile; `sm` is the same mark drawn inline — no
+ * tile, no border — for a menu row or a composer pill where the mark is a
+ * hint beside a word rather than the subject of a card.
+ */
+ size?: "md" | "sm";
}) {
const family = providerFamily(providerId);
const entry = family ? PROVIDER_FAMILY_LOGOS[family] : undefined;
const url = entry ? assetUrl(entry.file) : undefined;
const local = localGlyph(providerId);
const monogram = label.trim().slice(0, 1).toUpperCase() || "?";
+ const small = size === "sm";
+ const markClass = small ? "h-3.5 w-3.5" : "h-5 w-5";
+ const glyphClass = small ? "h-3.5 w-3.5" : "h-4 w-4";
return (
<span
@@ -114,13 +124,15 @@ export function ProviderLogo({
className={cn(
// One neutral tile for every mark, so a row of providers reads as one
// list rather than a row of differently shaped app icons.
- "inline-flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-surface border border-border/80 bg-background/70",
+ small
+ ? "inline-flex h-4 w-4 shrink-0 items-center justify-center overflow-hidden rounded-sm"
+ : "inline-flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-surface border border-border/80 bg-background/70",
className,
)}
>
{url && entry?.render === "mono" ? (
<span
- className="block h-5 w-5 bg-foreground"
+ className={cn("block bg-foreground", markClass)}
style={{
WebkitMaskImage: `url("${url}")`,
maskImage: `url("${url}")`,
@@ -136,13 +148,13 @@ export function ProviderLogo({
// A lockup with its own ground fills the tile; its corners are ours.
<img src={url} alt="" className="block h-full w-full object-cover" />
) : url ? (
- <img src={url} alt="" className="block h-5 w-5 object-contain" />
+ <img src={url} alt="" className={cn("block object-contain", markClass)} />
) : local === "server" ? (
- <Server className="h-4 w-4 text-muted-foreground" />
+ <Server className={cn("text-muted-foreground", glyphClass)} />
) : local === "device" ? (
- <HardDrive className="h-4 w-4 text-muted-foreground" />
+ <HardDrive className={cn("text-muted-foreground", glyphClass)} />
) : (
- <span className="font-display text-xs font-semibold text-muted-foreground">
+ <span className={cn("font-display font-semibold text-muted-foreground", small ? "text-[10px]" : "text-xs")}>
{monogram}
</span>
)}
diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
new file mode 100644
index 0000000000..2b7c1cd676
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
@@ -0,0 +1,270 @@
+// Thin client for the agent-chat REST + WebSocket API
+// (jarvis/ui/web/agent_chat_routes.py). Shapes mirror jarvis/agent_chat/*
+// one-to-one; nothing here decides behaviour.
+
+export interface CuratedModel {
+ id: string;
+ label: string;
+ /**
+ * The effort levels this model takes when narrower than the provider's
+ * ladder (agy's Pro: low/high; its Claude models: none). Absent = the
+ * provider ladder applies; [] = no effort pick for this model.
+ */
+ efforts?: string[];
+ /** A short note for the picker's hint ("retires 2026-08-31"). */
+ note?: string;
+}
+
+export interface PermissionModeOption {
+ id: string;
+ label: string;
+ description: string;
+}
+
+export interface AgentChatProvider {
+ id: string;
+ label: string;
+ /** Brand family for ProviderLogo. */
+ family: string;
+ /** "api" | "claude-cli" | "codex-cli" | "agy-cli" | "grok-cli" — resolved for this machine. */
+ runner: string;
+ models_source: "live" | "curated";
+ curated_models: CuratedModel[];
+ /** "" = the runner's own default. */
+ default_model: string;
+ keyless: boolean;
+ native_resume: boolean;
+ /** Ascending ladder; "" means "provider default". */
+ effort_levels: string[];
+ default_effort: string;
+ /** The ladder this provider's runner offers; a "plan" entry powers the Build | Plan switch. */
+ permission_modes: PermissionModeOption[];
+ default_permission_mode: string;
+ /** null for the API runner; else whether the vendor binary is on PATH. */
+ cli_installed: boolean | null;
+}
+
+export interface AgentChatCatalog {
+ providers: AgentChatProvider[];
+ default_cwd: string;
+ shell: string;
+}
+
+export interface AgentChatSession {
+ session_id: string;
+ title: string;
+ provider: string;
+ model: string;
+ effort: string;
+ cwd: string;
+ permission_mode: string;
+ vendor_session: string | null;
+ created_ms: number;
+ updated_ms: number;
+ message_count: number;
+ preview: string;
+ running?: boolean;
+ pending_approvals?: string[];
+}
+
+export interface AgentChatEvent {
+ seq: number;
+ ts_ms: number;
+ kind: string;
+ payload: Record<string, unknown>;
+}
+
+/** One row of `GET /api/jarvis-agent/status` — the Agents tab's truth about credentials. */
+export interface AgentConnectionRow {
+ jarvis: string;
+ label?: string;
+ key_set: boolean;
+ api_key_set?: boolean;
+ oauth_connected?: boolean;
+ is_active_brain: boolean;
+ keyless?: boolean;
+}
+
+export class AgentChatApiError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ ) {
+ super(message);
+ this.name = "AgentChatApiError";
+ }
+}
+
+async function json<T>(res: Response, what: string): Promise<T> {
+ if (!res.ok) {
+ let detail = what;
+ try {
+ const body = (await res.json()) as { detail?: unknown };
+ if (typeof body.detail === "string") detail = body.detail;
+ } catch {
+ /* no JSON body — keep the generic label */
+ }
+ throw new AgentChatApiError(detail, res.status);
+ }
+ return (await res.json()) as T;
+}
+
+export async function fetchAgentChatCatalog(): Promise<AgentChatCatalog> {
+ return json(await fetch("/api/agent-chat/catalog"), "catalog-failed");
+}
+
+export async function fetchAgentConnections(): Promise<AgentConnectionRow[]> {
+ const data = await json<{ mapping?: AgentConnectionRow[] }>(
+ await fetch("/api/jarvis-agent/status"),
+ "status-failed",
+ );
+ return Array.isArray(data.mapping) ? data.mapping : [];
+}
+
+export interface LiveModel {
+ id: string;
+ label?: string;
+ name?: string;
+}
+
+/** The provider's live model list (brain catalog route); [] when the route has none. */
+export async function fetchProviderModels(providerId: string): Promise<LiveModel[]> {
+ const res = await fetch(`/api/providers/${encodeURIComponent(providerId)}/models`);
+ if (!res.ok) return [];
+ const data = (await res.json()) as { models?: unknown } | unknown[];
+ const raw = Array.isArray(data) ? data : Array.isArray(data.models) ? data.models : [];
+ return raw
+ .map((m) => {
+ if (typeof m === "string") return { id: m };
+ if (m && typeof m === "object" && typeof (m as LiveModel).id === "string") {
+ return m as LiveModel;
+ }
+ return null;
+ })
+ .filter((m): m is LiveModel => m !== null);
+}
+
+export async function fetchAgentChatSessions(limit = 200): Promise<AgentChatSession[]> {
+ const data = await json<{ sessions: AgentChatSession[] }>(
+ await fetch(`/api/agent-chat/sessions?limit=${limit}`),
+ "sessions-failed",
+ );
+ return data.sessions;
+}
+
+export interface CreateSessionInput {
+ provider: string;
+ model?: string;
+ effort?: string | null;
+ cwd?: string | null;
+ permission_mode?: string;
+ title?: string;
+}
+
+export async function createAgentChatSession(input: CreateSessionInput): Promise<AgentChatSession> {
+ return json(
+ await fetch("/api/agent-chat/sessions", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(input),
+ }),
+ "create-failed",
+ );
+}
+
+export type PatchSessionInput = Partial<
+ Pick<AgentChatSession, "title" | "provider" | "model" | "effort" | "cwd" | "permission_mode">
+>;
+
+export async function patchAgentChatSession(
+ sessionId: string,
+ input: PatchSessionInput,
+): Promise<AgentChatSession> {
+ return json(
+ await fetch(`/api/agent-chat/sessions/${encodeURIComponent(sessionId)}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(input),
+ }),
+ "patch-failed",
+ );
+}
+
+export async function deleteAgentChatSession(sessionId: string): Promise<void> {
+ await json(
+ await fetch(`/api/agent-chat/sessions/${encodeURIComponent(sessionId)}`, {
+ method: "DELETE",
+ }),
+ "delete-failed",
+ );
+}
+
+export async function fetchAgentChatSession(
+ sessionId: string,
+): Promise<{ session: AgentChatSession; events: AgentChatEvent[] }> {
+ return json(
+ await fetch(`/api/agent-chat/sessions/${encodeURIComponent(sessionId)}`),
+ "session-failed",
+ );
+}
+
+export async function sendAgentChatMessage(
+ sessionId: string,
+ text: string,
+): Promise<{ turn_id: string }> {
+ return json(
+ await fetch(`/api/agent-chat/sessions/${encodeURIComponent(sessionId)}/messages`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ text }),
+ }),
+ "send-failed",
+ );
+}
+
+export async function cancelAgentChatTurn(sessionId: string): Promise<void> {
+ await json(
+ await fetch(`/api/agent-chat/sessions/${encodeURIComponent(sessionId)}/cancel`, {
+ method: "POST",
+ }),
+ "cancel-failed",
+ );
+}
+
+export type ApprovalDecision = "allow" | "allow_always" | "deny";
+
+export async function resolveAgentChatApproval(
+ sessionId: string,
+ approvalId: string,
+ decision: ApprovalDecision,
+): Promise<void> {
+ await json(
+ await fetch(
+ `/api/agent-chat/sessions/${encodeURIComponent(sessionId)}/approvals/${encodeURIComponent(approvalId)}`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ decision }),
+ },
+ ),
+ "approval-failed",
+ );
+}
+
+export async function pickAgentChatFolder(start?: string): Promise<string | null> {
+ const data = await json<{ path: string | null; cancelled: boolean }>(
+ await fetch("/api/agent-chat/pick-folder", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ start: start ?? null }),
+ }),
+ "pick-folder-failed",
+ );
+ return data.cancelled ? null : data.path;
+}
+
+export function agentChatSocketUrl(sessionId: string, afterSeq = 0): string {
+ const proto = window.location.protocol === "https:" ? "wss" : "ws";
+ const after = afterSeq > 0 ? `?after=${afterSeq}` : "";
+ return `${proto}://${window.location.host}/api/agent-chat/sessions/${encodeURIComponent(sessionId)}/ws${after}`;
+}
diff --git a/jarvis/ui/web/frontend/src/store/agentChat.ts b/jarvis/ui/web/frontend/src/store/agentChat.ts
new file mode 100644
index 0000000000..811e95afe7
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/store/agentChat.ts
@@ -0,0 +1,489 @@
+import { create } from "zustand";
+
+import {
+ agentChatSocketUrl,
+ cancelAgentChatTurn,
+ createAgentChatSession,
+ deleteAgentChatSession,
+ fetchAgentChatCatalog,
+ fetchAgentChatSessions,
+ fetchAgentConnections,
+ fetchProviderModels,
+ patchAgentChatSession,
+ resolveAgentChatApproval,
+ sendAgentChatMessage,
+ type AgentChatCatalog,
+ type AgentChatEvent,
+ type AgentChatProvider,
+ type AgentChatSession,
+ type AgentConnectionRow,
+ type ApprovalDecision,
+ type CuratedModel,
+ type PatchSessionInput,
+} from "@/lib/agentChatApi";
+import { EMPTY_TIMELINE, reduceEvent, reduceEvents, type Timeline } from "@/components/agentchat/reduce";
+
+/**
+ * The agent chat's own store — the typed half of the front page.
+ *
+ * One active session at a time: its timeline is fed by one WebSocket
+ * (snapshot, then live events, reconnect from the last seq). The composer's
+ * choice of provider / model / effort / permission mode lives here as the
+ * DRAFT: for a fresh chat it is what the next session is created with; with
+ * a session open, changing a pick patches that session on the backend and
+ * the same draft mirrors it. The draft survives a reload (localStorage) so
+ * the composer opens on what you used last, like the Claude app does.
+ *
+ * The provider list is the backend catalog (`/api/agent-chat/catalog`)
+ * joined with the Agents tab's credential truth (`/api/jarvis-agent/status`):
+ * a provider is offered when it is connected — a key saved, a subscription
+ * logged in, or a local server — and shown greyed out with a "connect" hint
+ * otherwise. The one marked active on the Agents tab is the draft's default.
+ */
+
+const DRAFT_KEY = "jarvis.agentChat.draft.v1";
+const RECONNECT_MS = 1500;
+
+export interface ComposerDraft {
+ provider: string;
+ model: string;
+ effort: string;
+ permissionMode: string;
+ /** The permission mode to go back to when Plan is switched off. */
+ buildMode: string;
+ cwd: string;
+}
+
+export interface ProviderOption extends AgentChatProvider {
+ /** Usable right now: credential present (or keyless) and, for a CLI, installed. */
+ connected: boolean;
+ /** The sub-agent marked active on the Agents tab. */
+ active: boolean;
+}
+
+interface AgentChatStore {
+ catalog: AgentChatCatalog | null;
+ connections: AgentConnectionRow[];
+ catalogError: string | null;
+ /** Live model lists per provider id (the API-backed rows). */
+ liveModels: Record<string, CuratedModel[]>;
+ sessions: AgentChatSession[];
+ activeSessionId: string | null;
+ activeSession: AgentChatSession | null;
+ timeline: Timeline;
+ socketState: "idle" | "connecting" | "open" | "closed";
+ draft: ComposerDraft;
+ busy: boolean;
+ lastError: string | null;
+
+ loadCatalog: () => Promise<void>;
+ loadSessions: () => Promise<void>;
+ loadModels: (providerId: string) => Promise<void>;
+ providerOptions: () => ProviderOption[];
+ providerById: (id: string) => ProviderOption | null;
+ setDraft: (patch: Partial<ComposerDraft>) => Promise<void>;
+ setPlan: (on: boolean) => Promise<void>;
+ newChat: () => void;
+ openSession: (sessionId: string) => void;
+ removeSession: (sessionId: string) => Promise<void>;
+ send: (text: string) => Promise<void>;
+ cancel: () => Promise<void>;
+ decide: (approvalId: string, decision: ApprovalDecision) => Promise<void>;
+ /** Tests and the socket: fold one event into the active timeline. */
+ ingest: (event: AgentChatEvent) => void;
+ disconnect: () => void;
+}
+
+function readDraft(): ComposerDraft {
+ const empty: ComposerDraft = {
+ provider: "",
+ model: "",
+ effort: "",
+ permissionMode: "",
+ buildMode: "",
+ cwd: "",
+ };
+ try {
+ const raw = window.localStorage.getItem(DRAFT_KEY);
+ if (!raw) return empty;
+ const parsed = JSON.parse(raw) as Partial<ComposerDraft>;
+ return { ...empty, ...parsed };
+ } catch {
+ return empty;
+ }
+}
+
+function writeDraft(draft: ComposerDraft): void {
+ try {
+ window.localStorage.setItem(DRAFT_KEY, JSON.stringify(draft));
+ } catch {
+ /* storage blocked — the draft just does not survive a reload */
+ }
+}
+
+function errorText(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
+
+/** Which `/api/jarvis-agent/status` row speaks for a catalog provider. */
+function connectionFor(
+ provider: AgentChatProvider,
+ rows: AgentConnectionRow[],
+): AgentConnectionRow | undefined {
+ return rows.find((r) => r.jarvis === provider.id);
+}
+
+/** A session patch the composer's draft must mirror. */
+function draftFromSession(session: AgentChatSession, prev: ComposerDraft): ComposerDraft {
+ const plan = session.permission_mode === "plan";
+ return {
+ provider: session.provider,
+ model: session.model,
+ effort: session.effort,
+ permissionMode: session.permission_mode,
+ buildMode: plan ? prev.buildMode || prev.permissionMode : session.permission_mode,
+ cwd: session.cwd,
+ };
+}
+
+let socket: WebSocket | null = null;
+let socketSession: string | null = null;
+let reconnectTimer: number | null = null;
+
+function closeSocket(): void {
+ if (reconnectTimer !== null) {
+ window.clearTimeout(reconnectTimer);
+ reconnectTimer = null;
+ }
+ const s = socket;
+ socket = null;
+ socketSession = null;
+ if (s) {
+ s.onclose = null;
+ s.onmessage = null;
+ s.onerror = null;
+ s.onopen = null;
+ try {
+ s.close();
+ } catch {
+ /* already closed */
+ }
+ }
+}
+
+export const useAgentChatStore = create<AgentChatStore>((set, get) => {
+ function connect(sessionId: string, afterSeq: number): void {
+ if (typeof WebSocket === "undefined") return;
+ closeSocket();
+ socketSession = sessionId;
+ set({ socketState: "connecting" });
+ const ws = new WebSocket(agentChatSocketUrl(sessionId, afterSeq));
+ socket = ws;
+ ws.onopen = () => {
+ if (socket === ws) set({ socketState: "open" });
+ };
+ ws.onmessage = (msg) => {
+ if (socket !== ws) return;
+ let frame: { type?: string; session?: AgentChatSession; events?: AgentChatEvent[]; event?: AgentChatEvent };
+ try {
+ frame = JSON.parse(String(msg.data));
+ } catch {
+ return;
+ }
+ if (frame.type === "snapshot" && frame.session) {
+ const prev = get();
+ // A snapshot after a reconnect only carries events past `after`;
+ // fold them onto what is already there, else start fresh.
+ const base = afterSeq > 0 && prev.activeSessionId === sessionId ? prev.timeline : EMPTY_TIMELINE;
+ const tl = reduceEvents(base, frame.events ?? []);
+ set({
+ activeSession: frame.session,
+ timeline: { ...tl, sessionPatch: null },
+ draft: draftFromSession(frame.session, prev.draft),
+ });
+ writeDraft(get().draft);
+ return;
+ }
+ if (frame.type === "event" && frame.event) get().ingest(frame.event);
+ };
+ ws.onclose = () => {
+ if (socket !== ws) return;
+ socket = null;
+ set({ socketState: "closed" });
+ // Reconnect while this session is still the open one; the backend
+ // replays what was missed from the last seq.
+ reconnectTimer = window.setTimeout(() => {
+ reconnectTimer = null;
+ const st = get();
+ if (st.activeSessionId === sessionId && socketSession === sessionId) {
+ connect(sessionId, st.timeline.lastSeq);
+ }
+ }, RECONNECT_MS);
+ };
+ ws.onerror = () => {
+ /* onclose follows and schedules the reconnect */
+ };
+ }
+
+ return {
+ catalog: null,
+ connections: [],
+ catalogError: null,
+ liveModels: {},
+ sessions: [],
+ activeSessionId: null,
+ activeSession: null,
+ timeline: EMPTY_TIMELINE,
+ socketState: "idle",
+ draft: readDraft(),
+ busy: false,
+ lastError: null,
+
+ loadCatalog: async () => {
+ try {
+ const [catalog, connections] = await Promise.all([
+ fetchAgentChatCatalog(),
+ fetchAgentConnections().catch(() => [] as AgentConnectionRow[]),
+ ]);
+ set({ catalog, connections, catalogError: null });
+ // Settle the draft: an empty or unknown provider becomes the active
+ // sub-agent (else the first connected one); blank picks take the
+ // provider's defaults.
+ const st = get();
+ const options = st.providerOptions();
+ let draft = st.draft;
+ const known = options.find((o) => o.id === draft.provider);
+ if (!known) {
+ const pick = options.find((o) => o.active && o.connected) ?? options.find((o) => o.connected) ?? options[0];
+ if (pick) {
+ draft = {
+ provider: pick.id,
+ model: pick.default_model,
+ effort: pick.default_effort,
+ permissionMode: pick.default_permission_mode,
+ buildMode: pick.default_permission_mode,
+ cwd: draft.cwd || catalog.default_cwd,
+ };
+ }
+ } else {
+ draft = {
+ ...draft,
+ effort: draft.effort || known.default_effort,
+ permissionMode: draft.permissionMode || known.default_permission_mode,
+ buildMode: draft.buildMode || known.default_permission_mode,
+ cwd: draft.cwd || catalog.default_cwd,
+ };
+ }
+ if (draft !== st.draft) {
+ set({ draft });
+ writeDraft(draft);
+ }
+ if (draft.provider) void get().loadModels(draft.provider);
+ } catch (err) {
+ set({ catalogError: errorText(err) });
+ }
+ },
+
+ loadSessions: async () => {
+ try {
+ const sessions = await fetchAgentChatSessions();
+ set({ sessions });
+ } catch {
+ /* offline / headless — keep the list as-is */
+ }
+ },
+
+ loadModels: async (providerId) => {
+ const provider = get().catalog?.providers.find((p) => p.id === providerId);
+ if (!provider || provider.models_source !== "live") return;
+ if (get().liveModels[providerId]) return;
+ try {
+ const models = await fetchProviderModels(providerId);
+ const rows: CuratedModel[] = models.map((m) => ({ id: m.id, label: m.label ?? m.name ?? m.id }));
+ set((s) => ({ liveModels: { ...s.liveModels, [providerId]: rows } }));
+ } catch {
+ /* the curated list stays */
+ }
+ },
+
+ providerOptions: () => {
+ const { catalog, connections } = get();
+ if (!catalog) return [];
+ return catalog.providers.map((p) => {
+ const row = connectionFor(p, connections);
+ const credentialed = p.keyless || Boolean(row?.key_set);
+ const installed = p.cli_installed === null ? true : p.cli_installed;
+ return {
+ ...p,
+ connected: credentialed && installed,
+ active: Boolean(row?.is_active_brain),
+ };
+ });
+ },
+
+ providerById: (id) => get().providerOptions().find((p) => p.id === id) ?? null,
+
+ setDraft: async (patch) => {
+ const st = get();
+ let draft: ComposerDraft = { ...st.draft, ...patch };
+ // A provider change re-seats model / effort / permission on the new
+ // provider's defaults unless the caller set them explicitly.
+ if (patch.provider && patch.provider !== st.draft.provider) {
+ const p = st.providerById(patch.provider);
+ if (p) {
+ draft = {
+ ...draft,
+ model: patch.model ?? p.default_model,
+ effort: patch.effort ?? p.default_effort,
+ permissionMode: patch.permissionMode ?? p.default_permission_mode,
+ buildMode: patch.permissionMode ?? p.default_permission_mode,
+ };
+ }
+ void get().loadModels(patch.provider);
+ } else if (patch.permissionMode && patch.permissionMode !== "plan") {
+ draft = { ...draft, buildMode: patch.permissionMode };
+ }
+ set({ draft });
+ writeDraft(draft);
+ // With a session open, the pick applies to it right away.
+ const sid = st.activeSessionId;
+ if (sid) {
+ const body: PatchSessionInput = {};
+ if (patch.provider !== undefined) body.provider = draft.provider;
+ if (patch.provider !== undefined || patch.model !== undefined) body.model = draft.model;
+ if (patch.provider !== undefined || patch.effort !== undefined) body.effort = draft.effort;
+ if (patch.provider !== undefined || patch.permissionMode !== undefined) {
+ body.permission_mode = draft.permissionMode;
+ }
+ if (patch.cwd !== undefined) body.cwd = draft.cwd;
+ try {
+ const session = await patchAgentChatSession(sid, body);
+ set((s) => ({
+ activeSession: s.activeSessionId === sid ? session : s.activeSession,
+ sessions: s.sessions.map((x) => (x.session_id === sid ? { ...x, ...session } : x)),
+ }));
+ } catch (err) {
+ set({ lastError: errorText(err) });
+ }
+ }
+ },
+
+ setPlan: async (on) => {
+ const st = get();
+ if (on) {
+ await st.setDraft({ permissionMode: "plan" });
+ } else {
+ const p = st.providerById(st.draft.provider);
+ const back = st.draft.buildMode && st.draft.buildMode !== "plan" ? st.draft.buildMode : p?.default_permission_mode ?? "";
+ await st.setDraft({ permissionMode: back });
+ }
+ },
+
+ newChat: () => {
+ closeSocket();
+ set({
+ activeSessionId: null,
+ activeSession: null,
+ timeline: EMPTY_TIMELINE,
+ socketState: "idle",
+ lastError: null,
+ });
+ },
+
+ openSession: (sessionId) => {
+ if (get().activeSessionId === sessionId && socket) return;
+ set({
+ activeSessionId: sessionId,
+ activeSession: get().sessions.find((s) => s.session_id === sessionId) ?? null,
+ timeline: EMPTY_TIMELINE,
+ lastError: null,
+ });
+ connect(sessionId, 0);
+ },
+
+ removeSession: async (sessionId) => {
+ try {
+ await deleteAgentChatSession(sessionId);
+ } catch (err) {
+ set({ lastError: errorText(err) });
+ }
+ if (get().activeSessionId === sessionId) get().newChat();
+ set((s) => ({ sessions: s.sessions.filter((x) => x.session_id !== sessionId) }));
+ void get().loadSessions();
+ },
+
+ send: async (text) => {
+ const content = text.trim();
+ if (!content) return;
+ const st = get();
+ set({ busy: true, lastError: null });
+ try {
+ let sid = st.activeSessionId;
+ if (!sid) {
+ const d = st.draft;
+ const session = await createAgentChatSession({
+ provider: d.provider,
+ model: d.model,
+ effort: d.effort,
+ cwd: d.cwd || null,
+ permission_mode: d.permissionMode,
+ });
+ sid = session.session_id;
+ set({
+ activeSessionId: sid,
+ activeSession: session,
+ timeline: EMPTY_TIMELINE,
+ sessions: [session, ...get().sessions],
+ });
+ connect(sid, 0);
+ }
+ await sendAgentChatMessage(sid, content);
+ void get().loadSessions();
+ } catch (err) {
+ set({ lastError: errorText(err) });
+ } finally {
+ set({ busy: false });
+ }
+ },
+
+ cancel: async () => {
+ const sid = get().activeSessionId;
+ if (!sid) return;
+ try {
+ await cancelAgentChatTurn(sid);
+ } catch (err) {
+ set({ lastError: errorText(err) });
+ }
+ },
+
+ decide: async (approvalId, decision) => {
+ const sid = get().activeSessionId;
+ if (!sid) return;
+ try {
+ await resolveAgentChatApproval(sid, approvalId, decision);
+ } catch (err) {
+ set({ lastError: errorText(err) });
+ }
+ },
+
+ ingest: (event) => {
+ const st = get();
+ const tl = reduceEvent(st.timeline, event);
+ if (tl === st.timeline) return;
+ const patch: Partial<AgentChatStore> = { timeline: tl };
+ if (tl.sessionPatch && st.activeSession) {
+ const session = { ...st.activeSession, ...tl.sessionPatch } as AgentChatSession;
+ patch.activeSession = session;
+ patch.draft = draftFromSession(session, st.draft);
+ writeDraft(patch.draft);
+ }
+ set(patch);
+ if (event.kind === "turn_finished" || event.kind === "user_message") void st.loadSessions();
+ },
+
+ disconnect: () => {
+ closeSocket();
+ set({ socketState: "idle" });
+ },
+ };
+});
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 62772ba9a7..2514606dbb 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -330,6 +330,7 @@ class WebServer:
from jarvis.runs.runs_ws import router as runs_ws_router
from .agent_accounts_routes import router as agent_accounts_router
+ from .agent_chat_routes import router as agent_chat_router
from .agentic_ide_routes import router as agentic_ide_router
from .antigravity_routes import router as antigravity_router
from .board_routes import (
@@ -525,6 +526,13 @@ class WebServer:
# "Speak in this conversation". Reuses chat_store + session_store +
# brain + speech_pipeline from app.state (graceful 503s when absent).
app.include_router(chats_router)
+ # Agent chat — the typed front-page chat as an agent session on the
+ # agent-tier providers (jarvis/agent_chat). The service is built on
+ # first use by the routes (store = data/agent_chat.db) so nothing
+ # opens on the boot path (AP-26); stop() cancels running turns.
+ app.state.agent_chat = None
+ app.state.agent_chat_factory = self._build_agent_chat_service
+ app.include_router(agent_chat_router)
app.include_router(drop_router)
# Default: no recorder wired up — _init_session_stack() in start()
# sets this once it succeeds.
@@ -3446,10 +3454,34 @@ class WebServer:
"Friends-Stack live: Telegram-Channel disabled (config off)"
)
+ def _build_agent_chat_service(self) -> Any:
+ """Build the agent-chat service on first use (see agent_chat_routes)."""
+ from jarvis.agent_chat.service import AgentChatService
+ from jarvis.agent_chat.store import AgentChatStore
+ from jarvis.brain.assistant_name import resolve_assistant_name
+
+ data_dir = Path(getattr(getattr(self.cfg, "memory", None), "data_dir", None) or "data")
+ store = AgentChatStore(data_dir / "agent_chat.db")
+
+ def _name() -> str:
+ try:
+ return resolve_assistant_name(self.cfg)
+ except Exception: # noqa: BLE001 — the name is cosmetic
+ return "Jarvis"
+
+ return AgentChatService(store, assistant_name=_name)
+
async def stop(self) -> None:
self._mic_level_sessions.clear()
self._stop_mic_level_bridge()
+ agent_chat = getattr(self.app.state, "agent_chat", None)
+ if agent_chat is not None:
+ try:
+ await agent_chat.cancel_all()
+ except Exception as exc: # noqa: BLE001
+ logger.opt(exception=exc).debug("agent chat cancel_all failed")
+
# Stop token refresh before the plugin registry so an in-flight refresh
# cannot enqueue a live-session rebuild while that registry is closing.
await self._stop_marketplace_refresh_scheduler()
diff --git a/tests/unit/agent_chat/__init__.py b/tests/unit/agent_chat/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/unit/agent_chat/test_agent_chat_core.py b/tests/unit/agent_chat/test_agent_chat_core.py
new file mode 100644
index 0000000000..a3ed581775
--- /dev/null
+++ b/tests/unit/agent_chat/test_agent_chat_core.py
@@ -0,0 +1,320 @@
+"""Agent chat — effort ladders, the store, the tools, the event reducers."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+
+import pytest
+
+from jarvis.agent_chat import effort
+from jarvis.agent_chat.catalog import PROVIDER_ROWS, provider_row
+from jarvis.agent_chat.events import make_event
+from jarvis.agent_chat.runner_api import messages_from_events
+from jarvis.agent_chat.runner_cli import (
+ _ClaudeState,
+ _CodexState,
+ translate_claude_line,
+ translate_codex_line,
+)
+from jarvis.agent_chat.store import AgentChatStore
+from jarvis.agent_chat.tools import execute_tool, summarize_call
+
+# ---------------------------------------------------------------- effort
+
+
+def test_effort_ladders_are_subsequences_of_the_universal_order():
+ for row in PROVIDER_ROWS:
+ levels = [lvl for lvl in effort.effort_levels(row.id) if lvl]
+ positions = [effort.ORDER.index(lvl) for lvl in levels]
+ assert positions == sorted(positions), row.id
+ default = effort.default_effort(row.id)
+ assert default in effort.effort_levels(row.id), row.id
+
+
+ ("provider", "picked", "expected"),
+ [
+ ("claude-api", "xhigh", "xhigh"),
+ ("claude-api", "none", "low"),
+ ("gemini", "xhigh", "high"),
+ ("gemini", "max", "high"),
+ ("openai-codex", "max", "max"),
+ ("openai-codex", "none", "low"),
+ ("gemini", "ultra", "high"),
+ ("openai", "", ""),
+ ("openai", None, ""),
+ ("grok", "medium", "medium"),
+ ("grok", "max", "xhigh"),
+ ("unknown-provider", "high", "high"),
+ ("openai", "bogus", "medium"),
+ ],
+)
+def test_normalize_effort_folds_onto_the_nearest_offered_level(provider, picked, expected):
+ assert effort.normalize_effort(provider, picked) == expected
+
+
+def test_catalog_rows_carry_ladders_and_curated_models_for_cli_runners():
+ claude = provider_row("claude-api")
+ assert claude is not None and claude.runner == "claude-cli"
+ d = claude.to_dict()
+ assert d["effort_levels"] == ["low", "medium", "high", "xhigh", "max"]
+ assert d["curated_models"], "CLI-backed rows need a curated list"
+ assert provider_row("openai").models_source == "live" # type: ignore[union-attr]
+
+
+# ----------------------------------------------------------------- store
+
+
+def test_store_round_trips_sessions_and_events(tmp_path: Path):
+ store = AgentChatStore(tmp_path / "agent_chat.db")
+ s = store.create_session(provider="openai", model="gpt-5.5", effort="high", cwd=str(tmp_path))
+ assert s.title == "" and s.message_count == 0
+
+ ev = store.append_event(s.session_id, make_event("user_message", {"text": "Hallo Welt, bitte"}))
+ assert ev["seq"] == 1
+ delta = store.append_event(s.session_id, make_event("text_delta", {"text": "x"}))
+ assert delta["seq"] == 0, "transient events are never persisted"
+ store.append_event(s.session_id, make_event("assistant_text", {"text": "Hi there"}))
+
+ again = store.get_session(s.session_id)
+ assert again is not None
+ assert again.title == "Hallo Welt, bitte"
+ assert again.message_count == 1
+ assert again.preview == "Hi there"
+
+ events = store.list_events(s.session_id)
+ assert [e["kind"] for e in events] == ["user_message", "assistant_text"]
+ assert store.list_events(s.session_id, after_seq=1)[0]["kind"] == "assistant_text"
+
+ # The store keeps whatever id the route validated against the runner's
+ # ladder (jarvis/agent_chat/permissions.py); it does not judge it.
+ updated = store.update_session(s.session_id, effort="low", permission_mode="accept-edits")
+ assert updated is not None and updated.effort == "low"
+ assert updated.permission_mode == "accept-edits"
+ assert store.list_sessions()[0].session_id == s.session_id
+ assert store.delete_session(s.session_id)
+ assert store.get_session(s.session_id) is None
+ assert store.list_events(s.session_id) == []
+ store.close()
+
+
+# ----------------------------------------------------------------- tools
+
+
+def _run(coro):
+ return asyncio.run(coro)
+
+
+def test_file_tools_read_write_edit_glob_grep(tmp_path: Path):
+ out, err = _run(
+ execute_tool("Write", {"file_path": "a/b.txt", "content": "one\ntwo\n"}, cwd=tmp_path)
+ )
+ assert not err and "Created" in out
+ assert (tmp_path / "a" / "b.txt").read_text(encoding="utf-8") == "one\ntwo\n"
+
+ out, err = _run(execute_tool("Read", {"file_path": "a/b.txt"}, cwd=tmp_path))
+ assert not err and "1\tone" in out and "2 lines" in out
+
+ out, err = _run(
+ execute_tool(
+ "Edit",
+ {"file_path": "a/b.txt", "old_string": "two", "new_string": "three"},
+ cwd=tmp_path,
+ )
+ )
+ assert not err and "1 replacement" in out
+
+ out, err = _run(
+ execute_tool(
+ "Edit", {"file_path": "a/b.txt", "old_string": "zzz", "new_string": "q"}, cwd=tmp_path
+ )
+ )
+ assert err and "not found" in out
+
+ out, err = _run(execute_tool("Glob", {"pattern": "**/*.txt"}, cwd=tmp_path))
+ assert not err and "a/b.txt" in out
+
+ out, err = _run(execute_tool("Grep", {"pattern": "thr.e", "glob": "*.txt"}, cwd=tmp_path))
+ assert not err and "a/b.txt:2:three" in out
+
+ out, err = _run(execute_tool("Ls", {}, cwd=tmp_path))
+ assert not err and "a/" in out
+
+ out, err = _run(execute_tool("Read", {"file_path": "missing.txt"}, cwd=tmp_path))
+ assert err
+
+
+def test_run_command_returns_output_and_exit_code(tmp_path: Path):
+ out, err = _run(execute_tool("RunCommand", {"command": "echo agent-chat-ok"}, cwd=tmp_path))
+ assert not err
+ assert "agent-chat-ok" in out and "[exit 0" in out
+
+
+def test_unknown_tool_is_an_error_not_a_crash(tmp_path: Path):
+ out, err = _run(execute_tool("Nope", {}, cwd=tmp_path))
+ assert err and "Unknown tool" in out
+
+
+def test_summarize_call_picks_the_human_field():
+ assert summarize_call("RunCommand", {"command": "git status\n--porcelain"}) == "git status"
+ assert summarize_call("Edit", {"file_path": "x.py"}) == "x.py"
+ assert summarize_call("Ls", {}) == "."
+
+
+# -------------------------------------------------------- history replay
+
+
+def test_messages_from_events_rebuilds_rounds_and_closes_dangling_calls():
+ events = [
+ make_event("user_message", {"text": "hi"}),
+ make_event("turn_started", {"turn_id": "t1"}),
+ make_event("assistant_text", {"turn_id": "t1", "text": "let me look"}),
+ make_event("tool_call", {"turn_id": "t1", "call_id": "c1", "name": "Ls", "input": {}}),
+ make_event(
+ "tool_result", {"turn_id": "t1", "call_id": "c1", "output": "a/\nb", "is_error": False}
+ ),
+ make_event("assistant_text", {"turn_id": "t1", "text": "done"}),
+ make_event("turn_finished", {"turn_id": "t1", "status": "done"}),
+ make_event("user_message", {"text": "again"}),
+ make_event("turn_started", {"turn_id": "t2"}),
+ make_event("tool_call", {"turn_id": "t2", "call_id": "c2", "name": "Ls", "input": {}}),
+ make_event("turn_finished", {"turn_id": "t2", "status": "cancelled"}),
+ ]
+ msgs = messages_from_events(events)
+ roles = [m.role for m in msgs]
+ assert roles == ["user", "assistant", "tool", "assistant", "user", "assistant", "tool"]
+ first_assistant = msgs[1]
+ assert isinstance(first_assistant.content, list)
+ assert [b["type"] for b in first_assistant.content] == ["text", "tool_use"]
+ assert msgs[2].tool_call_id == "c1"
+ # The cancelled round's tool call got a synthetic result so the next
+ # request is well-formed.
+ assert msgs[-1].tool_call_id == "c2"
+ assert "cancelled" in json.dumps(msgs[-1].content)
+
+
+# ---------------------------------------------------------- CLI shapes
+
+
+def test_claude_stream_translation_streams_then_finalizes():
+ st = _ClaudeState(turn_id="t")
+ lines = [
+ {"type": "system", "subtype": "init", "session_id": "sess-1"},
+ {"type": "stream_event", "event": {"type": "message_start", "message": {"id": "m1"}}},
+ {
+ "type": "stream_event",
+ "event": {
+ "type": "content_block_delta",
+ "index": 0,
+ "delta": {"type": "thinking_delta", "thinking": "hmm"},
+ },
+ },
+ {
+ "type": "assistant",
+ "message": {"id": "m1", "content": [{"type": "thinking", "thinking": "hmm"}]},
+ },
+ {
+ "type": "stream_event",
+ "event": {
+ "type": "content_block_delta",
+ "index": 1,
+ "delta": {"type": "text_delta", "text": "he"},
+ },
+ },
+ {
+ "type": "stream_event",
+ "event": {
+ "type": "content_block_delta",
+ "index": 1,
+ "delta": {"type": "text_delta", "text": "llo"},
+ },
+ },
+ {
+ "type": "assistant",
+ "message": {"id": "m1", "content": [{"type": "text", "text": "hello"}]},
+ },
+ {
+ "type": "assistant",
+ "message": {
+ "id": "m1",
+ "content": [
+ {"type": "tool_use", "id": "tu1", "name": "Bash", "input": {"command": "ls"}}
+ ],
+ },
+ },
+ {
+ "type": "user",
+ "message": {
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "tu1",
+ "content": "a b",
+ "is_error": False,
+ }
+ ]
+ },
+ },
+ {
+ "type": "result",
+ "subtype": "success",
+ "is_error": False,
+ "total_cost_usd": 0.01,
+ "usage": {"output_tokens": 5},
+ },
+ ]
+ kinds: list[str] = []
+ for obj in lines:
+ for ev in translate_claude_line(obj, st):
+ kinds.append(ev["kind"])
+ if ev["kind"] == "assistant_text":
+ assert ev["payload"]["text"] == "hello"
+ assert ev["payload"]["message_id"] == "m1"
+ if ev["kind"] == "tool_call":
+ assert ev["payload"]["summary"] == "ls"
+ assert kinds == [
+ "reasoning_delta",
+ "reasoning",
+ "text_delta",
+ "text_delta",
+ "assistant_text",
+ "tool_call",
+ "tool_result",
+ ]
+ assert st.vendor_session == "sess-1"
+ assert st.cost_usd == 0.01 and st.usage == {"output_tokens": 5} and st.status == "done"
+
+
+def test_codex_stream_translation_maps_items_to_tools():
+ st = _CodexState(turn_id="t")
+ lines = [
+ {"type": "thread.started", "thread_id": "th-9"},
+ {"type": "turn.started"},
+ {
+ "type": "item.started",
+ "item": {"id": "i1", "type": "command_execution", "command": "pytest -q"},
+ },
+ {
+ "type": "item.completed",
+ "item": {
+ "id": "i1",
+ "type": "command_execution",
+ "command": "pytest -q",
+ "aggregated_output": "3 passed",
+ "exit_code": 0,
+ },
+ },
+ {"type": "item.completed", "item": {"id": "i2", "type": "reasoning", "text": "thinking"}},
+ {
+ "type": "item.completed",
+ "item": {"id": "i3", "type": "agent_message", "text": "All green."},
+ },
+ {"type": "turn.completed", "usage": {"input_tokens": 10, "output_tokens": 4}},
+ ]
+ kinds = [ev["kind"] for obj in lines for ev in translate_codex_line(obj, st)]
+ assert kinds == ["tool_call", "tool_result", "reasoning", "assistant_text"]
+ assert st.vendor_session == "th-9"
+ assert st.usage == {"input_tokens": 10, "output_tokens": 4}
+ assert st.emitted_text
diff --git a/tests/unit/agent_chat/test_agent_chat_ladders.py b/tests/unit/agent_chat/test_agent_chat_ladders.py
new file mode 100644
index 0000000000..7058dca6d3
--- /dev/null
+++ b/tests/unit/agent_chat/test_agent_chat_ladders.py
@@ -0,0 +1,413 @@
+"""Permission ladders, the agy wire shape, CLI model catalogs, API effort."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from jarvis.agent_chat import permissions, runner_cli
+from jarvis.agent_chat.catalog import CODEX_FALLBACK_MODELS, provider_row
+from jarvis.agent_chat.runner_cli import (
+ _AgyState,
+ agy_model_args,
+ agy_model_catalog,
+ plan_agy,
+ plan_claude,
+ plan_codex,
+ translate_agy_line,
+)
+from jarvis.plugins.brain._anthropic_base import _is_reasoning_model, reasoning_kwargs
+
+# ------------------------------------------------------------ permissions
+
+
+def test_every_runner_has_a_ladder_with_its_default_on_it():
+ for runner in ("claude-cli", "codex-cli", "agy-cli", "grok-cli", "api"):
+ ids = permissions.permission_ids(runner)
+ assert ids, runner
+ assert permissions.default_permission(runner) in ids, runner
+ # Plan is the Build | Plan switch; every ladder offers it.
+ assert "plan" in ids, runner
+
+
+ ("runner", "picked", "expected"),
+ [
+ ("claude-cli", "acceptEdits", "acceptEdits"),
+ ("claude-cli", "auto", "auto"), # Claude Code's own classifier mode
+ ("claude-cli", "ask", "default"), # legacy draft value
+ ("claude-cli", "full-access", "bypassPermissions"),
+ ("codex-cli", "acceptEdits", "auto"), # Codex's "auto" = workspace-write
+ ("codex-cli", "bypassPermissions", "full-access"),
+ ("codex-cli", "plan", "plan"),
+ ("agy-cli", "default", "accept-edits"), # ask is never folded onto plan
+ ("agy-cli", "bypassPermissions", "skip-permissions"),
+ ("api", "acceptEdits", "accept-edits"),
+ ("api", "", "ask"),
+ ("api", "read-only", "plan"),
+ ],
+)
+def test_normalize_permission_folds_across_runners(runner, picked, expected):
+ assert permissions.normalize_permission(runner, picked) == expected
+
+
+# ------------------------------------------------------------ planners
+
+
+def test_claude_planner_passes_the_cli_mode_through(monkeypatch, tmp_path: Path):
+ monkeypatch.setattr(runner_cli, "claude_argv_prefix", lambda: ["claude"])
+ plan = plan_claude(
+ prompt="hi", cwd=tmp_path, model="opus", effort="xhigh", permission_mode="plan", resume=None
+ )
+ argv = plan.argv
+ assert argv[argv.index("--permission-mode") + 1] == "plan"
+ assert argv[argv.index("--effort") + 1] == "xhigh"
+ assert argv[argv.index("--model") + 1] == "opus"
+ assert plan.shape == "claude" and plan.keep_stdin
+ # The control protocol: NDJSON user message in, prompts answered on stdin.
+ assert argv[argv.index("--input-format") + 1] == "stream-json"
+ assert argv[argv.index("--permission-prompt-tool") + 1] == "stdio"
+ assert json.loads(plan.stdin_text or "") == {
+ "type": "user",
+ "message": {"role": "user", "content": "hi"},
+ }
+
+
+def test_codex_planner_maps_the_presets(monkeypatch, tmp_path: Path):
+ monkeypatch.setattr(runner_cli, "codex_argv_prefix", lambda: ["codex"])
+ monkeypatch.setattr(runner_cli, "read_codex_models", lambda: None)
+
+ def argv_for(mode: str, effort: str = "high", model: str = "") -> list[str]:
+ return plan_codex(
+ prompt="p", cwd=tmp_path, model=model, effort=effort, permission_mode=mode, resume=None
+ ).argv
+
+ assert 'sandbox_mode="read-only"' in argv_for("read-only")
+ assert 'sandbox_mode="workspace-write"' in argv_for("auto")
+ assert "--dangerously-bypass-approvals-and-sandbox" in argv_for("full-access")
+ approve = argv_for("approve-for-me")
+ assert (
+ 'approvals_reviewer="auto_review"' in approve
+ and 'sandbox_mode="workspace-write"' in approve
+ )
+ plan = plan_codex(
+ prompt="p", cwd=tmp_path, model="", effort="high", permission_mode="plan", resume=None
+ )
+ assert 'sandbox_mode="read-only"' in plan.argv
+ assert plan.stdin_text is not None and plan.stdin_text.startswith("PLAN MODE")
+ # Never the flags codex exec rejects with exit 2.
+ for argv in (argv_for("auto"), argv_for("full-access")):
+ assert "--full-auto" not in argv and "-a" not in argv
+ assert "model_reasoning_summary=auto" in argv_for("auto")
+ # Effort is snapped to the model's own ladder when the catalog knows it.
+ monkeypatch.setattr(
+ runner_cli,
+ "read_codex_models",
+ lambda: [
+ {"id": "gpt-5.5", "label": "GPT-5.5", "efforts": ["low", "medium", "high", "xhigh"]}
+ ],
+ )
+ assert "model_reasoning_effort=xhigh" in argv_for("auto", effort="ultra", model="gpt-5.5")
+
+
+def test_codex_resume_uses_the_resume_subcommand(monkeypatch, tmp_path: Path):
+ monkeypatch.setattr(runner_cli, "codex_argv_prefix", lambda: ["codex"])
+ monkeypatch.setattr(runner_cli, "read_codex_models", lambda: None)
+ argv = plan_codex(
+ prompt="p", cwd=tmp_path, model="", effort="", permission_mode="auto", resume="thread-1"
+ ).argv
+ assert argv[1:4] == ["exec", "resume", "thread-1"]
+ assert "--cd" not in argv # exec resume has no --cd
+ assert argv[-1] == "-"
+
+
+def test_agy_planner_speaks_agy(monkeypatch, tmp_path: Path):
+ monkeypatch.setattr(runner_cli, "agy_argv_prefix", lambda: ["agy"])
+ monkeypatch.setattr(runner_cli, "_agy_catalog_cached", lambda: None)
+ plan = plan_agy(
+ prompt="do it",
+ cwd=tmp_path,
+ model="gemini-3.1-pro",
+ effort="medium",
+ permission_mode="accept-edits",
+ resume=None,
+ )
+ argv = plan.argv
+ assert plan.shape == "agy"
+ assert plan.stdin_text == "do it" and "-p" not in argv and "--print" not in argv
+ assert argv[argv.index("--mode") + 1] == "accept-edits"
+ assert argv[argv.index("--add-dir") + 1] == str(tmp_path)
+ assert "--print-timeout" in argv
+ # Pro knows only low/high: medium snaps to low, and the pair is sent.
+ assert argv[argv.index("--model") + 1] == "gemini-3.1-pro"
+ assert argv[argv.index("--effort") + 1] == "low"
+ assert plan.env.get("AGY_CLI_HIDE_LOGO") == "1"
+
+ skip = plan_agy(
+ prompt="x",
+ cwd=tmp_path,
+ model="",
+ effort="",
+ permission_mode="skip-permissions",
+ resume="c1",
+ ).argv
+ assert (
+ "--dangerously-skip-permissions" in skip and skip[skip.index("--conversation") + 1] == "c1"
+ )
+ planned = plan_agy(
+ prompt="x", cwd=tmp_path, model="", effort="", permission_mode="plan", resume=None
+ ).argv
+ assert planned[planned.index("--mode") + 1] == "plan"
+
+
+def test_agy_model_args_respects_the_strict_pairing():
+ assert agy_model_args("claude-sonnet-4-6", "high") == ["--model", "claude-sonnet-4-6"]
+ assert agy_model_args("gpt-oss-120b", "low") == ["--model", "gpt-oss-120b"]
+ assert agy_model_args("gemini-3.5-flash", "high") == [
+ "--model",
+ "gemini-3.5-flash",
+ "--effort",
+ "high",
+ ]
+ assert agy_model_args("", "medium") == ["--effort", "medium"]
+ # A suffixed id is passed through untouched (no --effort next to it).
+ assert agy_model_args("gemini-3.5-flash-low", "high") == ["--model", "gemini-3.5-flash-low"]
+
+
+def test_agy_model_catalog_folds_suffixed_ids():
+ raw = [
+ {"id": "gemini-3.7-flash-high", "label": "Gemini 3.7 Flash (High)"},
+ {"id": "gemini-3.7-flash-low", "label": "Gemini 3.7 Flash (Low)"},
+ {"id": "gemini-3.7-flash-medium", "label": "Gemini 3.7 Flash (Medium)"},
+ {"id": "gemini-3.1-pro-high", "label": "Gemini 3.1 Pro (High)"},
+ {"id": "gemini-3.1-pro-low", "label": "Gemini 3.1 Pro (Low)"},
+ {"id": "claude-sonnet-4-6", "label": "Claude Sonnet 4.6 (Thinking)"},
+ {"id": "gpt-oss-120b-medium", "label": "GPT-OSS 120B (Medium)"},
+ ]
+ rows = agy_model_catalog(raw)
+ by_id = {r["id"]: r for r in rows}
+ assert by_id["gemini-3.7-flash"] == {
+ "id": "gemini-3.7-flash",
+ "label": "Gemini 3.7 Flash",
+ "efforts": ["low", "medium", "high"],
+ }
+ assert by_id["gemini-3.1-pro"]["efforts"] == ["low", "high"]
+ assert by_id["claude-sonnet-4-6"]["efforts"] == []
+ assert by_id["gpt-oss-120b"]["efforts"] == ["medium"]
+ # No list at all -> the fallback table.
+ assert agy_model_catalog(None)[0]["id"] == "gemini-3.7-flash"
+
+
+# ------------------------------------------------------------ agy translation
+
+
+def _agy_lines() -> list[dict]:
+ return [
+ {"event": "init", "conversation_id": "conv-1", "init": {"cwd": "C:\\x", "tools": []}},
+ {
+ "event": "step_update",
+ "step_update": {
+ "conversation_id": "conv-1",
+ "step_index": 1,
+ "state": "ACTIVE",
+ "step_type": "agent_response",
+ "text_delta": "Let me ",
+ },
+ },
+ {
+ "event": "step_update",
+ "step_update": {
+ "step_index": 1,
+ "state": "DONE",
+ "step_type": "agent_response",
+ "text_delta": "look.",
+ },
+ },
+ {
+ "event": "step_update",
+ "step_update": {
+ "step_index": 2,
+ "state": "ACTIVE",
+ "step_type": "tool",
+ "tool_name": "run_command",
+ "tool_info": {"name": "run_command", "parameters": {"CommandLine": "echo HELLO"}},
+ },
+ },
+ {
+ "event": "step_update",
+ "step_update": {
+ "step_index": 2,
+ "state": "DONE",
+ "step_type": "tool",
+ "tool_name": "run_command",
+ "tool_info": {
+ "name": "run_command",
+ "parameters": {"CommandLine": "echo HELLO"},
+ "output": "HELLO\r\n",
+ },
+ "duration_seconds": 1.5,
+ },
+ },
+ {
+ "event": "step_update",
+ "step_update": {
+ "step_index": 3,
+ "state": "ERROR",
+ "step_type": "tool",
+ "tool_name": "run_command",
+ "tool_info": {
+ "name": "run_command",
+ "parameters": {"CommandLine": "rm x"},
+ "error": {"type": "TOOL_ERROR", "message": "user denied permission"},
+ },
+ },
+ },
+ {
+ "event": "result",
+ "result": {
+ "conversation_id": "conv-1",
+ "status": "SUCCESS",
+ "response": "Done: HELLO",
+ "duration_seconds": 9.7,
+ "num_turns": 1,
+ "usage": {"input_tokens": 10, "output_tokens": 5, "thinking_tokens": 2},
+ },
+ },
+ ]
+
+
+def test_translate_agy_line_builds_the_timeline():
+ st = _AgyState(turn_id="t1")
+ events: list[dict] = []
+ for line in _agy_lines():
+ events.extend(translate_agy_line(line, st))
+ kinds = [e["kind"] for e in events]
+ assert kinds == [
+ "text_delta",
+ "text_delta",
+ "assistant_text",
+ "tool_call",
+ "tool_result",
+ "tool_call",
+ "tool_result",
+ ]
+ assert events[2]["payload"]["text"] == "Let me look."
+ call = events[3]["payload"]
+ assert call["name"] == "run_command" and call["summary"] == "echo HELLO"
+ result = events[4]["payload"]
+ assert result["output"].startswith("HELLO") and result["is_error"] is False
+ assert result["duration_ms"] == 1500
+ denied = events[6]["payload"]
+ assert denied["is_error"] and "denied" in denied["output"]
+ assert st.vendor_session == "conv-1"
+ assert st.status == "done" and st.result_text == "Done: HELLO"
+ assert st.usage == {"input_tokens": 10, "output_tokens": 5, "thinking_tokens": 2}
+
+
+def test_translate_agy_line_reads_failure_from_result_status():
+ st = _AgyState(turn_id="t2")
+ translate_agy_line(
+ {"event": "result", "result": {"status": "ERROR", "error": "timeout waiting for response"}},
+ st,
+ )
+ assert st.status == "error" and "timeout" in (st.error or "")
+ st2 = _AgyState(turn_id="t3")
+ translate_agy_line({"event": "result", "result": {"status": "CANCELED"}}, st2)
+ assert st2.status == "error"
+
+
+# ------------------------------------------------------------ codex catalog
+
+
+def test_read_codex_models_reads_the_account_cache(monkeypatch, tmp_path: Path):
+ home = tmp_path / "codex-home"
+ home.mkdir()
+ (home / "models_cache.json").write_text(
+ json.dumps(
+ {
+ "models": [
+ {
+ "slug": "gpt-5.5",
+ "display_name": "GPT-5.5",
+ "visibility": "list",
+ "priority": 3,
+ "supported_reasoning_levels": [{"effort": "low"}, {"effort": "high"}],
+ },
+ {
+ "slug": "gpt-5.6-terra",
+ "display_name": "GPT-5.6-Terra",
+ "visibility": "list",
+ "priority": 2,
+ "supported_reasoning_levels": [{"effort": "medium"}, {"effort": "ultra"}],
+ "upgrade": None,
+ },
+ {"slug": "codex-auto-review", "visibility": "hide", "priority": 1},
+ {
+ "slug": "gpt-5.4-mini",
+ "display_name": "GPT-5.4-Mini",
+ "visibility": "list",
+ "priority": 9,
+ "supported_reasoning_levels": [],
+ "upgrade": {
+ "model": "gpt-5.6-luna",
+ "retirement_at": "2026-08-31T19:00:00Z",
+ },
+ },
+ ]
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(runner_cli, "_account_env", lambda platform: {"CODEX_HOME": str(home)})
+ rows = runner_cli.read_codex_models()
+ assert rows is not None
+ assert [r["id"] for r in rows] == ["gpt-5.6-terra", "gpt-5.5", "gpt-5.4-mini"]
+ assert rows[0]["efforts"] == ["medium", "ultra"]
+ assert rows[2]["note"] == "retires 2026-08-31"
+ # No cache -> None, and the catalog's fallback carries the picker.
+ monkeypatch.setattr(runner_cli, "_account_env", lambda platform: {"CODEX_HOME": str(tmp_path)})
+ assert runner_cli.read_codex_models() is None
+ assert CODEX_FALLBACK_MODELS[0].id == "gpt-5.6-sol"
+
+
+def test_catalog_rows_carry_per_model_efforts_for_cli_runners():
+ agy = provider_row("antigravity")
+ assert agy is not None
+ models = agy.to_dict()["curated_models"]
+ assert models[0]["id"] == "gemini-3.7-flash" and models[0]["efforts"] == [
+ "low",
+ "medium",
+ "high",
+ ]
+ assert any(m["id"] == "claude-sonnet-4-6" and m["efforts"] == [] for m in models)
+ codex = provider_row("openai-codex")
+ assert codex is not None
+ assert codex.to_dict()["curated_models"][0]["efforts"][-1] == "ultra"
+
+
+# ------------------------------------------------------------ Anthropic API effort
+
+
+def test_anthropic_adapter_effort_and_temperature_rules():
+ # Claude 5 / 4.x families: no temperature.
+ for model in ("claude-fable-5", "claude-opus-5", "claude-sonnet-5", "claude-opus-4-8"):
+ assert _is_reasoning_model(model), model
+ assert not _is_reasoning_model("claude-3-5-sonnet-20241022")
+ # No effort requested -> nothing added (the voice brain's requests stay as they were).
+ assert reasoning_kwargs("claude-opus-5", None) == {}
+ assert reasoning_kwargs("claude-opus-5", "") == {}
+ # Effort -> output_config.effort + adaptive thinking on the models that take it.
+ assert reasoning_kwargs("claude-opus-5", "xhigh") == {
+ "output_config": {"effort": "xhigh"},
+ "thinking": {"type": "adaptive"},
+ }
+ # Opus 4.6 has no xhigh: snaps to high; Opus 4.5 tops out at high.
+ assert reasoning_kwargs("claude-opus-4-6", "xhigh")["output_config"] == {"effort": "high"}
+ assert reasoning_kwargs("claude-opus-4-5", "max")["output_config"] == {"effort": "high"}
+ assert "thinking" not in reasoning_kwargs("claude-opus-4-5", "max")
+ # Haiku 4.5 rejects the parameter: nothing is sent.
+ assert reasoning_kwargs("claude-haiku-4-5-20251001", "high") == {}
+ # none/minimal mean "as little as possible" -> the lowest rung.
+ assert reasoning_kwargs("claude-sonnet-5", "none")["output_config"] == {"effort": "low"}
diff --git a/tests/unit/agent_chat/test_agent_chat_service.py b/tests/unit/agent_chat/test_agent_chat_service.py
new file mode 100644
index 0000000000..613cb24951
--- /dev/null
+++ b/tests/unit/agent_chat/test_agent_chat_service.py
@@ -0,0 +1,276 @@
+"""Agent chat — a whole turn through the service and the routes with a fake brain."""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import AsyncIterator
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.agent_chat import runner_api
+from jarvis.agent_chat.service import AgentChatService, SessionBusy
+from jarvis.agent_chat.store import AgentChatStore
+from jarvis.core.protocols import BrainDelta, BrainRequest
+from jarvis.ui.web.agent_chat_routes import router
+
+
+class ScriptedBrain:
+ """A brain that answers from a script: each entry is a list of deltas."""
+
+ def __init__(self, model: str | None = None) -> None:
+ self.model = model
+ self.requests: list[BrainRequest] = []
+
+ script: list[list[BrainDelta]] = []
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ self.requests.append(req)
+ ScriptedBrain.seen.append(req)
+ step = ScriptedBrain.script.pop(0) if ScriptedBrain.script else [BrainDelta(content="(done)")]
+ for d in step:
+ await asyncio.sleep(0)
+ yield d
+
+ seen: list[BrainRequest] = []
+
+
+def scripted(monkeypatch: pytest.MonkeyPatch):
+ ScriptedBrain.script = []
+ ScriptedBrain.seen = []
+ monkeypatch.setitem(runner_api.BRAIN_BY_PROVIDER, "fakeprov", ("tests.unit.agent_chat.test_agent_chat_service", "ScriptedBrain"))
+ # Catalog has no row for fakeprov; supports_api_runner() still says yes.
+ return ScriptedBrain
+
+
+async def _drain(q: asyncio.Queue, until_kind: str, timeout: float = 5.0) -> list[dict[str, Any]]:
+ out: list[dict[str, Any]] = []
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + timeout
+ while True:
+ remaining = deadline - loop.time()
+ if remaining <= 0:
+ raise AssertionError(f"timed out waiting for {until_kind}; got {[e['kind'] for e in out]}")
+ ev = await asyncio.wait_for(q.get(), timeout=remaining)
+ out.append(ev)
+ if ev["kind"] == until_kind:
+ return out
+
+
+def test_turn_streams_text_runs_a_tool_and_asks_for_approval(tmp_path: Path, scripted):
+ ScriptedBrain.script = [
+ [
+ BrainDelta(content="Let me "),
+ BrainDelta(content="write it."),
+ BrainDelta(
+ tool_call={
+ "id": "c1",
+ "name": "Write",
+ "input": {"file_path": "hello.txt", "content": "hi"},
+ }
+ ),
+ BrainDelta(finish_reason="tool_use", usage={"input_tokens": 3, "output_tokens": 4}),
+ ],
+ [BrainDelta(content="Written."), BrainDelta(finish_reason="stop")],
+ ]
+
+ async def scenario() -> None:
+ store = AgentChatStore(":memory:")
+ svc = AgentChatService(store, assistant_name=lambda: "Testo")
+ session = svc.create_session(provider="fakeprov", model="m", effort="high", cwd=str(tmp_path))
+ q = svc.subscribe(session.session_id)
+ turn_id = await svc.send(session.session_id, "please write hello.txt")
+ with pytest.raises(SessionBusy):
+ await svc.send(session.session_id, "again")
+
+ events = await _drain(q, "approval_required")
+ kinds = [e["kind"] for e in events]
+ assert kinds[:2] == ["user_message", "turn_started"]
+ assert "text_delta" in kinds and "tool_call" in kinds
+ approval = events[-1]["payload"]
+ assert approval["name"] == "Write" and approval["summary"] == "hello.txt"
+ assert svc.pending_approvals(session.session_id) == [approval["approval_id"]]
+
+ assert svc.resolve_approval(session.session_id, approval["approval_id"], "allow")
+ events += await _drain(q, "turn_finished")
+ kinds = [e["kind"] for e in events]
+ assert "approval_resolved" in kinds and "tool_result" in kinds
+ assert (tmp_path / "hello.txt").read_text(encoding="utf-8") == "hi"
+ finished = events[-1]["payload"]
+ assert finished["turn_id"] == turn_id and finished["status"] == "done"
+ assert finished["usage"] == {"input_tokens": 3, "output_tokens": 4}
+
+ # The persisted log has no transient deltas and the final texts.
+ stored = store.list_events(session.session_id)
+ stored_kinds = [e["kind"] for e in stored]
+ assert "text_delta" not in stored_kinds
+ texts = [e["payload"]["text"] for e in stored if e["kind"] == "assistant_text"]
+ assert texts == ["Let me write it.", "Written."]
+ # The second request carried the tool round back to the brain.
+ second = ScriptedBrain.seen[1]
+ assert second.reasoning_effort == "high"
+ assert second.messages[-1].role == "tool"
+ assert second.system and "Testo" in second.system
+ assert not svc.is_running(session.session_id)
+
+ asyncio.run(scenario())
+
+
+def test_deny_feeds_a_denied_result_and_allow_always_flips_the_mode(tmp_path: Path, scripted):
+ ScriptedBrain.script = [
+ [BrainDelta(tool_call={"id": "c1", "name": "RunCommand", "input": {"command": "echo x"}})],
+ [BrainDelta(tool_call={"id": "c2", "name": "RunCommand", "input": {"command": "echo y"}})],
+ [BrainDelta(tool_call={"id": "c3", "name": "RunCommand", "input": {"command": "echo z"}})],
+ [BrainDelta(content="ok")],
+ ]
+
+ async def scenario() -> None:
+ svc = AgentChatService(AgentChatStore(":memory:"))
+ session = svc.create_session(provider="fakeprov", cwd=str(tmp_path))
+ q = svc.subscribe(session.session_id)
+ await svc.send(session.session_id, "run things")
+ ev = (await _drain(q, "approval_required"))[-1]["payload"]
+ svc.resolve_approval(session.session_id, ev["approval_id"], "deny")
+ events = await _drain(q, "tool_result")
+ assert events[-1]["payload"]["is_error"] and "Denied" in events[-1]["payload"]["output"]
+ ev = (await _drain(q, "approval_required"))[-1]["payload"]
+ svc.resolve_approval(session.session_id, ev["approval_id"], "allow_always")
+ events = await _drain(q, "turn_finished")
+ kinds = [e["kind"] for e in events]
+ # c2 ran after allow_always, c3 ran with no approval card at all.
+ assert kinds.count("approval_required") == 0
+ assert kinds.count("tool_result") == 2
+ assert svc.store.get_session(session.session_id).permission_mode == "auto" # type: ignore[union-attr]
+
+ asyncio.run(scenario())
+
+
+def test_cancel_ends_the_turn(tmp_path: Path, scripted):
+ ScriptedBrain.script = [
+ [BrainDelta(tool_call={"id": "c1", "name": "Write", "input": {"file_path": "a", "content": "b"}})],
+ ]
+
+ async def scenario() -> None:
+ svc = AgentChatService(AgentChatStore(":memory:"))
+ session = svc.create_session(provider="fakeprov", cwd=str(tmp_path))
+ q = svc.subscribe(session.session_id)
+ await svc.send(session.session_id, "go")
+ await _drain(q, "approval_required")
+ assert await svc.cancel(session.session_id)
+ events = await _drain(q, "turn_finished")
+ assert events[-1]["payload"]["status"] == "cancelled"
+ assert not (tmp_path / "a").exists()
+
+ asyncio.run(scenario())
+
+
+def test_provider_error_is_reported_not_raised(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ class Boom:
+ def __init__(self, model=None):
+ pass
+
+ async def complete(self, req):
+ raise RuntimeError("401 invalid api key")
+ yield # pragma: no cover
+
+ monkeypatch.setitem(runner_api.BRAIN_BY_PROVIDER, "boomprov", (__name__, "Boom"))
+ import sys
+
+ setattr(sys.modules[__name__], "Boom", Boom)
+
+ async def scenario() -> None:
+ svc = AgentChatService(AgentChatStore(":memory:"))
+ session = svc.create_session(provider="boomprov", cwd=str(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 "invalid api key" in events[-1]["payload"]["error"]
+
+ asyncio.run(scenario())
+
+
+# ------------------------------------------------------------------ routes
+
+
+def _app(tmp_path: Path) -> FastAPI:
+ app = FastAPI()
+ app.include_router(router)
+ app.state.agent_chat = None
+ app.state.agent_chat_factory = lambda: AgentChatService(
+ AgentChatStore(tmp_path / "db.sqlite"), default_cwd=lambda: str(tmp_path)
+ )
+ return app
+
+
+def test_routes_catalog_sessions_and_websocket_snapshot(tmp_path: Path, scripted):
+ ScriptedBrain.script = [[BrainDelta(content="hello from fake")]]
+ # One portal for the whole test: a bare TestClient opens a fresh event
+ # loop per request, and the turn task spawned by POST /messages would be
+ # cancelled the moment that request returns.
+ with TestClient(_app(tmp_path)) as client:
+ _exercise_routes(client, tmp_path)
+
+
+def _exercise_routes(client: TestClient, tmp_path: Path) -> None:
+
+ cat = client.get("/api/agent-chat/catalog").json()
+ ids = [p["id"] for p in cat["providers"]]
+ assert "claude-api" in ids and "openai" in ids and "openai-codex" in ids
+ claude = next(p for p in cat["providers"] if p["id"] == "claude-api")
+ assert claude["effort_levels"][-1] == "max"
+ assert cat["default_cwd"] == str(tmp_path)
+
+ created = client.post(
+ "/api/agent-chat/sessions",
+ json={"provider": "fakeprov", "model": "m", "effort": "xhigh"},
+ )
+ assert created.status_code == 201, created.text
+ sid = created.json()["session_id"]
+ assert created.json()["cwd"] == str(tmp_path)
+
+ bad = client.post("/api/agent-chat/sessions", json={"provider": "fakeprov", "cwd": "/no/such/dir"})
+ assert bad.status_code == 400
+
+ patched = client.patch(f"/api/agent-chat/sessions/{sid}", json={"title": "My chat", "effort": "low"})
+ assert patched.json()["title"] == "My chat" and patched.json()["effort"] == "low"
+
+ with client.websocket_connect(f"/api/agent-chat/sessions/{sid}/ws") as ws:
+ snap = ws.receive_json()
+ assert snap["type"] == "snapshot" and snap["session"]["session_id"] == sid
+ # A session_updated event from the PATCH is already in the log.
+ assert [e["kind"] for e in snap["events"]] == ["session_updated"]
+
+ sent = client.post(f"/api/agent-chat/sessions/{sid}/messages", json={"text": "hi"})
+ assert sent.status_code == 202, sent.text
+ kinds: list[str] = []
+ while True:
+ frame = ws.receive_json()
+ if frame["type"] != "event":
+ continue
+ kinds.append(frame["event"]["kind"])
+ if frame["event"]["kind"] == "turn_finished":
+ break
+ assert kinds[0] == "user_message" and "assistant_text" in kinds
+
+ detail = client.get(f"/api/agent-chat/sessions/{sid}").json()
+ assert detail["session"]["title"] == "My chat"
+ assert any(e["kind"] == "assistant_text" for e in detail["events"])
+
+ listed = client.get("/api/agent-chat/sessions").json()["sessions"]
+ assert listed[0]["session_id"] == sid
+
+ assert client.post(f"/api/agent-chat/sessions/{sid}/cancel").json()["cancelled"] is False
+ assert client.delete(f"/api/agent-chat/sessions/{sid}").json()["ok"]
+ assert client.get(f"/api/agent-chat/sessions/{sid}").status_code == 404
+
+
+def test_routes_answer_503_without_a_service(tmp_path: Path):
+ app = FastAPI()
+ app.include_router(router)
+ client = TestClient(app)
+ assert client.get("/api/agent-chat/sessions").status_code == 503