Skip to content

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

feat(agent-chat): the IDE's chat seats every coding CLI the IDE registers, each as a chat

rubenluetke10-beepf20610eaf3d8
diff --git a/docs/product/extend-and-automate/agentic-ide.md b/docs/product/extend-and-automate/agentic-ide.md
index 393981cc71..3b9f2b5459 100644
--- a/docs/product/extend-and-automate/agentic-ide.md
+++ b/docs/product/extend-and-automate/agentic-ide.md
@@ -66,6 +66,19 @@ Use the workspace bar to add, switch, rename, or close workspaces. Switching
tabs or app sections leaves panes running. Closing a workspace stops its panes;
files they wrote remain.
+### Every Coding CLI, as a Chat
+
+Chat mode's provider picker lists the same coding CLIs the pane step does —
+Claude Code, Codex, OpenCode, Kimi Code, GLM Coding Plan, Grok Build,
+Antigravity and DeepSeek Harness — under **Coding CLIs**, each with the
+models, effort levels and permission modes that CLI actually takes. Every one
+of them answers in the chat itself: the reply, the model's reasoning where the
+CLI shares it, and each tool call with its result appear as rows in the
+conversation, never as a terminal. A CLI that keeps its own login (OpenCode,
+Kimi Code, DeepSeek Harness) shows as available once it is installed; GLM
+Coding Plan needs the Z.ai key from the API Keys page. A CLI you added
+yourself opens in a pane — it has no headless mode this app could read.
+
### Add a Coding CLI of Your Own
The pane step lists the coding CLIs Jarvis ships with. If yours is not among
diff --git a/jarvis/agent_chat/__init__.py b/jarvis/agent_chat/__init__.py
index c3a49d8298..be9adaa8b3 100644
--- a/jarvis/agent_chat/__init__.py
+++ b/jarvis/agent_chat/__init__.py
@@ -5,12 +5,14 @@ One package, two surfaces (``store.SURFACES``):
* ``"jarvis"`` — the front page's chat. What you type is input to Jarvis:
the same assistant the microphone talks to, on the model the composer
picked for THIS chat (:mod:`.runner_brain` — ``BrainManager.generate``
- with a per-turn override; the live voice brain is never switched). A
- subscription CLI seat (Claude Code, Codex, …) runs as Jarvis through
- :mod:`.runner_cli` + :mod:`.jarvis_harness`, so the subscription pays.
- The folder chip is Jarvis' working folder (:mod:`.folder_tools`), and the
- one permission ladder — Ask / Auto-accept edits / Bypass, plus Plan —
- decides what asks through a clickable card (:mod:`.approval_bridge`).
+ with a per-turn override; the live voice brain is never switched). Every
+ seat here is a provider API behind a key — no vendor CLI runs this chat
+ (``surface_kits.SurfaceKit.cli_seats``, maintainer 2026-08-26), so one
+ pipeline answers, one place picks the model and one ledger counts the
+ cost. The folder chip is Jarvis' working folder (:mod:`.folder_tools`),
+ and the one permission ladder — Ask / Auto-accept edits / Bypass, plus
+ Plan — decides what asks through a clickable card
+ (:mod:`.approval_bridge`).
* ``"agent"`` — a plain coding-agent session in a folder, the Claude Code
shape, which the Agentic IDE's chat mode runs: a vendor CLI or the API tool
loop, with the vendor's own permission ladder.
@@ -20,7 +22,8 @@ The pieces:
* :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);
+ family, curated model lists for the CLI-backed providers) and which of
+ them each surface may be seated on (``rows_for``);
* :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
@@ -28,8 +31,9 @@ The pieces:
* :mod:`.store` — SQLite persistence for sessions and their event log;
* :mod:`.runner_api` / :mod:`.runner_cli` / :mod:`.runner_brain` — the
three ways a turn runs: the provider's own chat API in a coding-agent tool
- loop, a vendor CLI (``claude``, ``codex``, ``agy``, ``grok``) driven
- non-interactively, or Jarvis' own brain;
+ loop, a vendor CLI driven non-interactively — every coding CLI the
+ Agentic IDE registers: ``claude``, ``codex``, ``opencode``, ``kimi``, GLM
+ Coding Plan, ``grok``, ``agy``, ``dsh`` — or Jarvis' own brain;
* :mod:`.folder_tools` / :mod:`.approval_bridge` — the Jarvis surface's
hands in the folder and the card that answers the executor's ticket;
* :mod:`.service` — sessions in flight, subscribers, cancel and approvals.
diff --git a/jarvis/agent_chat/catalog.py b/jarvis/agent_chat/catalog.py
index cbd6bc3ffd..506cd54a38 100644
--- a/jarvis/agent_chat/catalog.py
+++ b/jarvis/agent_chat/catalog.py
@@ -1,12 +1,18 @@
"""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 row. The **coding CLIs** are the Agentic IDE's own registry
+(``jarvis.workspace.agents`` — Claude Code, Codex, OpenCode, Kimi Code, GLM
+Coding Plan, Grok Build, Antigravity, DeepSeek Harness), one row per entry
+that :mod:`jarvis.agent_chat.runner_cli` drives without a terminal. Each row
+names its registry key in ``agent``, and :func:`rows_for` drops a row whose
+entry the IDE no longer has, so the chat's picker and the IDE's pane picker
+offer the same CLIs (maintainer, 2026-08-27: the CLIs connected in the
+Agentic IDE, not the sub-agent missions' provider map — and every one of
+them drawn as a chat). The **API rows** are the provider families the
+API-Keys "Agents" section shows. Every row is listed 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:
@@ -15,12 +21,12 @@ Two kinds of runner sit behind the rows:
(: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``
+``claude-cli`` … ``dsh-cli`` — one runner per coding CLI (``runner_cli._PLANNERS``)
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".
+ ``opencode models``, Codex's ``models_cache.json``), else the curated
+ fallback here — and ``""`` means "the CLI's default".
``brain``
Jarvis' own harness — ``BrainManager.generate`` with a per-turn pick of
@@ -29,14 +35,21 @@ Two kinds of runner sit behind the rows:
the Jarvis surface (the front page's chat), where the typed turn is
Jarvis rather than a coding agent.
-``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 brain runner on the Jarvis surface). The route decides per request
-by probing; this module only carries the static shape.
+``claude-api`` is the one dual row: on a surface with CLI seats, a Claude
+subscription login makes the ``claude`` CLI run the session (Claude Code
+proper — tools, skills, the Max plan's included usage); otherwise the
+Anthropic API answers, through the API runner or the brain one. The route
+decides per request by probing; this module only carries the static shape.
+
+Not every row reaches every surface: a surface whose kit has no CLI seats
+(``SurfaceKit.cli_seats``, the front page's chat) is offered only the rows
+with a brain plugin behind them — :func:`rows_for` is the one place that
+narrowing happens, and it gates on the capability, never on a provider name
+(AP-21).
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
@@ -47,7 +60,18 @@ 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", "brain", "claude-cli", "codex-cli", "agy-cli", "grok-cli"]
+Runner = Literal[
+ "api",
+ "brain",
+ "claude-cli",
+ "codex-cli",
+ "agy-cli",
+ "grok-cli",
+ "opencode-cli",
+ "kimi-cli",
+ "glm-cli",
+ "dsh-cli",
+]
@dataclass(frozen=True, slots=True)
@@ -90,6 +114,12 @@ class ProviderRow:
#: True when the CLI runner supports resuming a conversation natively
#: (claude --resume, codex exec resume). Others get the transcript replayed.
native_resume: bool = False
+ #: The Agentic IDE's registry key for the CLI this row runs
+ #: (``jarvis.workspace.agents``) — ``""`` on an API row. The one link
+ #: between the chat's picker and the IDE's: :func:`rows_for` offers a CLI
+ #: row only while the IDE still has that entry, and the UI draws the row
+ #: with the same mark the IDE's pane picker uses.
+ agent: str = ""
def to_dict(self) -> dict[str, Any]:
return {
@@ -102,6 +132,7 @@ class ProviderRow:
"default_model": self.default_model,
"keyless": self.keyless,
"native_resume": self.native_resume,
+ "agent": self.agent,
"effort_levels": list(effort_levels(self.id)),
"default_effort": default_effort(self.id),
}
@@ -153,9 +184,9 @@ CODEX_FALLBACK_MODELS: Final[tuple[CuratedModel, ...]] = (
)
-# 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.
+# Order = the order the picker shows. The coding CLIs first, in the Agentic
+# IDE registry's own order (``jarvis.workspace.agents._AGENTS``) so the two
+# pickers read alike, then the API families, then the local servers.
PROVIDER_ROWS: Final[tuple[ProviderRow, ...]] = (
ProviderRow(
id="claude-api",
@@ -166,6 +197,7 @@ PROVIDER_ROWS: Final[tuple[ProviderRow, ...]] = (
curated_models=_curated("claude-api"),
default_model="",
native_resume=True,
+ agent="claude",
),
ProviderRow(
id="openai-codex",
@@ -178,6 +210,56 @@ PROVIDER_ROWS: Final[tuple[ProviderRow, ...]] = (
curated_models=CODEX_FALLBACK_MODELS,
default_model="",
native_resume=True,
+ agent="codex",
+ ),
+ ProviderRow(
+ id="opencode",
+ label="OpenCode",
+ family="opencode",
+ runner="opencode-cli",
+ models_source="curated",
+ # OpenCode's ids are ``provider/model`` and depend on which providers
+ # the person configured, so nothing is shipped: the route replaces
+ # this with the live ``opencode models`` list.
+ default_model="",
+ native_resume=True,
+ agent="opencode",
+ ),
+ ProviderRow(
+ id="kimi",
+ label="Kimi Code",
+ family="kimi",
+ runner="kimi-cli",
+ models_source="curated",
+ # Model aliases live in the person's own config.toml and the CLI
+ # publishes no list — the pick is whatever they named there.
+ default_model="",
+ native_resume=True,
+ agent="kimi",
+ ),
+ ProviderRow(
+ id="glm",
+ label="GLM Coding Plan",
+ family="glm",
+ runner="glm-cli",
+ models_source="curated",
+ # Claude Code against Z.ai's endpoint, which maps Claude Code's model
+ # aliases onto GLM models itself (``glm_spawn_env`` in
+ # ``jarvis.workspace.agents``); this app ships no list of Z.ai's ids
+ # on purpose — see ``_GLM_PICKS`` there.
+ default_model="",
+ native_resume=True,
+ agent="glm",
+ ),
+ ProviderRow(
+ id="grok-build",
+ label="Grok Build",
+ family="xai",
+ runner="grok-cli",
+ models_source="curated",
+ curated_models=_curated("grok"),
+ default_model="",
+ agent="grok-build",
),
ProviderRow(
id="antigravity",
@@ -192,15 +274,18 @@ PROVIDER_ROWS: Final[tuple[ProviderRow, ...]] = (
),
default_model="",
native_resume=True,
+ agent="antigravity",
),
ProviderRow(
- id="grok-build",
- label="Grok Build",
- family="xai",
- runner="grok-cli",
+ id="deepseek-harness",
+ label="DeepSeek Harness",
+ family="deepseek",
+ runner="dsh-cli",
models_source="curated",
- curated_models=_curated("grok"),
+ # The headless profile answers with its final message only — no
+ # model flag, no session to resume, no tool stream.
default_model="",
+ agent="deepseek-harness",
),
ProviderRow(id="openai", label="OpenAI", family="openai", runner="api", models_source="live"),
ProviderRow(
@@ -252,3 +337,78 @@ def provider_row(provider_id: str) -> ProviderRow | None:
def known_provider_ids() -> tuple[str, ...]:
return tuple(row.id for row in PROVIDER_ROWS)
+
+
+def rows_for(surface: str) -> tuple[ProviderRow, ...]:
+ """The rows ``surface`` may pick from.
+
+ A surface with CLI seats sees every API row and every CLI row whose entry
+ the Agentic IDE still registers — the registry is open, so the chat asks
+ it rather than assuming the table above is the whole truth. One without
+ CLI seats (the front page's chat) sees only the rows a brain plugin can
+ drive — the providers whose own API answers behind a key, so the turn
+ runs through Jarvis' harness and its model pick is one ``TurnOverride``
+ rather than a vendor process. Decided by asking the runner whether it can
+ drive the provider at all, never from a list of names (AP-21).
+ """
+ from jarvis.agent_chat.surface_kits import kit_for
+
+ if kit_for(surface).cli_seats:
+ return tuple(row for row in PROVIDER_ROWS if not row.agent or _ide_has(row.agent))
+ from jarvis.agent_chat.runner_api import supports_api_runner
+
+ return tuple(row for row in PROVIDER_ROWS if supports_api_runner(row.id))
+
+
+def cli_rows() -> tuple[ProviderRow, ...]:
+ """The rows that run a coding CLI — the chat's half of the IDE's registry."""
+ return tuple(row for row in PROVIDER_ROWS if row.agent)
+
+
+def _ide_has(agent: str) -> bool:
+ """Whether the Agentic IDE registers ``agent`` right now.
+
+ A registry that cannot be imported or asked (a stripped install, a broken
+ custom-CLI store) answers yes: the row then says what is wrong the moment
+ a turn tries to run, which beats a picker that silently lost a CLI.
+ """
+ try:
+ from jarvis.workspace.agents import get_agent
+
+ return get_agent(agent) is not None
+ except Exception: # noqa: BLE001 — see docstring
+ return True
+
+
+def offers(surface: str, provider_id: str) -> bool:
+ """Whether ``provider_id`` is one of ``surface``'s rows."""
+ pid = (provider_id or "").strip().lower()
+ return any(row.id == pid for row in rows_for(surface))
+
+
+#: A CLI-only row and the API row of the same brand. A chat that was seated
+#: on a vendor CLI before the front page dropped its CLI seats moves across
+#: this map instead of being stranded on a provider its picker no longer
+#: lists — same brand, same key page, now the provider's own endpoint.
+API_TWIN: Final[dict[str, str]] = {
+ "openai-codex": "openai",
+ "antigravity": "gemini",
+ "grok-build": "grok",
+}
+
+
+def api_seat(provider: str, model: str) -> tuple[str, str]:
+ """Where a CLI-seated ``(provider, model)`` lands on an API-only surface.
+
+ The provider moves to its API twin; the model is kept only when the
+ provider's own catalog knows it. A CLI's model ids are the CLI's own —
+ ``opusplan``, ``best``, ``claude-opus-5[1m]``, ``gpt-5.6-sol`` as Codex
+ spells it — and sending one to the provider's endpoint is an error, not
+ a near miss. An unknown id therefore becomes ``""``: the provider's
+ default, which the picker shows as "Default" and the person can change
+ in one click.
+ """
+ pid = (provider or "").strip().lower()
+ seat = API_TWIN.get(pid, pid)
+ known = {m.id for m in CURATED_MODELS.get(seat, ())}
+ return seat, (model if model in known else "")
diff --git a/jarvis/agent_chat/effort.py b/jarvis/agent_chat/effort.py
index de699c0ad6..5cfa28b4ca 100644
--- a/jarvis/agent_chat/effort.py
+++ b/jarvis/agent_chat/effort.py
@@ -35,9 +35,13 @@ ORDER: Final[tuple[str, ...]] = (
# "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.
+ # Anthropic low/medium/high/xhigh/max — one ladder for both runners.
+ # Claude Code takes it as ``--effort``; the API takes it as
+ # ``output_config.effort`` plus adaptive thinking on the models that
+ # have it (``_anthropic_base.reasoning_kwargs``, which snaps a level a
+ # model does not offer down to its nearest one). So the pick means the
+ # same thing on the front page's chat, where the API always answers, as
+ # it does on a Claude Code seat in the IDE'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
@@ -60,6 +64,15 @@ _LADDERS: Final[dict[str, tuple[tuple[str, ...], str]]] = {
# a model that reasons on its own alone.
"grok": (("", "low", "medium", "high", "xhigh"), ""),
"grok-build": (("", "low", "medium", "high"), ""),
+ # No knob to offer: OpenCode's ``--variant`` names are the model's own
+ # and differ per provider, Kimi sets effort in its config, GLM's endpoint
+ # takes no effort flag and the DeepSeek harness has none — so the pick
+ # disappears, exactly as it does on a pane of the same CLI
+ # (``jarvis.workspace.agents`` launch picks).
+ "opencode": (("",), ""),
+ "kimi": (("",), ""),
+ "glm": (("",), ""),
+ "deepseek-harness": (("",), ""),
"nvidia": (("", "none", "low", "medium", "high"), ""),
"ollama": (("", "none", "low", "medium", "high", "max"), ""),
"local-openai": (("", "none", "low", "medium", "high"), ""),
diff --git a/jarvis/agent_chat/permissions.py b/jarvis/agent_chat/permissions.py
index d8f107242e..7e5ca44534 100644
--- a/jarvis/agent_chat/permissions.py
+++ b/jarvis/agent_chat/permissions.py
@@ -6,7 +6,10 @@ 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
+switch, OpenCode's ``run`` has its own rules plus ``--auto`` and a read-only
+plan agent, Kimi's print mode is autonomous by design, the DeepSeek harness
+keeps its policy in its own settings, 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
@@ -164,6 +167,50 @@ _GROK: Final[tuple[PermissionMode, ...]] = (
),
)
+_OPENCODE: Final[tuple[PermissionMode, ...]] = (
+ PermissionMode(
+ "default",
+ "Ask before acting",
+ "OpenCode's own permission rules decide; a headless run cannot ask "
+ "back, so anything they would have asked about is declined and "
+ "reported to the model.",
+ ),
+ PermissionMode(
+ "plan",
+ "Plan",
+ "OpenCode's plan agent — read and plan only; nothing is changed.",
+ ),
+ PermissionMode(
+ "auto",
+ "Full access",
+ "Every permission OpenCode's rules do not deny outright is granted "
+ "without asking (`--auto`).",
+ ),
+)
+
+_KIMI: Final[tuple[PermissionMode, ...]] = (
+ PermissionMode(
+ "auto",
+ "Full access",
+ "Kimi's print mode runs fully autonomous: tools run without asking.",
+ ),
+ PermissionMode(
+ "plan",
+ "Plan",
+ "The agent is asked to investigate and answer with a plan instead of "
+ "acting. Kimi enforces nothing here — read the plan before building.",
+ ),
+)
+
+_DSH: Final[tuple[PermissionMode, ...]] = (
+ PermissionMode(
+ "auto",
+ "Harness policy",
+ "The headless profile never asks; DeepSeek Harness's own permission "
+ "policy, set in its own settings, decides what runs.",
+ ),
+)
+
_API: Final[tuple[PermissionMode, ...]] = (
PermissionMode(
"ask",
@@ -223,6 +270,12 @@ _LADDERS: Final[dict[str, tuple[tuple[PermissionMode, ...], str]]] = {
"codex-cli": (_CODEX, "auto"),
"agy-cli": (_AGY, "accept-edits"),
"grok-cli": (_GROK, "acceptEdits"),
+ "opencode-cli": (_OPENCODE, "default"),
+ "kimi-cli": (_KIMI, "auto"),
+ # GLM Coding Plan drives the Claude Code binary, so it takes Claude
+ # Code's own words.
+ "glm-cli": (_CLAUDE, "acceptEdits"),
+ "dsh-cli": (_DSH, "auto"),
"api": (_API, "ask"),
JARVIS_LADDER: (_JARVIS, "ask"),
}
@@ -254,7 +307,7 @@ def _stance(runner: str, mode: str) -> int:
# 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":
+ if runner in ("claude-cli", "glm-cli") and mode == "auto":
return _STANCE["auto_claude"]
return _STANCE.get(mode, 1)
diff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.py
index 8e1bbb361d..7748f67167 100644
--- a/jarvis/agent_chat/runner_cli.py
+++ b/jarvis/agent_chat/runner_cli.py
@@ -1,26 +1,44 @@
"""CLI-backed turns — a vendor agent binary drives the session.
-Four binaries, three wire shapes:
+Every coding CLI the Agentic IDE registers (``jarvis.workspace.agents``)
+has a planner here, so the chat's picker offers the same CLIs a pane does
+(maintainer, 2026-08-27: the CLIs connected in the Agentic IDE, and each
+one drawn as a chat, never as a terminal). Eight entries, six wire shapes:
-* **Claude-shaped NDJSON** — ``claude`` (Claude Code) and ``grok`` (Grok
+* **Claude-shaped NDJSON** — ``claude`` (Claude Code), ``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.
+ Messages wire shape on purpose) and GLM Coding Plan, which IS Claude Code
+ pointed at Z.ai's endpoint through the registry's environment factory.
+ 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.
+* **OpenCode NDJSON** — ``opencode run --format json`` with ``step_start`` /
+ ``text`` / ``reasoning`` / ``tool_use`` / ``step_finish`` / ``error``
+ lines, each wrapping one ``part`` of the session record and naming the
+ session on every line (verified against opencode 1.18.23).
+* **Kimi NDJSON** — ``kimi -p --output-format stream-json`` writes chat
+ messages by ``role``: an ``assistant`` line with its text and
+ ``tool_calls`` (OpenAI's function-call shape, arguments as a JSON string)
+ and a ``tool`` line per result. Nothing streams and nothing names the
+ session, so the id is found afterwards in Kimi's own session store
+ (``agentic_ide.agent_sessions``), the way a pane finds its own
+ (verified against kimi-code 0.29.2).
+* **Plain text** — ``dsh --profile headless`` (DeepSeek Harness) prints the
+ final message and exits: no tool stream, no session, one answer.
+
+Every CLI that keeps a conversation resumes it natively (``claude --resume``,
+``codex exec resume``, ``grok -r``, ``agy --conversation``, ``opencode run
+--session``, ``kimi --session``), 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,
@@ -37,6 +55,7 @@ import os
import shutil
import time
import uuid
+from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Final
@@ -62,7 +81,34 @@ class CliUnavailable(RuntimeError):
# ------------------------------------------------------------ binaries
+#: The binaries behind each CLI runner, in the order tried. One table for the
+#: planners below, the catalog route's "installed" flag and the workspace
+#: panes' launch picks — three readers of one fact, so a CLI added here is
+#: offerable everywhere at once.
+CLI_BINARIES: Final[dict[str, tuple[str, ...]]] = {
+ "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"),
+ "opencode-cli": ("opencode", "opencode.cmd", "opencode.exe"),
+ "kimi-cli": ("kimi", "kimi.cmd", "kimi.exe"),
+ # GLM Coding Plan IS Claude Code — Z.ai ships no binary of its own
+ # (``jarvis.workspace.agents``), so its seat stands on Claude Code's.
+ "glm-cli": ("claude", "claude.cmd", "claude.exe"),
+ "dsh-cli": ("dsh", "dsh.cmd", "dsh.exe"),
+}
+
+
def _which(*names: str) -> str | None:
+ # The well-known install dirs a GUI-launched process does not inherit
+ # (``~/.local/bin``, ``~/.grok/bin``, npm's prefix) — best-effort, and the
+ # same augmentation a pane runs before it resolves its CLI.
+ try:
+ from jarvis.core.path_augment import ensure_cli_paths
+
+ ensure_cli_paths()
+ except Exception: # noqa: BLE001, S110 — PATH augmentation is best-effort
+ pass
for name in names:
found = shutil.which(name)
if found:
@@ -70,8 +116,13 @@ def _which(*names: str) -> str | None:
return None
+def cli_installed(runner: str) -> bool:
+ """Whether ``runner``'s binary resolves from here (False for an unknown runner)."""
+ return _which(*CLI_BINARIES.get(runner, ())) is not None
+
+
def claude_argv_prefix() -> list[str]:
- binary = _which("claude", "claude.cmd", "claude.exe")
+ binary = _which(*CLI_BINARIES["claude-cli"])
if not binary:
raise CliUnavailable("Claude Code (claude) is not installed or not on PATH.")
from jarvis.claude_auth import claude_cli_argv_prefix
@@ -88,7 +139,7 @@ def codex_argv_prefix() -> list[str]:
prefix = []
if prefix:
return list(prefix)
- binary = _which("codex", "codex.cmd", "codex.exe")
+ binary = _which(*CLI_BINARIES["codex-cli"])
if not binary:
raise CliUnavailable("Codex CLI (codex) is not installed or not on PATH.")
return [binary]
@@ -103,19 +154,40 @@ def agy_argv_prefix() -> list[str]:
cli = None
if cli is not None and cli.kind == "agy":
return list(cli.argv_prefix)
- binary = _which("agy", "agy.exe")
+ binary = _which(*CLI_BINARIES["agy-cli"])
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")
+ binary = _which(*CLI_BINARIES["grok-cli"])
if not binary:
raise CliUnavailable("Grok Build (grok) is not installed or not on PATH.")
return [binary]
+def opencode_argv_prefix() -> list[str]:
+ binary = _which(*CLI_BINARIES["opencode-cli"])
+ if not binary:
+ raise CliUnavailable("OpenCode (opencode) is not installed or not on PATH.")
+ return [binary]
+
+
+def kimi_argv_prefix() -> list[str]:
+ binary = _which(*CLI_BINARIES["kimi-cli"])
+ if not binary:
+ raise CliUnavailable("Kimi Code (kimi) is not installed or not on PATH.")
+ return [binary]
+
+
+def dsh_argv_prefix() -> list[str]:
+ binary = _which(*CLI_BINARIES["dsh-cli"])
+ if not binary:
+ raise CliUnavailable("DeepSeek Harness (dsh) 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:
@@ -129,6 +201,45 @@ def _account_env(platform: str) -> dict[str, str]:
return env
+def _registry_env(agent: str, base: dict[str, str]) -> dict[str, str]:
+ """``base`` with the Agentic IDE registry's per-CLI environment on top.
+
+ The same overlay a pane of ``agent`` gets (``jarvis.agentic_ide.session.
+ agent_spawn_overlay``): the entry's fixed variables — an auto-updater
+ switched off so the binary is not swapped under a running turn — and, for
+ an entry whose environment is user configuration, its factory's answer.
+ A factory that answers ``None`` says the CLI is not configured (GLM
+ without a Z.ai key), and that stops the turn here rather than letting
+ Claude Code answer from — and bill — the wrong vendor. An empty value
+ removes the variable from the child, as it does for a pane.
+ """
+ env = dict(base)
+ env.setdefault("PYTHONIOENCODING", "utf-8")
+ try:
+ from jarvis.workspace import agents as workspace_agents
+
+ spec = workspace_agents.get_agent(agent)
+ except Exception: # noqa: BLE001 — no registry, no overlay
+ spec = None
+ if spec is None:
+ return env
+ overlay = dict(spec.spawn_env)
+ if spec.spawn_env_factory is not None:
+ resolved = spec.spawn_env_factory()
+ if resolved is None:
+ raise CliUnavailable(
+ f"{spec.display_name} is not configured yet — add its API key on "
+ "the API Keys page, then send again."
+ )
+ overlay.update(resolved)
+ for key, value in overlay.items():
+ if value:
+ env[key] = value
+ else:
+ env.pop(key, None)
+ return env
+
+
# ------------------------------------------------------------ argv per CLI
#: Prepended to the prompt for a runner without a plan mode of its own: the
@@ -146,7 +257,7 @@ class CliPlan:
argv: list[str]
env: dict[str, str]
stdin_text: str | None
- shape: str # "claude" | "codex" | "agy"
+ shape: str # a key of ``_SHAPES``: claude | codex | agy | opencode | kimi | text
#: 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
@@ -157,6 +268,10 @@ class CliPlan:
#: The control-protocol handshake, written before the prompt. Claude Code
#: only asks about tool calls once a client has announced itself this way.
control_init: str | None = None
+ #: For a CLI whose stream never names its session: called once the turn
+ #: is over with the working folder and the wall-clock start, and answers
+ #: the id the CLI's own store gave the conversation (or None).
+ discover: Callable[[Path, float], str | None] | None = None
def claude_control_init() -> str:
@@ -206,6 +321,62 @@ def plan_claude(
permission_mode: str,
resume: str | None,
identity: jarvis_harness.Identity | None = None,
+) -> CliPlan:
+ return _plan_claude_code(
+ prompt=prompt,
+ cwd=cwd,
+ model=model,
+ effort=effort,
+ permission_mode=permission_mode,
+ resume=resume,
+ identity=identity,
+ env=jarvis_harness.apply_env(_account_env("claude")),
+ )
+
+
+def plan_glm(
+ *,
+ prompt: str,
+ cwd: Path,
+ model: str,
+ effort: str,
+ permission_mode: str,
+ resume: str | None,
+ identity: jarvis_harness.Identity | None = None,
+) -> CliPlan:
+ """GLM Coding Plan: Claude Code's own plan, pointed at Z.ai by the registry.
+
+ Z.ai ships no CLI; its documentation says to run Anthropic's binary
+ against its endpoint, so everything — the control protocol that answers
+ permission prompts from the chat, ``--resume``, the MCP tools — is
+ inherited rather than re-implemented. Two things differ: the environment
+ is ``glm_spawn_env``'s (and its ``None`` refuses the turn instead of
+ letting Claude Code answer from, and bill, the wrong vendor), and no
+ ``--effort`` is sent, because that flag belongs to Anthropic's endpoint
+ (``_GLM_PICKS`` in ``jarvis.workspace.agents``).
+ """
+ return _plan_claude_code(
+ prompt=prompt,
+ cwd=cwd,
+ model=model,
+ effort="",
+ permission_mode=permission_mode,
+ resume=resume,
+ identity=identity,
+ env=jarvis_harness.apply_env(_registry_env("glm", dict(os.environ))),
+ )
+
+
+def _plan_claude_code(
+ *,
+ prompt: str,
+ cwd: Path,
+ model: str,
+ effort: str,
+ permission_mode: str,
+ resume: str | None,
+ identity: jarvis_harness.Identity | None,
+ env: dict[str, str],
) -> CliPlan:
mode = normalize_permission("claude-cli", permission_mode)
argv = [
@@ -249,7 +420,7 @@ def plan_claude(
argv += ["--session-id", sid]
return CliPlan(
argv,
- jarvis_harness.apply_env(_account_env("claude")),
+ env,
claude_stream_input(prompt),
"claude",
sid,
@@ -618,6 +789,158 @@ def plan_codex(
return CliPlan(argv, jarvis_harness.apply_env(_account_env("codex")), text, "codex", resume)
+_OPENCODE_CATALOG: dict[str, Any] = {"at": 0.0, "rows": None}
+_OPENCODE_CATALOG_TTL_S: Final[float] = 600.0
+
+
+def read_opencode_models(timeout_s: float = 20.0) -> list[dict[str, Any]]:
+ """``opencode models`` -> the ids this install can run (cached 10 min).
+
+ OpenCode's ids are ``provider/model`` and the list is whatever providers
+ the person configured — nothing to curate, only to ask. The label is the
+ model half and the note the provider, so ``anthropic/claude-opus-5`` and
+ ``cloudflare-ai-gateway/anthropic/claude-opus-5`` read apart in the picker.
+ Blocking (a ~2 s subprocess) — call it off the event loop. Any failure
+ yields an empty list, and the cache keeps a failure out of the next
+ request for the TTL too.
+ """
+ import subprocess
+
+ now = time.monotonic()
+ if (
+ _OPENCODE_CATALOG["rows"] is not None
+ and now - _OPENCODE_CATALOG["at"] < _OPENCODE_CATALOG_TTL_S
+ ):
+ return list(_OPENCODE_CATALOG["rows"])
+ rows: list[dict[str, Any]] = []
+ try:
+ argv = [*opencode_argv_prefix(), "models"]
+ env = _registry_env("opencode", dict(os.environ))
+ proc = subprocess.run( # noqa: S603 — fixed argv, no shell
+ argv,
+ capture_output=True,
+ timeout=timeout_s,
+ env=env,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ for line in proc.stdout.decode("utf-8", errors="replace").splitlines():
+ mid = line.strip()
+ if not mid or "/" not in mid or " " in mid:
+ continue
+ provider, _, model = mid.partition("/")
+ rows.append({"id": mid, "label": model, "note": provider})
+ except (CliUnavailable, OSError, ValueError, subprocess.SubprocessError) as exc:
+ log.debug("agent chat: opencode models unavailable: %s", exc)
+ _OPENCODE_CATALOG["rows"] = rows
+ _OPENCODE_CATALOG["at"] = now
+ return list(rows)
+
+
+def plan_opencode(
+ *,
+ prompt: str,
+ cwd: Path,
+ model: str,
+ effort: str,
+ permission_mode: str,
+ resume: str | None,
+ identity: jarvis_harness.Identity | None = None,
+) -> CliPlan:
+ mode = normalize_permission("opencode-cli", permission_mode)
+ # The prompt is a positional of ``run`` (no stdin mode), behind ``--`` so
+ # a sentence that starts with a dash is a sentence and not a flag; the
+ # identity rides in front of it on a fresh conversation.
+ prompt = _with_identity(prompt, identity, resume)
+ argv = [*opencode_argv_prefix(), "run", "--format", "json", "--thinking"]
+ if mode == "auto":
+ argv += ["--auto"]
+ elif mode == "plan":
+ # OpenCode's own plan agent: read-only by its definition.
+ argv += ["--agent", "plan"]
+ if model:
+ argv += ["--model", model]
+ if effort:
+ argv += ["--variant", effort]
+ if resume:
+ argv += ["--session", resume]
+ argv += ["--", prompt]
+ env = _registry_env("opencode", _account_env("opencode"))
+ return CliPlan(argv, env, None, "opencode", resume)
+
+
+def _kimi_session_after(cwd: Path, started_at: float) -> str | None:
+ """The session Kimi's print run in ``cwd`` created after ``started_at``.
+
+ Kimi's stream names no session; its store does. The same search a pane
+ runs for its own conversation — the newest session under this folder's
+ bucket, created after the start, with content — through
+ ``agent_sessions.discover``, so the two never disagree about where Kimi
+ keeps a conversation.
+ """
+ try:
+ from jarvis.agentic_ide import agent_sessions
+
+ handle = agent_sessions.discover("kimi", str(cwd), started_at)
+ except Exception as exc: # noqa: BLE001 — a lost id costs one resume, not the turn
+ log.debug("agent chat: kimi session discovery failed: %s", exc)
+ return None
+ return handle.id if handle is not None else None
+
+
+def plan_kimi(
+ *,
+ prompt: str,
+ cwd: Path,
+ model: str,
+ effort: str,
+ permission_mode: str,
+ resume: str | None,
+ identity: jarvis_harness.Identity | None = None,
+) -> CliPlan:
+ mode = normalize_permission("kimi-cli", permission_mode)
+ prompt = _with_identity(prompt, identity, resume)
+ argv = [*kimi_argv_prefix(), "--output-format", "stream-json"]
+ if model:
+ argv += ["--model", model]
+ # Print mode is autonomous by Kimi's own design (a headless run has nobody
+ # to ask); the flag only says so out loud. Plan is an instruction, not a
+ # sandbox — the ladder's sentence says as much.
+ if mode == "auto":
+ argv += ["--auto"]
+ if resume:
+ # Long form on purpose: the two Kimi generations disagree on the short
+ # flag (``agent_sessions``).
+ argv += ["--session", resume]
+ text = _PLAN_PREAMBLE + prompt if mode == "plan" else prompt
+ argv += ["--prompt", text]
+ env = _registry_env("kimi", _account_env("kimi"))
+ return CliPlan(
+ argv, env, None, "kimi", resume, discover=None if resume else _kimi_session_after
+ )
+
+
+def plan_dsh(
+ *,
+ prompt: str,
+ cwd: Path,
+ model: str,
+ effort: str,
+ permission_mode: str,
+ resume: str | None,
+ identity: jarvis_harness.Identity | None = None,
+) -> CliPlan:
+ """DeepSeek Harness's headless profile: one task in, the final message out.
+
+ No model flag, no session, no tool stream — the harness keeps its key and
+ its policy in its own settings (``jarvis.workspace.agents``). What comes
+ back is text, and the chat shows it as the answer.
+ """
+ prompt = _with_identity(prompt, identity, None, compact=True)
+ argv = [*dsh_argv_prefix(), "--profile", "headless", prompt]
+ env = _registry_env("deepseek-harness", _account_env("deepseek-harness"))
+ return CliPlan(argv, env, None, "text", None)
+
+
def _with_identity(
prompt: str,
identity: jarvis_harness.Identity | None,
@@ -643,8 +966,20 @@ _PLANNERS: Final[dict[str, Any]] = {
"grok-cli": plan_grok,
"agy-cli": plan_agy,
"codex-cli": plan_codex,
+ "opencode-cli": plan_opencode,
+ "kimi-cli": plan_kimi,
+ "glm-cli": plan_glm,
+ "dsh-cli": plan_dsh,
}
+#: Every runner this module drives — the catalog route's "is this a CLI
+#: seat" question, answered from the planners rather than a second list.
+CLI_RUNNERS: Final[frozenset[str]] = frozenset(_PLANNERS)
+
+#: The runners that are Claude Code under the hood, and so take its identity
+#: file and its control protocol.
+_CLAUDE_CODE_RUNNERS: Final[frozenset[str]] = frozenset({"claude-cli", "glm-cli"})
+
def supports_cli_runner(runner: str) -> bool:
return runner in _PLANNERS
@@ -924,7 +1259,17 @@ def translate_claude_line(obj: dict[str, Any], st: _ClaudeState) -> list[dict[st
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"):
+ for key in (
+ "command",
+ "file_path",
+ "filePath",
+ "target_file",
+ "path",
+ "pattern",
+ "query",
+ "url",
+ "description",
+ ):
val = args.get(key)
if isinstance(val, str) and val.strip():
return val.strip().splitlines()[0][:200]
@@ -1294,6 +1639,311 @@ def translate_agy_line(obj: dict[str, Any], st: _AgyState) -> list[dict[str, Any
return out
+# ------------------------------------------------------ opencode translation
+
+
+@dataclass(slots=True)
+class _OpenCodeState:
+ turn_id: str
+ vendor_session: str | None = None
+ status: str = "done"
+ error: str | None = None
+ usage: dict[str, int] = field(default_factory=dict)
+ cost_usd: float | None = None
+ emitted_text: bool = False
+ result_text: str = ""
+ #: callIDs already announced as tool rows
+ tool_calls: set[str] = field(default_factory=set)
+ started_at: dict[str, float] = field(default_factory=dict)
+
+
+#: ``step_finish.part.tokens`` -> the usage keys the timeline sums. OpenCode
+#: follows the OpenAI convention: ``input`` INCLUDES the cache read.
+_OPENCODE_TOKEN_KEYS: Final[tuple[tuple[str, str], ...]] = (
+ ("input", "input_tokens"),
+ ("output", "output_tokens"),
+ ("reasoning", "reasoning_output_tokens"),
+)
+
+
+def _part_duration_ms(part: dict[str, Any]) -> int | None:
+ span = part.get("time")
+ if not isinstance(span, dict):
+ return None
+ start, end = span.get("start"), span.get("end")
+ if isinstance(start, int | float) and isinstance(end, int | float) and end >= start:
+ return int(end - start)
+ return None
+
+
+def translate_opencode_line(obj: dict[str, Any], st: _OpenCodeState) -> list[dict[str, Any]]:
+ """One ``opencode run --format json`` object -> agent-chat events.
+
+ Shape (opencode 1.18.23): ``{"type", "timestamp", "sessionID", "part"}``
+ where ``type`` is ``step_start`` / ``text`` / ``reasoning`` / ``tool_use``
+ / ``step_finish``, and ``part`` is the session record's part of that
+ kind — a finished ``text`` part with its ``text``, a ``tool`` part with
+ ``tool``, ``callID`` and ``state{status, input, output, title, time}``,
+ a ``step-finish`` part with ``tokens{input, output, reasoning,
+ cache{read, write}}`` and ``cost``. An ``error`` line carries
+ ``error{name, data{message}}`` instead of a part.
+ """
+ out: list[dict[str, Any]] = []
+ kind = str(obj.get("type") or "")
+ sid = obj.get("sessionID")
+ if sid and not st.vendor_session:
+ st.vendor_session = str(sid)
+ part = obj.get("part") if isinstance(obj.get("part"), dict) else {}
+
+ if kind == "text":
+ text = str(part.get("text") or "")
+ mid = str(part.get("id") or part.get("messageID") or uuid.uuid4().hex)
+ if text.strip():
+ st.emitted_text = True
+ st.result_text = text
+ # An answer after a retryable error means the retry worked.
+ st.status, st.error = "done", None
+ out.append(
+ make_event(
+ "assistant_text",
+ {"turn_id": st.turn_id, "message_id": mid, "text": text},
+ )
+ )
+ return out
+
+ if kind == "reasoning":
+ text = str(part.get("text") or "")
+ mid = str(part.get("id") or part.get("messageID") or uuid.uuid4().hex)
+ if text.strip():
+ out.append(
+ make_event(
+ "reasoning",
+ {
+ "turn_id": st.turn_id,
+ "message_id": mid,
+ "text": text,
+ "duration_ms": _part_duration_ms(part),
+ },
+ )
+ )
+ return out
+
+ if kind == "tool_use":
+ name = str(part.get("tool") or "tool")
+ call_id = str(part.get("callID") or part.get("id") or uuid.uuid4().hex)
+ state = part.get("state") if isinstance(part.get("state"), dict) else {}
+ args = state.get("input") if isinstance(state.get("input"), dict) else {}
+ if call_id not in st.tool_calls:
+ st.tool_calls.add(call_id)
+ st.started_at[call_id] = time.perf_counter()
+ out.append(
+ make_event(
+ "tool_call",
+ {
+ "turn_id": st.turn_id,
+ "call_id": call_id,
+ "name": name,
+ "input": args,
+ "summary": _cli_tool_summary(name, args)
+ or str(state.get("title") or "")[:200],
+ },
+ )
+ )
+ status = str(state.get("status") or "")
+ if status in {"completed", "error"}:
+ is_error = status == "error"
+ output = str(state.get("output") or "")
+ err = state.get("error")
+ if is_error and err:
+ output = (output.rstrip() + ("\n" if output else "") + str(err)).strip()
+ started = st.started_at.get(call_id)
+ duration_ms = _part_duration_ms(state) or (
+ 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 ("failed" if is_error else "done"),
+ "is_error": is_error,
+ "duration_ms": duration_ms,
+ },
+ )
+ )
+ return out
+
+ if kind == "step_finish":
+ tokens = part.get("tokens") if isinstance(part.get("tokens"), dict) else {}
+ for theirs, ours in _OPENCODE_TOKEN_KEYS:
+ val = tokens.get(theirs)
+ if isinstance(val, int | float):
+ st.usage[ours] = st.usage.get(ours, 0) + int(val)
+ cache = tokens.get("cache") if isinstance(tokens.get("cache"), dict) else {}
+ for theirs, ours in (
+ ("read", "cached_input_tokens"),
+ ("write", "cache_write_input_tokens"),
+ ):
+ val = cache.get(theirs)
+ if isinstance(val, int | float):
+ st.usage[ours] = st.usage.get(ours, 0) + int(val)
+ cost = part.get("cost")
+ if isinstance(cost, int | float):
+ st.cost_usd = (st.cost_usd or 0.0) + float(cost)
+ if str(part.get("reason") or "") == "stop":
+ st.status, st.error = "done", None
+ return out
+
+ if kind == "error":
+ err = obj.get("error") if isinstance(obj.get("error"), dict) else {}
+ data = err.get("data") if isinstance(err.get("data"), dict) else {}
+ message = data.get("message") or err.get("message") or err.get("name") or "error"
+ # Terminal unless a later part shows the CLI retried and got through.
+ st.status = "error"
+ st.error = str(message)
+ return out
+
+ return out
+
+
+# ---------------------------------------------------------- kimi translation
+
+
+@dataclass(slots=True)
+class _KimiState:
+ 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 = ""
+ #: assistant lines seen — each is one message on the timeline
+ messages: int = 0
+ started_at: dict[str, float] = field(default_factory=dict)
+
+
+def _kimi_arguments(raw: Any) -> dict[str, Any]:
+ """The call's arguments as a dict — Kimi writes them as a JSON string."""
+ if isinstance(raw, dict):
+ return raw
+ if isinstance(raw, str) and raw.strip():
+ try:
+ parsed = json.loads(raw)
+ except ValueError:
+ return {"arguments": raw}
+ return parsed if isinstance(parsed, dict) else {"arguments": parsed}
+ return {}
+
+
+def translate_kimi_line(obj: dict[str, Any], st: _KimiState) -> list[dict[str, Any]]:
+ """One ``kimi --output-format stream-json`` object -> agent-chat events.
+
+ Shape (kimi-code 0.29.2, ``PromptJsonWriter``): chat messages by
+ ``role``. ``assistant`` carries ``content`` (the step's whole text) and
+ ``tool_calls`` — OpenAI's function-call shape, ``function.arguments`` a
+ JSON string; ``tool`` carries ``tool_call_id`` and ``content``; ``meta``
+ lines (``turn.step.retrying``) and a goal's ``goal.summary`` are noise.
+ """
+ out: list[dict[str, Any]] = []
+ role = str(obj.get("role") or "")
+
+ if role == "assistant":
+ st.messages += 1
+ mid = f"kimi-{st.messages}"
+ content = obj.get("content")
+ if isinstance(content, str) and content.strip():
+ st.emitted_text = True
+ st.result_text = content
+ out.append(
+ make_event(
+ "assistant_text",
+ {"turn_id": st.turn_id, "message_id": mid, "text": content},
+ )
+ )
+ calls = obj.get("tool_calls") if isinstance(obj.get("tool_calls"), list) else []
+ for call in calls:
+ if not isinstance(call, dict):
+ continue
+ fn = call.get("function") if isinstance(call.get("function"), dict) else {}
+ name = str(fn.get("name") or "tool")
+ args = _kimi_arguments(fn.get("arguments"))
+ call_id = str(call.get("id") or uuid.uuid4().hex)
+ st.started_at[call_id] = time.perf_counter()
+ out.append(
+ make_event(
+ "tool_call",
+ {
+ "turn_id": st.turn_id,
+ "call_id": call_id,
+ "name": name,
+ "input": args,
+ "summary": _cli_tool_summary(name, args),
+ },
+ )
+ )
+ return out
+
+ if role == "tool":
+ call_id = str(obj.get("tool_call_id") or "")
+ content = obj.get("content")
+ output = content if isinstance(content, str) else json.dumps(content, ensure_ascii=False)
+ started = st.started_at.get(call_id)
+ out.append(
+ make_event(
+ "tool_result",
+ {
+ "turn_id": st.turn_id,
+ "call_id": call_id,
+ "output": output,
+ # Kimi's record does not say; a failure reads in the text.
+ "is_error": False,
+ "duration_ms": int((time.perf_counter() - started) * 1000) if started else None,
+ },
+ )
+ )
+ return out
+
+ return out
+
+
+# ---------------------------------------------------------- plain-text shape
+
+
+@dataclass(slots=True)
+class _TextState:
+ """A CLI that prints its answer and nothing else — every line is the answer."""
+
+ 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 = ""
+
+
+def _translate_nothing(obj: dict[str, Any], st: Any) -> list[dict[str, Any]]:
+ return []
+
+
+#: shape -> (a fresh state for a turn, the line translator). The pump below
+#: knows nothing about any CLI: it decodes a line, hands it here, and emits
+#: what comes back. A new wire shape is one row.
+_SHAPES: Final[dict[str, tuple[Callable[[str, str | None], Any], Callable[..., Any]]]] = {
+ "claude": (lambda tid, vs: _ClaudeState(turn_id=tid, vendor_session=vs), translate_claude_line),
+ "codex": (lambda tid, vs: _CodexState(turn_id=tid, vendor_session=vs), translate_codex_line),
+ "agy": (lambda tid, vs: _AgyState(turn_id=tid, vendor_session=vs), translate_agy_line),
+ "opencode": (
+ lambda tid, vs: _OpenCodeState(turn_id=tid, vendor_session=vs),
+ translate_opencode_line,
+ ),
+ "kimi": (lambda tid, vs: _KimiState(turn_id=tid, vendor_session=vs), translate_kimi_line),
+ "text": (lambda tid, vs: _TextState(turn_id=tid, vendor_session=vs), _translate_nothing),
+}
+
+
# ------------------------------------------------------------ the turn
@@ -1358,7 +2008,7 @@ async def run_cli_turn(
user_text=user_text,
history=handle.history,
resume=resume,
- with_file=(runner == "claude-cli"),
+ with_file=(runner in _CLAUDE_CODE_RUNNERS),
)
if bridge is not None:
from jarvis.agent_chat.approval_bridge import ChatGrant
@@ -1397,7 +2047,7 @@ async def run_cli_turn(
user_text=user_text,
history=handle.history,
resume=None,
- with_file=(runner == "claude-cli"),
+ with_file=(runner in _CLAUDE_CODE_RUNNERS),
)
outcome = await _run_cli_once(
handle, user_text, runner, None, identity=ident, bridge=bridge
@@ -1458,6 +2108,7 @@ async def _run_cli_once(
vendor_session = plan.vendor_session
log.info("agent chat %s: %s argv=%s", handle.turn_id, runner, plan.argv[:6])
+ started_at = time.time()
try:
proc = await asyncio.create_subprocess_exec(
*plan.argv,
@@ -1474,9 +2125,13 @@ async def _run_cli_once(
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)
+ make_state, translate = _SHAPES[plan.shape]
+ state: Any = make_state(handle.turn_id, vendor_session)
+ # Lines that are not the CLI's JSON — a banner, a warning, the whole
+ # answer of a plain-text CLI — shown as they come, and kept as the answer
+ # of last resort when the stream said nothing else.
+ plain: list[str] = []
+ plain_id = f"plain-{handle.turn_id}"
stderr_tail: list[str] = []
async def _drain_stderr() -> None:
@@ -1490,6 +2145,15 @@ async def _run_cli_once(
stderr_tail.append(text)
del stderr_tail[:-40]
+ async def _say_plain(line: str) -> None:
+ plain.append(line + "\n")
+ await handle.emit(
+ make_event(
+ "text_delta",
+ {"turn_id": handle.turn_id, "message_id": plain_id, "text": line + "\n"},
+ )
+ )
+
async def _pump_stdout() -> None:
assert proc.stdout is not None
while True:
@@ -1499,31 +2163,17 @@ async def _run_cli_once(
line = raw.decode("utf-8", errors="replace").strip()
if not line:
continue
+ if plan.shape == "text":
+ await _say_plain(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"
- )
+ await _say_plain(line)
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 plan.control_init is not None:
if obj.get("type") == "control_request":
await _answer_control_request(obj)
continue
@@ -1531,10 +2181,9 @@ async def _run_cli_once(
# The CLI's answer to our handshake (its command list).
# Nothing the timeline shows, and not a line to translate.
continue
- events = translate_claude_line(obj, claude_state)
- for ev in events:
+ for ev in translate(obj, state):
await handle.emit(ev)
- if plan.keep_stdin and claude_state.saw_result:
+ if plan.keep_stdin and getattr(state, "saw_result", False):
# The turn is over; closing stdin lets the CLI exit.
_close_stdin()
@@ -1573,8 +2222,9 @@ async def _run_cli_once(
)
# 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)
+ announced: set[str] = getattr(state, "emitted_tool_ids", set())
+ if tool_name == "ExitPlanMode" and call_id not in announced:
+ announced.add(call_id)
await handle.emit(
make_event(
"tool_call",
@@ -1654,72 +2304,46 @@ async def _run_cli_once(
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
+ if state.status == "error":
+ status, error_text = "error", state.error
elif proc.returncode not in (0, None):
status = "error"
error_text = (
- st_error
- or getattr(shape_state, "last_error", None)
+ state.error
+ or getattr(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,
- },
- )
+ usage = dict(state.usage)
+ cost_usd = getattr(state, "cost_usd", None)
+ vendor_session = state.vendor_session or vendor_session
+ if vendor_session is None and plan.discover is not None and status == "done":
+ # A CLI that never said which conversation it opened: ask its store.
+ vendor_session = await asyncio.to_thread(plan.discover, cwd, started_at)
+ result_text = str(getattr(state, "result_text", "") or "")
+ plain_tail = "".join(plain)
+ if not state.emitted_text and result_text.strip():
+ await handle.emit(
+ make_event(
+ "assistant_text",
+ {
+ "turn_id": handle.turn_id,
+ "message_id": f"result-{handle.turn_id}",
+ "text": result_text,
+ },
)
- if not emitted_text and plain_tail.strip():
+ )
+ elif not state.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}",
+ "message_id": plain_id,
"text": plain_tail.strip(),
},
)
diff --git a/jarvis/agent_chat/typeahead.py b/jarvis/agent_chat/typeahead.py
index 23ee1cef3f..96429bee98 100644
--- a/jarvis/agent_chat/typeahead.py
+++ b/jarvis/agent_chat/typeahead.py
@@ -56,13 +56,23 @@ SKILL_REF: Final[str] = "$"
#: runner id -> the trigger characters that seat honours (see module doc).
TRIGGERS_BY_RUNNER: Final[dict[str, tuple[str, ...]]] = {
"claude-cli": (SLASH, MENTION),
+ # Claude Code under Z.ai's endpoint: the same commands and agents.
+ "glm-cli": (SLASH, MENTION),
"codex-cli": (MENTION, SKILL_REF),
"agy-cli": (MENTION,),
"grok-cli": (MENTION,),
+ "opencode-cli": (MENTION,),
+ "kimi-cli": (MENTION,),
+ # One task in, one answer out — nothing to complete against.
+ "dsh-cli": (),
"api": (MENTION,),
"brain": (SLASH,),
}
+#: The runners that read Claude Code's ``.claude/agents`` — Claude Code, and
+#: the launch profile that IS Claude Code (GLM Coding Plan).
+_CLAUDE_SHAPED: Final[frozenset[str]] = frozenset({"claude-cli", "glm-cli"})
+
#: Group ids the composer turns into headings (i18n keys ``agent_chat.typeahead_group_*``).
GROUP_PROJECT: Final[str] = "project"
GROUP_ACCOUNT: Final[str] = "account"
@@ -138,7 +148,7 @@ def suggest(
elif trigger == SKILL_REF:
rows = _filter_definitions(codex_skills(folder), q)
else:
- rows = claude_agents(folder) if runner == "claude-cli" else []
+ rows = claude_agents(folder) if runner in _CLAUDE_SHAPED else []
rows = _filter_definitions(rows, q) if q else rows
rows = rows + file_suggestions(folder, q, limit=limit)
truncated = len(rows) > limit
diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.py
index 18d8b2fde3..4ed0c0adb0 100644
--- a/jarvis/ui/web/agent_chat_routes.py
+++ b/jarvis/ui/web/agent_chat_routes.py
@@ -19,8 +19,6 @@ Prefix ``/api/agent-chat``:
GET /check-folder?path= does the folder exist / is it a directory
GET /typeahead?trigger=&surface=&provider=&cwd=&q=
what the composer lists after "/", "@" or "$"
- GET /typeahead?trigger=&surface=&provider=&cwd=&q=
- what the composer lists after "/", "@" or "$"
The service lives on ``app.state.agent_chat`` (built in ``server.py``); a
missing service answers 503 like every other optional subsystem.
@@ -50,7 +48,7 @@ from fastapi import (
from pydantic import BaseModel, Field
from jarvis.agent_chat import attachments as chat_attachments
-from jarvis.agent_chat import typeahead
+from jarvis.agent_chat import runner_cli, typeahead
from jarvis.agent_chat.catalog import CLAUDE_CODE_MODELS, offers, rows_for
from jarvis.agent_chat.effort import normalize_effort
from jarvis.agent_chat.events import make_event
@@ -164,15 +162,9 @@ def _ws_service(ws: WebSocket) -> AgentChatService | None:
def _cli_installed(runner: str) -> bool:
- import shutil
+ from jarvis.agent_chat.runner_cli import cli_installed
- 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)
+ return cli_installed(runner)
async def _live_cli_models() -> dict[str, list[dict[str, Any]]]:
@@ -333,11 +325,27 @@ _health_cache: dict[str, tuple[float, list[ProviderHealthRow]]] = {}
#: so the API-Keys one-token probe is the wrong check: the dual Claude row
#: is catalogued as ``claude-api``, and that probe hits Anthropic's endpoint
#: and paints "Key rejected" on a Claude Code seat that is signed in.
-_CLI_RUNNERS: Final[frozenset[str]] = frozenset({"claude-cli", "codex-cli", "agy-cli", "grok-cli"})
+_CLI_RUNNERS: Final[frozenset[str]] = runner_cli.CLI_RUNNERS
def _cli_auth_status(runner: str) -> Any | None:
- """The vendor CLI's own login snapshot. ``None`` if ``runner`` is not a CLI."""
+ """The vendor CLI's own login snapshot. ``None`` if ``runner`` is not a CLI
+ this app can read the login of (OpenCode, Kimi and the DeepSeek harness
+ keep theirs where no reader has been verified — see the registry)."""
+ if runner == "glm-cli":
+ # GLM Coding Plan is Claude Code plus a Z.ai key: the key IS the login.
+ from types import SimpleNamespace
+
+ from jarvis.workspace.agents import glm_spawn_env
+
+ configured = glm_spawn_env() is not None
+ return SimpleNamespace(
+ connected=configured,
+ mode="subscription",
+ message="GLM Coding Plan: Z.ai key saved"
+ if configured
+ else "GLM Coding Plan: no Z.ai key — add one under API Keys",
+ )
if runner == "claude-cli":
from jarvis.claude_auth import ClaudeAuthService
@@ -394,7 +402,10 @@ def _cli_login_snapshot(runner: str) -> tuple[str, str, str]:
f"The check itself failed ({type(exc).__name__})",
)
if st is None:
- return "unknown", "unknown_provider", f"{runner}: not a CLI seat"
+ # The CLI keeps its own login and this app has no verified reader for
+ # it: no dot rather than a guessed one (the turn itself says if the
+ # CLI is signed out).
+ return "unknown", "self_managed", f"{runner}: keeps its own login"
connected = _cli_subscription_connected(runner, st)
detail = (getattr(st, "message", None) or "").strip() or (
f"{runner}: signed in" if connected else f"{runner}: not signed in"
diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
index be93e9525e..7b14253a0c 100644
--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
@@ -26,7 +26,11 @@ export interface AgentChatProvider {
label: string;
/** Brand family for ProviderLogo. */
family: string;
- /** "api" | "claude-cli" | "codex-cli" | "agy-cli" | "grok-cli" — resolved for this machine. */
+ /**
+ * Which runner answers on this machine: "api" / "brain", or a vendor CLI —
+ * "claude-cli" | "codex-cli" | "agy-cli" | "grok-cli" | "opencode-cli" |
+ * "kimi-cli" | "glm-cli" | "dsh-cli" (jarvis/agent_chat/runner_cli.py).
+ */
runner: string;
models_source: "live" | "curated";
curated_models: CuratedModel[];
@@ -42,6 +46,13 @@ export interface AgentChatProvider {
default_permission_mode: string;
/** null for the API runner; else whether the vendor binary is on PATH. */
cli_installed: boolean | null;
+ /**
+ * The Agentic IDE's registry key for the CLI this row runs ("claude",
+ * "opencode", "glm", …) — "" on an API row, absent on an older backend.
+ * The mark the row wears is that entry's (`AgentMark`), so the chat's
+ * picker and the IDE's pane picker draw one CLI the same way.
+ */
+ agent?: string;
/**
* The characters that open the composer's typeahead on this seat — a
* subset of "/", "@", "$" decided by the runner (jarvis/agent_chat/typeahead.py).
diff --git a/jarvis/ui/web/frontend/src/store/agentChat.test.ts b/jarvis/ui/web/frontend/src/store/agentChat.test.ts
index 5c14501e6f..497a861f1b 100644
--- a/jarvis/ui/web/frontend/src/store/agentChat.test.ts
+++ b/jarvis/ui/web/frontend/src/store/agentChat.test.ts
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AgentChatSession } from "@/lib/agentChatApi";
+import { providerKind } from "@/components/agentchat/AgentComposer";
import { createAgentChatStore, draftKey } from "@/store/agentChat";
/**
@@ -135,6 +136,87 @@ describe("agent-chat store surfaces", () => {
vi.unstubAllGlobals();
});
+ it("counts a brain seat as connected only when an API KEY is saved", () => {
+ // The Agents tab calls a Claude Code login "connected" — right for a row
+ // a CLI runs. On the front page's chat the same row is the Anthropic
+ // endpoint, where that login buys nothing, so it must read as unconnected
+ // until a key is there.
+ const row = (runner: string, keyless = false) => ({
+ id: "claude-api",
+ label: "Anthropic Claude",
+ family: "claude",
+ runner,
+ models_source: "live" as const,
+ curated_models: [],
+ default_model: "",
+ keyless,
+ native_resume: true,
+ effort_levels: ["low", "high"],
+ default_effort: "high",
+ permission_modes: [{ id: "ask", label: "ask", description: "" }],
+ default_permission_mode: "ask",
+ cli_installed: null,
+ });
+ const seat = (runner: string, conn: Record<string, unknown>) => {
+ const store = createAgentChatStore("jarvis");
+ store.setState({
+ catalog: { providers: [row(runner)], default_cwd: "C:\work", shell: "pwsh" },
+ connections: [{ jarvis: "claude-api", is_active_brain: false, ...conn }],
+ } as never);
+ return store.getState().providerOptions()[0].connected;
+ };
+ const subscriptionOnly = { key_set: true, api_key_set: false, oauth_connected: true };
+ expect(seat("brain", subscriptionOnly)).toBe(false);
+ expect(seat("api", subscriptionOnly)).toBe(false);
+ // The CLI seat itself is exactly what that login is for.
+ expect(seat("claude-cli", subscriptionOnly)).toBe(true);
+ expect(seat("brain", { key_set: true, api_key_set: true })).toBe(true);
+ // A backend too old to report the finer field still answers as before.
+ expect(seat("brain", { key_set: true })).toBe(true);
+ });
+
+ it("counts a coding CLI the Agents tab has no card for as connected once installed", () => {
+ // OpenCode, Kimi, GLM Coding Plan and the DeepSeek harness keep their own
+ // login; the Agents tab has no card for them, and "no card" must not read
+ // as "not connected" — installed is what this app can know. The row also
+ // wears the IDE's mark for that CLI, so both pickers draw it alike.
+ const row = (cli_installed: boolean) => ({
+ id: "opencode",
+ label: "OpenCode",
+ family: "opencode",
+ runner: "opencode-cli",
+ models_source: "curated" as const,
+ curated_models: [],
+ default_model: "",
+ keyless: false,
+ native_resume: true,
+ effort_levels: [""],
+ default_effort: "",
+ permission_modes: [{ id: "auto", label: "auto", description: "" }],
+ default_permission_mode: "auto",
+ cli_installed,
+ agent: "opencode",
+ });
+ const seat = (cli_installed: boolean) => {
+ const store = createAgentChatStore("agent");
+ store.setState({
+ catalog: { providers: [row(cli_installed)], default_cwd: "C:\\work", shell: "pwsh" },
+ connections: [],
+ } as never);
+ return store.getState().providerOptions()[0];
+ };
+ expect(seat(true).connected).toBe(true);
+ expect(seat(true).agentMark).toBe("opencode");
+ expect(seat(false).connected).toBe(false);
+ });
+
+ it("groups a brain seat with the API keys, never with the CLIs", () => {
+ expect(providerKind({ runner: "brain", keyless: false })).toBe("api");
+ expect(providerKind({ runner: "api", keyless: false })).toBe("api");
+ expect(providerKind({ runner: "claude-cli", keyless: false })).toBe("cli");
+ expect(providerKind({ runner: "brain", keyless: true })).toBe("local");
+ });
+
it("names the front page's draft key as it always was, and gives the IDE its own", () => {
expect(draftKey("jarvis")).toBe("jarvis.agentChat.draft.v2");
expect(draftKey("agent")).toBe("jarvis.agentChat.draft.agent.v1");
diff --git a/jarvis/ui/web/frontend/src/store/agentChat.ts b/jarvis/ui/web/frontend/src/store/agentChat.ts
index b10ea83bd9..ee366a4cf5 100644
--- a/jarvis/ui/web/frontend/src/store/agentChat.ts
+++ b/jarvis/ui/web/frontend/src/store/agentChat.ts
@@ -442,16 +442,25 @@ export function createAgentChatStore(surface: AgentChatSurface) {
// CLI runs — but the brain runner calls the provider's endpoint,
// where a Claude Code login buys nothing. `key_set` stands in when
// an older backend does not report the finer field.
+ // A coding CLI the Agents tab has no card for — OpenCode, Kimi,
+ // GLM Coding Plan, the DeepSeek harness — keeps its own login where
+ // this app has no verified reader; installed is all it can know,
+ // and the live sweep says the rest.
const credentialed = p.keyless
? true
: isApiRunner(p.runner)
? Boolean(row?.api_key_set ?? row?.key_set)
- : Boolean(row?.key_set);
+ : row
+ ? Boolean(row.key_set)
+ : true;
const installed = p.cli_installed === null ? true : p.cli_installed;
return {
...p,
connected: credentialed && installed,
active: Boolean(row?.is_active_brain),
+ // The IDE's mark for the CLI behind a CLI row; an API row keeps
+ // its provider-family logo.
+ agentMark: p.agent || undefined,
};
});
},
diff --git a/jarvis/ui/web/frontend/src/store/paneChat.test.ts b/jarvis/ui/web/frontend/src/store/paneChat.test.ts
index 5ffc298ed7..d0685db658 100644
--- a/jarvis/ui/web/frontend/src/store/paneChat.test.ts
+++ b/jarvis/ui/web/frontend/src/store/paneChat.test.ts
@@ -150,6 +150,23 @@ describe("providerForAgent", () => {
expect(providerForAgent("codex", [CLAUDE_CLI])).toBeNull();
expect(providerForAgent("", [CLAUDE_CLI])).toBeNull();
});
+
+ it("matches on the row's registry key, which a runner name cannot spell", () => {
+ // GLM Coding Plan runs the Claude binary and the DeepSeek harness runs
+ // `dsh`: neither runner name is the agent's, so the row says whose it is.
+ const glm = { ...CLAUDE_CLI, id: "glm", runner: "glm-cli", agent: "glm" } as ProviderOption;
+ const dsh = {
+ ...CLAUDE_CLI,
+ id: "deepseek-harness",
+ runner: "dsh-cli",
+ agent: "deepseek-harness",
+ } as ProviderOption;
+ expect(providerForAgent("glm", [CLAUDE_CLI, glm, dsh])?.id).toBe("glm");
+ expect(providerForAgent("deepseek-harness", [CLAUDE_CLI, glm, dsh])?.id).toBe(
+ "deepseek-harness",
+ );
+ expect(providerForAgent("claude", [glm, CLAUDE_CLI])?.id).toBe("claude-api");
+ });
});
describe("createPaneChatStore", () => {
diff --git a/jarvis/ui/web/frontend/src/store/paneChat.ts b/jarvis/ui/web/frontend/src/store/paneChat.ts
index 2c6cb0c6ab..155d89615a 100644
--- a/jarvis/ui/web/frontend/src/store/paneChat.ts
+++ b/jarvis/ui/web/frontend/src/store/paneChat.ts
@@ -91,10 +91,12 @@ export function eventsSignature(events: AgentChatEvent[], live: boolean): string
/**
* Which catalog provider a pane's CLI is.
*
- * By the RUNNER, not by a table of names: the catalog's CLI rows name the
- * binary they run (`claude-cli`, `codex-cli`, `agy-cli`, `grok-cli`), and a
- * pane names its agent the same way (`claude`, `codex`, `agy`, `grok`). A CLI
- * added later matches on the same rule.
+ * By the row's registry key first: a catalog CLI row names the Agentic IDE
+ * entry it runs (`agent`), which is exactly what a pane calls its agent. The
+ * runner rule stays for an older backend that does not send it — the catalog's
+ * CLI rows name the binary they run (`claude-cli`, `codex-cli`, `agy-cli`,
+ * `grok-cli`), and a pane names its agent the same way (`claude`, `codex`,
+ * `agy`, `grok`). A CLI added later matches on either.
*/
export function providerForAgent(
agent: string,
@@ -105,7 +107,9 @@ export function providerForAgent(
const aliases = key === "antigravity" ? ["agy", "antigravity"] : [key];
return (
providers.find((p) =>
- aliases.some((a) => p.runner === `${a}-cli` || p.runner === a || p.id === a),
+ aliases.some(
+ (a) => p.agent === a || p.runner === `${a}-cli` || p.runner === a || p.id === a,
+ ),
) ?? null
);
}
diff --git a/jarvis/workspace/launch_picks.py b/jarvis/workspace/launch_picks.py
index 16c5f3620a..493127a56a 100644
--- a/jarvis/workspace/launch_picks.py
+++ b/jarvis/workspace/launch_picks.py
@@ -226,10 +226,10 @@ def normalize_model(agent: str, model: str | None) -> str:
async def live_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 ten minutes in
- the runner module); Codex keeps ``models_cache.json`` in its home. Both are
- read off the event loop, and a failure simply leaves the curated fallback
- standing.
+ ``agy`` answers ``agy models`` and OpenCode ``opencode models`` (each a
+ ~2 s subprocess, cached ten minutes in the runner module); Codex keeps
+ ``models_cache.json`` in its home. All are read off the event loop, and a
+ failure simply leaves the curated fallback standing.
One reader for both surfaces on purpose: the chat composer and a workspace
pane offer the same CLI, so a list either of them read alone would be a
@@ -238,7 +238,11 @@ async def live_models() -> dict[str, list[dict[str, Any]]]:
"""
import asyncio
- from jarvis.agent_chat.runner_cli import read_agy_models, read_codex_models
+ from jarvis.agent_chat.runner_cli import (
+ read_agy_models,
+ read_codex_models,
+ read_opencode_models,
+ )
out: dict[str, list[dict[str, Any]]] = {}
if _installed("agy-cli"):
@@ -254,20 +258,23 @@ async def live_models() -> dict[str, list[dict[str, Any]]]:
rows = None
if rows:
out["codex-cli"] = rows
+ if _installed("opencode-cli"):
+ # ``opencode models`` — the providers this install configured.
+ try:
+ rows = await asyncio.wait_for(asyncio.to_thread(read_opencode_models), 25.0)
+ except Exception as exc: # noqa: BLE001 — no list is an empty picker, not an error
+ _log.debug("launch picks: opencode model list unavailable: %s", exc)
+ rows = []
+ if rows:
+ out["opencode-cli"] = rows
return out
def _installed(runner: str) -> bool:
"""Is the binary behind ``runner`` resolvable from here?"""
- 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(name) for name in names)
+ from jarvis.agent_chat.runner_cli import cli_installed
+
+ return cli_installed(runner)
def runner_of(agent: str) -> str:
diff --git a/tests/unit/agent_chat/test_ide_cli_seats.py b/tests/unit/agent_chat/test_ide_cli_seats.py
new file mode 100644
index 0000000000..b621478b60
--- /dev/null
+++ b/tests/unit/agent_chat/test_ide_cli_seats.py
@@ -0,0 +1,586 @@
+"""The Agentic IDE's coding CLIs are the chat's coding CLIs — every one, as a chat.
+
+Binds the chat catalog (``jarvis.agent_chat.catalog``) to the IDE's registry
+(``jarvis.workspace.agents``) and to the planners that drive each CLI without
+a terminal (``jarvis.agent_chat.runner_cli``), and pins the wire shapes of the
+CLIs that joined on 2026-08-27 — OpenCode, Kimi Code, GLM Coding Plan, DeepSeek
+Harness — against lines captured from the installed binaries.
+
+The drift this guards against is the quiet kind: a CLI the IDE offers as a
+pane and the chat does not, or a chat seat whose turn falls back to "No runner
+for provider" — both are a picker that lies.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.agent_chat import catalog, effort, permissions, typeahead
+from jarvis.agent_chat import runner_cli as rc
+from jarvis.agent_chat.runner_api import TurnHandle
+from jarvis.agent_chat.store import AgentChatSession
+from jarvis.workspace import agents as workspace_agents
+
+# ------------------------------------------------------------------ parity
+
+
+def _ide_coding_clis() -> list[str]:
+ """The registry's built-in coding CLIs, in the registry's own order."""
+ return [
+ name
+ for name in workspace_agents.builtin_names()
+ if (entry := workspace_agents.get_agent(name)) is not None and entry.is_coding_agent
+ ]
+
+
+def test_every_ide_coding_cli_has_a_chat_seat_with_a_planner() -> None:
+ """Registry vs. catalog vs. planners.
+
+ A CLI the IDE opens as a pane must be a row in the chat's picker, and that
+ row's runner must be one the CLI runner can actually drive — otherwise the
+ seat exists and every turn on it ends in "No runner for provider".
+ """
+ rows = {row.agent: row for row in catalog.cli_rows()}
+ for name in _ide_coding_clis():
+ assert name in rows, f"{name} is a pane in the IDE but not a seat in the chat"
+ assert rc.supports_cli_runner(rows[name].runner), name
+ assert rows[name].runner in rc.CLI_BINARIES, name
+
+
+def test_every_chat_cli_seat_names_a_registered_ide_entry_in_the_ide_order() -> None:
+ for row in catalog.cli_rows():
+ assert workspace_agents.get_agent(row.agent) is not None, row.id
+ # The same order in both pickers, so a person finds one CLI in one place.
+ assert [row.agent for row in catalog.cli_rows()] == _ide_coding_clis()
+
+
+def test_the_agent_surface_offers_every_cli_seat_and_the_front_page_none() -> None:
+ agent_ids = {row.id for row in catalog.rows_for("agent")}
+ jarvis_ids = {row.id for row in catalog.rows_for("jarvis")}
+ for row in catalog.cli_rows():
+ assert row.id in agent_ids, row.id
+ # The dual Claude row is the Anthropic API on the front page; every
+ # other CLI seat has no API twin there and stays out.
+ if row.id != "claude-api":
+ assert row.id not in jarvis_ids, row.id
+
+
+def test_a_cli_the_ide_dropped_leaves_the_picker(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(catalog, "_ide_has", lambda agent: agent != "kimi")
+ ids = [row.id for row in catalog.rows_for("agent")]
+ assert "kimi" not in ids
+ assert "opencode" in ids and "openai" in ids
+
+
+def test_resolve_runner_names_each_clis_own_runner() -> None:
+ from jarvis.agent_chat.service import resolve_runner
+
+ assert resolve_runner("opencode") == "opencode-cli"
+ assert resolve_runner("kimi") == "kimi-cli"
+ assert resolve_runner("glm") == "glm-cli"
+ assert resolve_runner("deepseek-harness") == "dsh-cli"
+ for pid in ("opencode", "kimi", "glm", "deepseek-harness"):
+ assert resolve_runner(pid, surface="jarvis") == "unknown"
+
+
+def test_the_row_dict_carries_the_registry_key() -> None:
+ opencode = catalog.provider_row("opencode")
+ openai = catalog.provider_row("openai")
+ assert opencode is not None and opencode.to_dict()["agent"] == "opencode"
+ assert openai is not None and openai.to_dict()["agent"] == ""
+
+
+# ----------------------------------------------------------------- ladders
+
+
+def test_every_cli_runner_has_a_permission_ladder_and_a_typeahead_answer() -> None:
+ for runner in rc.CLI_RUNNERS:
+ assert permissions.permission_modes(runner), runner
+ assert permissions.default_permission(runner) in permissions.permission_ids(runner)
+ assert isinstance(typeahead.triggers_for(runner), tuple)
+ # GLM Coding Plan IS Claude Code: same words, same commands after "/".
+ assert permissions.permission_modes("glm-cli") == permissions.permission_modes("claude-cli")
+ assert typeahead.triggers_for("glm-cli") == typeahead.triggers_for("claude-cli")
+ assert typeahead.triggers_for("dsh-cli") == ()
+
+
+ ("runner", "picked", "expected"),
+ [
+ ("opencode-cli", "bypassPermissions", "auto"),
+ ("opencode-cli", "plan", "plan"),
+ ("opencode-cli", "acceptEdits", "default"),
+ ("kimi-cli", "ask", "auto"),
+ ("kimi-cli", "plan", "plan"),
+ ("dsh-cli", "plan", "auto"),
+ ("glm-cli", "bypass", "bypassPermissions"),
+ ],
+)
+def test_a_mode_from_another_ladder_folds_onto_the_new_clis(
+ runner: str, picked: str, expected: str
+) -> None:
+ assert permissions.normalize_permission(runner, picked) == expected
+
+
+def test_the_new_clis_offer_no_effort_knob() -> None:
+ for provider in ("opencode", "kimi", "glm", "deepseek-harness"):
+ assert effort.effort_levels(provider) == ("",)
+ assert effort.default_effort(provider) == ""
+ assert effort.normalize_effort(provider, "high") == ""
+
+
+# ------------------------------------------------------------ opencode wire
+
+# Captured from ``opencode run --format json`` (opencode 1.18.23), trimmed.
+_OC_TEXT = {
+ "type": "text",
+ "timestamp": 1787847908825,
+ "sessionID": "ses_1",
+ "part": {
+ "id": "prt_t",
+ "messageID": "msg_1",
+ "sessionID": "ses_1",
+ "type": "text",
+ "text": "pong",
+ "time": {"start": 1787847908734, "end": 1787847908810},
+ },
+}
+_OC_REASONING = {
+ "type": "reasoning",
+ "timestamp": 1787849182569,
+ "sessionID": "ses_1",
+ "part": {
+ "id": "prt_r",
+ "messageID": "msg_1",
+ "type": "reasoning",
+ "text": "The user wants exactly one word.",
+ "time": {"start": 1787849182500, "end": 1787849182560},
+ },
+}
+_OC_TOOL = {
+ "type": "tool_use",
+ "timestamp": 1787848055718,
+ "sessionID": "ses_1",
+ "part": {
+ "type": "tool",
+ "tool": "read",
+ "callID": "call_1",
+ "state": {
+ "status": "completed",
+ "input": {"filePath": "C:\\w\\note.txt"},
+ "output": "<content>\n1: hello\n</content>",
+ "title": "w\\note.txt",
+ "time": {"start": 1787848055697, "end": 1787848055715},
+ },
+ "id": "prt_x",
+ "sessionID": "ses_1",
+ "messageID": "msg_1",
+ },
+}
+_OC_FINISH = {
+ "type": "step_finish",
+ "timestamp": 1787847908825,
+ "sessionID": "ses_1",
+ "part": {
+ "id": "prt_f",
+ "reason": "stop",
+ "messageID": "msg_1",
+ "type": "step-finish",
+ "tokens": {
+ "total": 21445,
+ "input": 19649,
+ "output": 4,
+ "reasoning": 0,
+ "cache": {"write": 0, "read": 1792},
+ },
+ "cost": 0.0125,
+ },
+}
+_OC_ERROR = {
+ "type": "error",
+ "timestamp": 1787848313951,
+ "sessionID": "ses_1",
+ "error": {
+ "name": "APIError",
+ "data": {"message": "Upstream request failed: Endpoint is unavailable.", "statusCode": 503},
+ },
+}
+
+
+def _kinds(events: list[dict]) -> list[str]:
+ return [e["kind"] for e in events]
+
+
+def test_opencode_lines_become_text_reasoning_tool_rows_and_usage() -> None:
+ st = rc._OpenCodeState(turn_id="t")
+ events = rc.translate_opencode_line(_OC_REASONING, st)
+ assert _kinds(events) == ["reasoning"]
+ assert events[0]["payload"]["text"].startswith("The user wants")
+ assert events[0]["payload"]["duration_ms"] == 60
+
+ events = rc.translate_opencode_line(_OC_TOOL, st)
+ assert _kinds(events) == ["tool_call", "tool_result"]
+ call, result = events[0]["payload"], events[1]["payload"]
+ assert call["name"] == "read" and call["call_id"] == "call_1"
+ assert call["summary"] == "C:\\w\\note.txt"
+ assert result["call_id"] == "call_1" and not result["is_error"]
+ assert "hello" in result["output"] and result["duration_ms"] == 18
+ # The same part reported again (a later status) is one row, not two.
+ assert _kinds(rc.translate_opencode_line(_OC_TOOL, st)) == ["tool_result"]
+
+ events = rc.translate_opencode_line(_OC_TEXT, st)
+ assert _kinds(events) == ["assistant_text"]
+ assert events[0]["payload"]["text"] == "pong"
+ assert st.emitted_text and st.vendor_session == "ses_1"
+
+ assert rc.translate_opencode_line(_OC_FINISH, st) == []
+ assert st.usage == {
+ "input_tokens": 19649,
+ "output_tokens": 4,
+ "reasoning_output_tokens": 0,
+ "cached_input_tokens": 1792,
+ "cache_write_input_tokens": 0,
+ }
+ assert st.cost_usd == pytest.approx(0.0125)
+ assert st.status == "done"
+
+
+def test_an_opencode_error_ends_the_turn_unless_the_retry_answered() -> None:
+ st = rc._OpenCodeState(turn_id="t")
+ assert rc.translate_opencode_line(_OC_ERROR, st) == []
+ assert st.status == "error" and "Endpoint is unavailable" in (st.error or "")
+ # A retry that got through: the answer wins over the error before it.
+ rc.translate_opencode_line(_OC_TEXT, st)
+ assert st.status == "done" and st.error is None
+
+
+# ---------------------------------------------------------------- kimi wire
+
+# The shape ``PromptJsonWriter`` writes (kimi-code 0.29.2).
+_KIMI_STEP = {
+ "role": "assistant",
+ "content": "Let me read it.",
+ "tool_calls": [
+ {
+ "type": "function",
+ "id": "call_a",
+ "function": {"name": "ReadFile", "arguments": '{"path": "note.txt"}'},
+ }
+ ],
+}
+_KIMI_RESULT = {"role": "tool", "tool_call_id": "call_a", "content": "hello"}
+_KIMI_META = {"role": "meta", "type": "turn.step.retrying", "failed_attempt": 1}
+_KIMI_FINAL = {"role": "assistant", "content": "It says hello."}
+
+
+def test_kimi_lines_become_messages_and_tool_rows() -> None:
+ st = rc._KimiState(turn_id="t")
+ events = rc.translate_kimi_line(_KIMI_STEP, st)
+ assert _kinds(events) == ["assistant_text", "tool_call"]
+ assert events[0]["payload"]["text"] == "Let me read it."
+ call = events[1]["payload"]
+ assert call["name"] == "ReadFile" and call["call_id"] == "call_a"
+ # Arguments arrive as a JSON string and are handed on as the dict they are.
+ assert call["input"] == {"path": "note.txt"} and call["summary"] == "note.txt"
+
+ events = rc.translate_kimi_line(_KIMI_RESULT, st)
+ assert _kinds(events) == ["tool_result"]
+ assert events[0]["payload"]["call_id"] == "call_a"
+ assert events[0]["payload"]["output"] == "hello"
+
+ assert rc.translate_kimi_line(_KIMI_META, st) == []
+ events = rc.translate_kimi_line(_KIMI_FINAL, st)
+ assert _kinds(events) == ["assistant_text"]
+ # Each assistant line is its own message on the timeline.
+ assert events[0]["payload"]["message_id"] != "kimi-1"
+ assert st.result_text == "It says hello." and st.emitted_text
+
+
+def test_kimi_arguments_that_are_not_json_are_kept_rather_than_dropped() -> None:
+ assert rc._kimi_arguments("not json") == {"arguments": "not json"}
+ assert rc._kimi_arguments('["a"]') == {"arguments": ["a"]}
+ assert rc._kimi_arguments({"x": 1}) == {"x": 1}
+ assert rc._kimi_arguments(None) == {}
+
+
+# ---------------------------------------------------------------- planners
+
+
+def stubbed(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(rc, "opencode_argv_prefix", lambda: ["opencode"])
+ monkeypatch.setattr(rc, "kimi_argv_prefix", lambda: ["kimi"])
+ monkeypatch.setattr(rc, "dsh_argv_prefix", lambda: ["dsh"])
+ monkeypatch.setattr(rc, "claude_argv_prefix", lambda: ["claude"])
+ monkeypatch.setattr(rc, "_account_env", lambda platform: {"HOME": "h"})
+ monkeypatch.setattr(rc, "_registry_env", lambda agent, base: {**base, "AGENT": agent})
+ monkeypatch.setattr(rc.jarvis_harness, "mcp_config_json", lambda sid=None: None)
+
+
+def test_plan_opencode_speaks_run_json_and_the_stance_flags(stubbed: None) -> None:
+ plan = rc.plan_opencode(
+ prompt="-- fix it",
+ cwd=Path("."),
+ model="anthropic/claude-opus-5",
+ effort="",
+ permission_mode="auto",
+ resume=None,
+ )
+ assert plan.argv[:5] == ["opencode", "run", "--format", "json", "--thinking"]
+ assert "--auto" in plan.argv
+ # A sentence that starts with a dash is a sentence: it rides behind ``--``.
+ assert plan.argv[-2:] == ["--", "-- fix it"]
+ assert plan.argv[plan.argv.index("--model") + 1] == "anthropic/claude-opus-5"
+ assert plan.shape == "opencode" and plan.env["AGENT"] == "opencode"
+ assert plan.stdin_text is None and plan.vendor_session is None
+
+ plan = rc.plan_opencode(
+ prompt="p", cwd=Path("."), model="", effort="", permission_mode="plan", resume="ses_9"
+ )
+ assert plan.argv[plan.argv.index("--agent") + 1] == "plan"
+ assert plan.argv[plan.argv.index("--session") + 1] == "ses_9"
+ assert "--auto" not in plan.argv and plan.vendor_session == "ses_9"
+
+ plan = rc.plan_opencode(
+ prompt="p", cwd=Path("."), model="", effort="", permission_mode="default", resume=None
+ )
+ assert "--auto" not in plan.argv and "--agent" not in plan.argv
+
+
+def test_plan_kimi_prints_json_and_finds_its_session_afterwards(stubbed: None) -> None:
+ plan = rc.plan_kimi(
+ prompt="hi", cwd=Path("."), model="k2", effort="", permission_mode="auto", resume=None
+ )
+ assert plan.argv[:3] == ["kimi", "--output-format", "stream-json"]
+ assert plan.argv[plan.argv.index("--model") + 1] == "k2"
+ assert "--auto" in plan.argv
+ assert plan.argv[-2:] == ["--prompt", "hi"]
+ assert plan.shape == "kimi" and plan.env["AGENT"] == "kimi"
+ # Fresh conversation: the id is looked up in Kimi's store afterwards.
+ assert plan.discover is rc._kimi_session_after
+
+ plan = rc.plan_kimi(
+ prompt="hi", cwd=Path("."), model="", effort="", permission_mode="plan", resume="session_1"
+ )
+ assert plan.argv[plan.argv.index("--session") + 1] == "session_1"
+ assert plan.argv[-1].startswith("PLAN MODE:") and plan.argv[-1].endswith("hi")
+ assert plan.discover is None and plan.vendor_session == "session_1"
+
+
+def test_plan_dsh_is_one_task_in_plain_text(stubbed: None) -> None:
+ plan = rc.plan_dsh(
+ prompt="run the tests", cwd=Path("."), model="", effort="", permission_mode="", resume=None
+ )
+ assert plan.argv == ["dsh", "--profile", "headless", "run the tests"]
+ assert plan.shape == "text" and plan.vendor_session is None
+ assert plan.env["AGENT"] == "deepseek-harness"
+
+
+def test_plan_glm_is_claude_codes_plan_on_zais_environment(stubbed: None) -> None:
+ plan = rc.plan_glm(
+ prompt="hi",
+ cwd=Path("."),
+ model="opus",
+ effort="high",
+ permission_mode="acceptEdits",
+ resume=None,
+ )
+ assert plan.argv[0] == "claude" and plan.shape == "claude"
+ assert plan.argv[plan.argv.index("--permission-mode") + 1] == "acceptEdits"
+ assert plan.argv[plan.argv.index("--model") + 1] == "opus"
+ # The effort flag belongs to Anthropic's endpoint, not Z.ai's.
+ assert "--effort" not in plan.argv
+ assert plan.keep_stdin and plan.control_init is not None
+ assert plan.env["AGENT"] == "glm"
+
+
+def test_registry_env_applies_the_panes_overlay_and_refuses_an_unconfigured_cli(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ configured = SimpleNamespace(
+ display_name="GLM Coding Plan",
+ spawn_env=(("KEEP", "1"),),
+ spawn_env_factory=lambda: {"ANTHROPIC_BASE_URL": "https://z", "ANTHROPIC_API_KEY": ""},
+ )
+ monkeypatch.setattr(workspace_agents, "get_agent", lambda name: configured)
+ env = rc._registry_env("glm", {"ANTHROPIC_API_KEY": "host-key", "PATH": "p"})
+ assert env["KEEP"] == "1" and env["ANTHROPIC_BASE_URL"] == "https://z"
+ # An empty value REMOVES the variable — the host's key must not outrank
+ # the token the endpoint is given.
+ assert "ANTHROPIC_API_KEY" not in env and env["PATH"] == "p"
+
+ unconfigured = SimpleNamespace(
+ display_name="GLM Coding Plan", spawn_env=(), spawn_env_factory=lambda: None
+ )
+ monkeypatch.setattr(workspace_agents, "get_agent", lambda name: unconfigured)
+ with pytest.raises(rc.CliUnavailable, match="GLM Coding Plan is not configured"):
+ rc._registry_env("glm", {})
+
+ monkeypatch.setattr(workspace_agents, "get_agent", lambda name: None)
+ assert rc._registry_env("nobody", {"A": "b"})["A"] == "b"
+
+
+def test_opencode_models_reads_provider_slash_model_lines(monkeypatch: pytest.MonkeyPatch) -> None:
+ import subprocess
+
+ out = (
+ b"opencode/big-pickle\n"
+ b"anthropic/claude-opus-5\n"
+ b"cloudflare-ai-gateway/anthropic/claude-opus-5\n"
+ b"\n"
+ b"not a model\n"
+ )
+ monkeypatch.setattr(rc, "opencode_argv_prefix", lambda: ["opencode"])
+ monkeypatch.setattr(rc, "_registry_env", lambda agent, base: base)
+ monkeypatch.setattr(
+ subprocess, "run", lambda *a, **k: SimpleNamespace(stdout=out, returncode=0)
+ )
+ rc._OPENCODE_CATALOG["rows"] = None
+ rows = rc.read_opencode_models()
+ assert rows == [
+ {"id": "opencode/big-pickle", "label": "big-pickle", "note": "opencode"},
+ {"id": "anthropic/claude-opus-5", "label": "claude-opus-5", "note": "anthropic"},
+ {
+ "id": "cloudflare-ai-gateway/anthropic/claude-opus-5",
+ "label": "anthropic/claude-opus-5",
+ "note": "cloudflare-ai-gateway",
+ },
+ ]
+ rc._OPENCODE_CATALOG["rows"] = None
+
+
+# ------------------------------------------------------------------ the pump
+
+
+def _fake_cli(lines: list[dict | str], exit_code: int = 0) -> list[str]:
+ """argv for a process that prints ``lines`` (dicts as JSON) and exits."""
+ body = "import sys\n"
+ for line in lines:
+ text = json.dumps(line) if isinstance(line, dict) else line
+ body += f"sys.stdout.write({json.dumps(text)} + chr(10))\n"
+ body += f"sys.exit({exit_code})\n"
+ return [sys.executable, "-c", body]
+
+
+def _turn(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ runner: str,
+ plan: rc.CliPlan,
+ provider: str,
+) -> tuple[str | None, list[dict]]:
+ monkeypatch.setitem(rc._PLANNERS, runner, lambda **kw: plan)
+ events: list[dict] = []
+
+ async def emit(ev: dict) -> None:
+ events.append(ev)
+
+ async def ask(*_: object) -> str:
+ return "deny"
+
+ session = AgentChatSession(
+ session_id="s1",
+ title="",
+ provider=provider,
+ model="",
+ effort="",
+ cwd=str(tmp_path),
+ permission_mode="",
+ vendor_session=None,
+ created_ms=0,
+ updated_ms=0,
+ message_count=0,
+ preview="",
+ )
+ handle = TurnHandle(
+ session=session, turn_id="t1", emit=emit, request_approval=ask, cancel=asyncio.Event()
+ )
+ vendor = asyncio.run(rc.run_cli_turn(handle, "hi", runner))
+ return vendor, events
+
+
+def test_an_opencode_turn_runs_through_the_shared_pump(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ plan = rc.CliPlan(
+ _fake_cli([_OC_REASONING, _OC_TOOL, _OC_TEXT, _OC_FINISH]),
+ dict(os.environ),
+ None,
+ "opencode",
+ None,
+ )
+ vendor, events = _turn(monkeypatch, tmp_path, "opencode-cli", plan, "opencode")
+ assert vendor == "ses_1"
+ assert _kinds(events) == [
+ "reasoning",
+ "tool_call",
+ "tool_result",
+ "assistant_text",
+ "turn_finished",
+ ]
+ finished = events[-1]["payload"]
+ assert finished["status"] == "done" and finished["error"] is None
+ assert finished["usage"]["input_tokens"] == 19649
+ assert finished["cost_usd"] == pytest.approx(0.0125)
+
+
+def test_a_plain_text_cli_is_shown_as_it_prints_and_kept_as_the_answer(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ plan = rc.CliPlan(
+ _fake_cli(["pong", "and a second line"]), dict(os.environ), None, "text", None
+ )
+ vendor, events = _turn(monkeypatch, tmp_path, "dsh-cli", plan, "deepseek-harness")
+ assert vendor is None
+ assert _kinds(events) == ["text_delta", "text_delta", "assistant_text", "turn_finished"]
+ assert events[2]["payload"]["text"] == "pong\nand a second line"
+ assert events[2]["payload"]["message_id"] == events[0]["payload"]["message_id"]
+ assert events[-1]["payload"]["status"] == "done"
+
+
+def test_a_kimi_turn_discovers_its_session_once_the_cli_has_exited(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ seen: list[tuple[Path, float]] = []
+
+ def discover(cwd: Path, started_at: float) -> str | None:
+ seen.append((cwd, started_at))
+ return "session_abc"
+
+ plan = rc.CliPlan(
+ _fake_cli([_KIMI_STEP, _KIMI_RESULT, _KIMI_FINAL]),
+ dict(os.environ),
+ None,
+ "kimi",
+ None,
+ discover=discover,
+ )
+ vendor, events = _turn(monkeypatch, tmp_path, "kimi-cli", plan, "kimi")
+ assert vendor == "session_abc"
+ assert seen and seen[0][0] == tmp_path
+ assert _kinds(events) == [
+ "assistant_text",
+ "tool_call",
+ "tool_result",
+ "assistant_text",
+ "turn_finished",
+ ]
+ assert events[-1]["payload"]["status"] == "done"
+
+
+def test_a_cli_that_dies_silently_reports_its_exit_code(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ plan = rc.CliPlan(_fake_cli([], exit_code=3), dict(os.environ), None, "opencode", None)
+ vendor, events = _turn(monkeypatch, tmp_path, "opencode-cli", plan, "opencode")
+ assert vendor is None
+ assert _kinds(events) == ["turn_finished"]
+ finished = events[-1]["payload"]
+ assert finished["status"] == "error" and "exited with code 3" in finished["error"]