Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agent-chat): adopt the Jarvis MCP harness — Jarvis' tools offered to a chat's CLI seat
rubenluetke10-beep48cc2dfa9851
diff --git a/jarvis/agent_chat/jarvis_harness.py b/jarvis/agent_chat/jarvis_harness.pynew file mode 100644index 0000000000..0bbfa9dc43--- /dev/null+++ b/jarvis/agent_chat/jarvis_harness.py@@ -0,0 +1,167 @@+"""What makes the chat session Jarvis rather than a coding agent in a folder.++Two things are handed to the spawned CLI:++* an **MCP config** pointing at this app's own tool server+ (``jarvis.ui.web.mcp_server_routes``), so the model's hands are Jarvis' hands+ — the same catalog the voice path calls, through the same safety gateway;+* a **system preamble** that tells it who it is and when to reach for those+ tools instead of a shell command.++Why this shape and not "Jarvis' brain drives the turn": the person pays for+these turns through a *subscription* (Claude Code, Codex, …), and a+subscription only pays for the CLI's own agent loop. Driving the loop from+Jarvis' brain would bill per token against an API key instead. So the CLI keeps+the wheel and Jarvis lends it the hands — the model works INSIDE the Jarvis+harness while the seat stays the person's own.++This surface is deliberately additive: a CLI that cannot mount MCP servers, or+an app whose tool gateway is not up yet, simply runs as it did before. Nothing+here is allowed to make a turn fail.+"""++from __future__ import annotations++import json+import logging+from typing import Final++log = logging.getLogger(__name__)++#: Where the tool server is mounted on the app's own web server. The trailing+#: slash is load-bearing: a mounted ASGI app owns ``<prefix>/…``, and the app+#: has other routes that match the slash-less form first — a CLI pointed at it+#: gets 405, fails to connect, and the chat silently falls back to being an+#: ordinary coding session (the exact symptom, live 2026-08-24).+_MCP_PATH: Final[str] = "/api/control/mcp/"++#: The server name the CLI shows to the model. Claude Code exposes the tools as+#: ``mcp__jarvis__<tool>``; the preamble below names that prefix, so the two+#: must stay in step.+_SERVER_NAME: Final[str] = "jarvis"++SYSTEM_PREAMBLE: Final[str] = (+ "You are Jarvis — the assistant of the person you are talking to, running as "+ "the chat surface of the Personal Jarvis desktop app that is open in front of "+ "them right now. This chat is the same assistant they otherwise talk to by "+ "voice; the only difference is that here they type, and here you are expected "+ "to think longer and go deeper.\n\n"+ "You have Jarvis' own tools, offered to you over MCP under the "+ "`mcp__jarvis__` prefix. They act on the RUNNING app and on the accounts the "+ "person has connected to it — their calendar, mail, contacts, media, wiki, "+ "windows, screen, skills and Jarvis' own settings. Prefer them over a shell "+ "command, a CLI you would have to authenticate yourself, a skill, or the "+ "browser whenever the request is about the person's own apps, data or "+ "machine: those tools are already signed in and already permitted. Reach for "+ "your file and shell tools for code and for the filesystem.\n\n"+ "Some of those tools ask the person for approval before they run. That is "+ "normal and it is not a failure — wait for the answer rather than routing "+ "around it.\n\n"+ "Do not spawn background workers or sub-agents: for this turn, you are the "+ "worker."+)+++#: The child environment variable the control key travels in — the SAME name+#: the app itself reads it from (``jarvis.core.control_key.ENV_VAR``), so one+#: secret has one name. It never goes on the command line: argv is readable by+#: every process on the machine, and this key is the Control API's whole+#: security boundary.+KEY_ENV_VAR: Final[str] = "JARVIS_CONTROL_API_KEY"+++def endpoint() -> str | None:+ """This app's own MCP URL, or ``None`` before the web server bound."""+ from jarvis.core import runtime_refs++ base = runtime_refs.get_api_base_url()+ return f"{base.rstrip('/')}{_MCP_PATH}" if base else None+++def control_key() -> str | None:+ from jarvis.core import control_key as ck++ return ck.get_control_key()+++def mcp_config_json() -> str | None:+ """The Claude-shaped ``mcpServers`` config, or ``None`` when unavailable.++ ``None`` whenever anything is missing — the web server has not bound yet,+ there is no control key, the gateway is still coming up. The caller then+ spawns the CLI exactly as before instead of handing it a config that would+ fail to connect and cost the turn a confusing error.+ """+ try:+ url = endpoint()+ if not url or not control_key():+ return None+ return json.dumps(+ {+ "mcpServers": {+ _SERVER_NAME: {+ "type": "http",+ "url": url,+ # Expanded by the CLI from the child env — see KEY_ENV_VAR.+ "headers": {"Authorization": f"Bearer ${{{KEY_ENV_VAR}}}"},+ }+ }+ },+ ensure_ascii=False,+ )+ except Exception: # noqa: BLE001 — no Jarvis tools is a degraded chat, never a broken one+ log.warning("agent chat: could not build the Jarvis MCP config", exc_info=True)+ return None+++def codex_config_args() -> list[str]:+ """``-c`` overrides that mount the tool server in ``codex exec``.++ Codex speaks streamable HTTP MCP with a bearer token read from an+ environment variable (``codex mcp add --url --bearer-token-env-var``),+ which is the same shape used here — no config file is written, so a chat+ turn never edits the person's own ``~/.codex/config.toml``.+ """+ try:+ url = endpoint()+ if not url or not control_key():+ return []+ return [+ "-c",+ f'mcp_servers.{_SERVER_NAME}.url="{url}"',+ "-c",+ f'mcp_servers.{_SERVER_NAME}.bearer_token_env_var="{KEY_ENV_VAR}"',+ ]+ except Exception: # noqa: BLE001 — see mcp_config_json+ log.warning("agent chat: could not build the Codex MCP overrides", exc_info=True)+ return []+++def apply_env(env: dict[str, str]) -> dict[str, str]:+ """Put the control key into a child environment, if there is one to give."""+ key = control_key()+ if key:+ env[KEY_ENV_VAR] = key+ return env+++def tool_count() -> int:+ """How many Jarvis tools the chat would currently be offered (0 = none)."""+ try:+ from jarvis.mcp.jarvis_tools_server import offered_tools++ return len(offered_tools())+ except Exception: # noqa: BLE001 — a count is a nicety, never a failure+ return 0+++__all__ = [+ "KEY_ENV_VAR",+ "SYSTEM_PREAMBLE",+ "apply_env",+ "codex_config_args",+ "control_key",+ "endpoint",+ "mcp_config_json",+ "tool_count",+]diff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.pyindex fca18e741b..13f365c301 100644--- a/jarvis/agent_chat/runner_cli.py+++ b/jarvis/agent_chat/runner_cli.py@@ -18,12 +18,9 @@ Every CLI resumes its own conversation natively (``claude --resume``,row keeps the vendor's id in ``vendor_session`` and a later turn continuesthe same conversation — the tools, skills, MCP servers and permissions arethe CLI's own, exactly as in a terminal. The person's permission mode maps-onto the closest stance each CLI offers. Claude Code really does ask: the-control-protocol handshake below opens a channel on stdin, and its prompts-arrive as ``can_use_tool`` for the chat's approval card to answer. The-others cannot ask in print mode, so there ``ask`` means "edits yes, anything-riskier is declined by the CLI and reported to the model", and ``auto``-bypasses.+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 stdinwhere the binary accepts it, ``NO_WINDOW_CREATIONFLAGS``, UTF-8 decoding,@@ -44,6 +41,7 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Final+from jarvis.agent_chat import jarvis_harnessfrom jarvis.agent_chat.effort import normalize_effort, snap_to_ladderfrom jarvis.agent_chat.events import make_eventfrom jarvis.agent_chat.permissions import normalize_permission@@ -223,6 +221,17 @@ def plan_claude(argv += ["--model", model]if effort:argv += ["--effort", effort]+ # Jarvis' own tools, and the identity that says when to use them. Both are+ # skipped when the app cannot offer them (no control key, server not bound+ # yet) — the session then behaves exactly as it did before.+ mcp_config = jarvis_harness.mcp_config_json()+ if mcp_config:+ argv += [+ "--mcp-config",+ mcp_config,+ "--append-system-prompt",+ jarvis_harness.SYSTEM_PREAMBLE,+ ]if resume:argv += ["--resume", resume]sid = resume@@ -231,7 +240,7 @@ def plan_claude(argv += ["--session-id", sid]return CliPlan(argv,- _account_env("claude"),+ jarvis_harness.apply_env(_account_env("claude")),claude_stream_input(prompt),"claude",sid,@@ -525,6 +534,9 @@ def plan_codex(else:argv = [*base, "exec", "--json", "--cd", str(cwd)]argv += ["--skip-git-repo-check"]+ # Jarvis' own tools over streamable-HTTP MCP, mounted for this run only —+ # the person's ~/.codex/config.toml is never touched.+ argv += jarvis_harness.codex_config_args()# The TUI's presets, spelled out for ``exec`` (codex 0.149): Read only /# Auto (workspace-write) / Full access (``--yolo``), plus "approve for# me" — Codex's own reviewer model decides what would have asked you,@@ -562,7 +574,7 @@ def plan_codex(argv += ["--model", model]argv += ["-"] # prompt on stdintext = _PLAN_PREAMBLE + prompt if mode == "plan" else prompt- return CliPlan(argv, _account_env("codex"), text, "codex", resume)+ return CliPlan(argv, jarvis_harness.apply_env(_account_env("codex")), text, "codex", resume)_PLANNERS: Final[dict[str, Any]] = {diff --git a/jarvis/mcp/jarvis_tools_server.py b/jarvis/mcp/jarvis_tools_server.pynew file mode 100644index 0000000000..96f2e45636--- /dev/null+++ b/jarvis/mcp/jarvis_tools_server.py@@ -0,0 +1,177 @@+"""Jarvis' own tools, offered outwards as an MCP server.++Every other MCP module in this package points INWARDS: Jarvis is the client+that mounts somebody else's server (``client.py``, ``loader.py``,+``registry.py``), or projects a connected plugin into a worker's config+(``claude_export.py``, ``marketplace/mcp_bridge.py``). This module is the one+that points OUT — it lets an agent session that Jarvis spawned reach back in+and drive Jarvis itself.++That is what turns the typed chat from "a coding CLI that happens to run in+Jarvis' window" into Jarvis with a keyboard instead of a microphone: the model+paying with the person's subscription runs its own agent loop, but its hands+are the hands the voice has — ``open-app``, ``google-calendar``,+``wiki-recall``, ``switch-provider``, every registered tool plugin.++**The safety seam is structural, not polite.** Tools are listed from+:class:`~jarvis.core.protocols.SupervisorToolGateway` and executed through it,+which is the only authorized execution path in the codebase (AP-3). A caller+here cannot reach a tool's ``execute`` directly, so risk tiers, the approval+workflow and the audit log apply exactly as they do on the voice path — there+is no second door to keep in sync.++Transport is Streamable HTTP, mounted on the app's own web server+(``jarvis.ui.web.mcp_server_routes``) rather than a stdio child process. The+gateway lives in the running app's memory; a child process would only be able+to talk back over the same HTTP anyway, one hop later.+"""++from __future__ import annotations++import json+import logging+from typing import Any, Final+from uuid import uuid4++log = logging.getLogger(__name__)++#: What ``SupervisorToolRequest.origin`` is stamped with. The risk evaluator and+#: the audit log use it to tell a chat-driven action from a spoken one.+CHAT_ORIGIN: Final[str] = "agent-chat"++#: Tools never offered to a chat session, by name. A spawn vehicle would let the+#: session start a background worker that starts another one — the recursion the+#: router tiers exist to prevent (AP-5/AP-14). The session IS the heavy worker+#: here; it has no reason to hire one.+_WITHHELD: Final[frozenset[str]] = frozenset(+ {+ "spawn-worker",+ "spawn_worker",+ "multi-spawn",+ "multi_spawn",+ "spawn-subagents",+ "spawn_subagents",+ "dispatch-to-harness",+ "dispatch_to_harness",+ "dispatch-with-review",+ "dispatch_with_review",+ "dispatch-to-admin",+ "dispatch_to_admin",+ }+)++#: MCP requires tool names to match ``[a-zA-Z0-9_-]{1,128}``. Jarvis names+#: already do; anything else is dropped rather than silently renamed, because a+#: renamed tool is a tool the model cannot be told about in a prompt.+_NAME_OK = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")+++def _usable_name(name: str) -> bool:+ return bool(name) and len(name) <= 128 and set(name) <= _NAME_OK+++def _gateway() -> Any | None:+ from jarvis.core import runtime_refs++ return runtime_refs.get_supervisor_tool_gateway()+++def offered_tools() -> list[Any]:+ """The catalog entries a chat session may call, gateway order preserved."""+ gateway = _gateway()+ if gateway is None:+ return []+ try:+ catalog = gateway.catalog()+ except Exception: # noqa: BLE001 — a broken catalog offers nothing, it never crashes the server+ log.warning("jarvis MCP: tool catalog unavailable", exc_info=True)+ return []+ return [+ entry+ for entry in catalog+ if _usable_name(str(entry.name)) and str(entry.name) not in _WITHHELD+ ]+++def _render(result: Any) -> str:+ """A ToolResult as the text the model reads back."""+ if result is None:+ return "The tool returned nothing."+ output = getattr(result, "output", None)+ error = getattr(result, "error", None)+ if not getattr(result, "success", False):+ return f"Tool failed: {error or 'no reason given'}"+ if output is None:+ return "Done."+ if isinstance(output, str):+ return output+ try:+ return json.dumps(output, ensure_ascii=False, default=str)+ except (TypeError, ValueError):+ return str(output)+++def build_server() -> Any:+ """A low-level MCP server bound to the live tool gateway.++ Built per process, not per session: the handlers read the gateway on every+ call, so a tool that connects later (an MCP source, a marketplace plugin, a+ CLI that finished bootstrapping) shows up without a rebuild.+ """+ import mcp.types as types+ from mcp.server.lowlevel import Server++ server: Any = Server("jarvis")++ @server.list_tools() # type: ignore[misc, no-untyped-call]+ async def _list_tools() -> list[Any]:+ tools: list[Any] = []+ for entry in offered_tools():+ schema = entry.input_schema+ if not isinstance(schema, dict) or not schema:+ schema = {"type": "object", "properties": {}}+ tools.append(+ types.Tool(+ name=str(entry.name),+ description=str(entry.description or entry.name),+ inputSchema=schema,+ )+ )+ return tools++ @server.call_tool() # type: ignore[misc, no-untyped-call]+ async def _call_tool(name: str, arguments: dict[str, Any] | None) -> list[Any]:+ from jarvis.core.protocols import SupervisorToolRequest++ gateway = _gateway()+ if gateway is None:+ return [types.TextContent(type="text", text="Jarvis is still starting up.")]+ if name in _WITHHELD:+ return [+ types.TextContent(+ type="text",+ text=(+ f"{name} is not available from the chat — you ARE the worker. "+ "Do the work yourself."+ ),+ )+ ]+ request = SupervisorToolRequest(+ trace_id=uuid4(),+ origin=CHAT_ORIGIN,+ user_utterance="",+ rationale="agent chat tool call",+ )+ try:+ result = await gateway.execute(name, dict(arguments or {}), request)+ except Exception as exc: # noqa: BLE001 — a tool failure is data for the model, not a crash+ log.warning("jarvis MCP: %s raised", name, exc_info=True)+ return [+ types.TextContent(type="text", text=f"Tool failed: {type(exc).__name__}: {exc}")+ ]+ return [types.TextContent(type="text", text=_render(result))]++ return server+++__all__ = ["CHAT_ORIGIN", "build_server", "offered_tools"]diff --git a/jarvis/ui/web/mcp_server_routes.py b/jarvis/ui/web/mcp_server_routes.pynew file mode 100644index 0000000000..329dfce182--- /dev/null+++ b/jarvis/ui/web/mcp_server_routes.py@@ -0,0 +1,117 @@+"""Serve Jarvis' own tools over MCP, so a spawned agent session can drive them.++Mounted as a raw ASGI sub-app rather than a FastAPI router: the MCP Streamable+HTTP transport needs the untouched ``(scope, receive, send)`` triple — it+streams, negotiates its own content types and answers ``GET``/``DELETE`` as+well as ``POST``. Wrapping that in a response model would fight it.++Authentication is the Control API's Bearer key, checked here instead of by a+dependency for the same reason. The rule is the Control API's rule (see+``control_auth``): loopback does NOT bypass it. The key is exactly what makes+this surface safe to exist — anything on the machine could otherwise open a+socket and start driving the person's calendar.++The session manager is stateless (a fresh transport per request), so a chat+turn that dies mid-tool leaves nothing to clean up. Its task group is started+on first use and lives for the process — there is no lifespan hook on this app+to hang it from, and one background task is cheaper than a per-request one.+"""++from __future__ import annotations++import asyncio+import logging+from typing import Any++log = logging.getLogger(__name__)++_UNAUTHORIZED_BODY = b'{"error":"Invalid or missing Jarvis Control API key."}'++_manager: Any | None = None+_manager_ready: asyncio.Event | None = None+_manager_task: asyncio.Task[None] | None = None+++def _bearer(scope: dict[str, Any]) -> str | None:+ for raw_name, raw_value in scope.get("headers") or ():+ if raw_name == b"authorization":+ scheme, _, token = raw_value.decode("latin-1").partition(" ")+ if scheme.lower() == "bearer" and token.strip():+ return token.strip()+ return None+++async def _reject(send: Any, status: int, body: bytes) -> None:+ await send(+ {+ "type": "http.response.start",+ "status": status,+ "headers": [+ (b"content-type", b"application/json"),+ (b"content-length", str(len(body)).encode()),+ ],+ }+ )+ await send({"type": "http.response.body", "body": body})+++async def _run_manager(manager: Any, ready: asyncio.Event) -> None:+ """Hold the manager's task group open for the life of the process."""+ try:+ async with manager.run():+ ready.set()+ await asyncio.Event().wait() # never set — cancelled at shutdown+ except asyncio.CancelledError:+ raise+ except Exception: # noqa: BLE001 — a dead manager must not take the web server with it+ log.warning("jarvis MCP: session manager stopped", exc_info=True)+ finally:+ ready.set() # unblock waiters so they fail fast instead of hanging+++async def _ensure_manager() -> Any | None:+ global _manager, _manager_ready, _manager_task+ if _manager is not None and _manager_ready is not None:+ await _manager_ready.wait()+ return _manager+ try:+ from mcp.server.streamable_http_manager import StreamableHTTPSessionManager++ from jarvis.mcp.jarvis_tools_server import build_server+ except Exception: # noqa: BLE001 — no MCP library → the surface is simply absent+ log.warning("jarvis MCP: server unavailable", exc_info=True)+ return None+ manager = StreamableHTTPSessionManager(+ app=build_server(),+ json_response=True,+ stateless=True,+ )+ ready = asyncio.Event()+ _manager = manager+ _manager_ready = ready+ _manager_task = asyncio.create_task(_run_manager(manager, ready))+ await ready.wait()+ return manager+++def build_mcp_asgi_app() -> Any:+ """The ASGI app to mount at ``/api/control/mcp``."""++ async def app(scope: dict[str, Any], receive: Any, send: Any) -> None:+ if scope.get("type") != "http":+ return+ from jarvis.core import control_key as ck++ if not ck.verify_control_key(_bearer(scope)):+ await _reject(send, 401, _UNAUTHORIZED_BODY)+ return+ manager = await _ensure_manager()+ if manager is None:+ await _reject(send, 503, b'{"error":"Jarvis MCP server is not available."}')+ return+ await manager.handle_request(scope, receive, send)++ return app+++__all__ = ["build_mcp_asgi_app"]diff --git a/tests/unit/agent_chat/test_chat_ide_separation.py b/tests/unit/agent_chat/test_chat_ide_separation.pynew file mode 100644index 0000000000..d4cb33201b--- /dev/null+++ b/tests/unit/agent_chat/test_chat_ide_separation.py@@ -0,0 +1,93 @@+"""Two chats, two worlds — and they must stay that way.++Jarvis has two typed surfaces that both run a coding CLI, and they mean+different things:++* the **front-page chat** (``jarvis.agent_chat``) is Jarvis with a keyboard.+ It gets Jarvis' own tools over MCP, so a sentence there can open an app,+ read the calendar or switch the brain provider.+* the **Agentic-IDE panes** (``jarvis.agentic_ide``) are coding agents in a+ workspace. Each pane is a real PTY on the person's own subscription seat,+ with the CLI's own tools and nothing else — the terminal experience, in a+ window.++Merging them would be easy and wrong in both directions: a coding pane that+can silently re-point the brain provider is a surprise, and a Jarvis chat that+has to be a workspace first is the very thing the maintainer rejected on+2026-08-24. These tests pin the seam that keeps them apart.+"""++from __future__ import annotations++import ast+from pathlib import Path++import pytest++_ROOT = Path(__file__).resolve().parents[3]+_IDE = _ROOT / "jarvis" / "agentic_ide"++#: The chat-only modules. Nothing under ``jarvis/agentic_ide`` may reach these:+#: they are what hands a session Jarvis' own tools.+_CHAT_ONLY = ("jarvis.agent_chat.jarvis_harness", "jarvis.agent_chat.runner_cli")+++def _imported_modules(path: Path) -> set[str]:+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))+ found: set[str] = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ found.update(alias.name for alias in node.names)+ elif isinstance(node, ast.ImportFrom) and node.module and not node.level:+ found.add(node.module)+ found.update(f"{node.module}.{alias.name}" for alias in node.names)+ return found++[email protected](not _IDE.is_dir(), reason="agentic_ide package not present")+def test_the_ide_never_reaches_into_the_chat_runner():+ """A pane must not acquire Jarvis' tools by importing the chat's plumbing."""+ offenders: list[str] = []+ for module in sorted(_IDE.rglob("*.py")):+ imported = _imported_modules(module)+ for banned in _CHAT_ONLY:+ if any(name == banned or name.startswith(banned + ".") for name in imported):+ offenders.append(f"{module.relative_to(_ROOT)} imports {banned}")+ assert not offenders, "the IDE reached into the chat runner:\n" + "\n".join(offenders)+++def test_only_the_chat_package_hands_out_jarvis_tools():+ """The MCP config has exactly one home: nothing outside jarvis/agent_chat builds it."""+ callers: list[str] = []+ for module in sorted((_ROOT / "jarvis").rglob("*.py")):+ if module.parent.name == "agent_chat":+ continue+ text = module.read_text(encoding="utf-8", errors="replace")+ if "mcp_config_json" in text or "codex_config_args" in text:+ callers.append(str(module.relative_to(_ROOT)))+ assert callers == [], f"unexpected callers of the Jarvis MCP config: {callers}"+++def test_the_chat_child_environment_is_a_copy_never_the_process_environment():+ """The control key must reach the chat's child and nothing else on the box."""+ import os++ from jarvis.agent_chat import jarvis_harness++ before = os.environ.get(jarvis_harness.KEY_ENV_VAR)+ child: dict[str, str] = {}+ jarvis_harness.apply_env(child)+ assert os.environ.get(jarvis_harness.KEY_ENV_VAR) == before+++def test_the_ide_panes_and_the_chat_do_not_share_a_spawn_function():+ """One shared argv builder is how two surfaces silently become one."""+ from jarvis.agent_chat import runner_cli++ ide_session = _IDE / "session.py"+ if not ide_session.is_file():+ pytest.skip("agentic_ide.session not present")+ text = ide_session.read_text(encoding="utf-8", errors="replace")+ for name in ("plan_claude", "plan_codex", "plan_agy", "plan_grok"):+ if hasattr(runner_cli, name):+ assert name not in text, f"the IDE calls the chat's {name}"diff --git a/tests/unit/agent_chat/test_jarvis_harness.py b/tests/unit/agent_chat/test_jarvis_harness.pynew file mode 100644index 0000000000..d514adc448--- /dev/null+++ b/tests/unit/agent_chat/test_jarvis_harness.py@@ -0,0 +1,164 @@+"""The chat runs INSIDE the Jarvis harness — the wiring that makes that true.++Covers the three seams that decide whether a typed turn is Jarvis or a coding+agent in a folder: which tools are offered, how they are executed, and what the+spawned CLI is actually told.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any++import pytest++from jarvis.agent_chat import jarvis_harness+from jarvis.core import runtime_refs+from jarvis.mcp import jarvis_tools_server as server+++@dataclass+class _Result:+ success: bool = True+ output: Any = None+ error: str | None = None+++@dataclass+class _Descriptor:+ name: str+ description: str = "a tool"+ input_schema: dict[str, Any] = field(default_factory=lambda: {"type": "object"})+ risk_tier: str = "safe"+++@dataclass+class _Gateway:+ names: tuple[str, ...] = ("open-app", "spawn-worker", "wiki-recall")+ calls: list[tuple[str, dict[str, Any], Any]] = field(default_factory=list)+ raises: bool = False++ def catalog(self) -> tuple[_Descriptor, ...]:+ return tuple(_Descriptor(name=n) for n in self.names)++ async def execute(self, name: str, arguments: dict[str, Any], request: Any) -> _Result:+ if self.raises:+ raise RuntimeError("boom")+ self.calls.append((name, arguments, request))+ return _Result(success=True, output={"ok": name})++[email protected](autouse=True)+def _clean_refs():+ yield+ runtime_refs._reset_for_tests()+++def test_spawn_vehicles_are_never_offered_to_the_chat():+ """The session IS the worker; a spawn tool would only start another one (AP-5/AP-14)."""+ runtime_refs.set_supervisor_tool_gateway(_Gateway())+ offered = [entry.name for entry in server.offered_tools()]+ assert "open-app" in offered and "wiki-recall" in offered+ assert "spawn-worker" not in offered+++def test_no_gateway_offers_nothing_instead_of_crashing():+ assert server.offered_tools() == []+++def test_a_name_mcp_cannot_carry_is_dropped_not_renamed():+ runtime_refs.set_supervisor_tool_gateway(_Gateway(names=("fine-name", "not a name!")))+ assert [e.name for e in server.offered_tools()] == ["fine-name"]+++def test_a_tool_result_becomes_text_the_model_can_read():+ assert server._render(_Result(success=True, output="plain")) == "plain"+ assert server._render(_Result(success=True, output={"a": 1})) == '{"a": 1}'+ assert server._render(_Result(success=True, output=None)) == "Done."+ assert "no reason given" in server._render(_Result(success=False))+ assert "went wrong" in server._render(_Result(success=False, error="went wrong"))+++def test_the_config_is_withheld_until_the_app_can_actually_serve_it(monkeypatch):+ """Half a config is worse than none: the CLI would fail to connect mid-turn."""+ monkeypatch.setattr(jarvis_harness, "control_key", lambda: "k")+ assert jarvis_harness.mcp_config_json() is None # no base URL yet+ assert jarvis_harness.codex_config_args() == []++ runtime_refs.set_api_base_url("http://127.0.0.1:47821")+ monkeypatch.setattr(jarvis_harness, "control_key", lambda: None)+ assert jarvis_harness.mcp_config_json() is None # no key+ assert jarvis_harness.codex_config_args() == []+++def test_the_key_travels_in_the_environment_never_in_argv(monkeypatch):+ """argv is readable by every process on the machine; the control key is the boundary."""+ monkeypatch.setattr(jarvis_harness, "control_key", lambda: "super-secret-key")+ runtime_refs.set_api_base_url("http://127.0.0.1:47821")++ config = jarvis_harness.mcp_config_json() or ""+ codex_args = " ".join(jarvis_harness.codex_config_args())+ assert "super-secret-key" not in config+ assert "super-secret-key" not in codex_args+ assert "${JARVIS_CONTROL_API_KEY}" in config+ assert "bearer_token_env_var" in codex_args++ env = jarvis_harness.apply_env({})+ assert env["JARVIS_CONTROL_API_KEY"] == "super-secret-key"+++def test_both_cli_shapes_point_at_the_same_endpoint(monkeypatch):+ monkeypatch.setattr(jarvis_harness, "control_key", lambda: "k")+ runtime_refs.set_api_base_url("http://127.0.0.1:47921/")+ url = "http://127.0.0.1:47921/api/control/mcp"+ assert url in (jarvis_harness.mcp_config_json() or "")+ assert any(url in arg for arg in jarvis_harness.codex_config_args())+++def test_the_preamble_names_the_prefix_the_tools_actually_get():+ """If the prefix drifts, the model is told to use tools it cannot see."""+ assert "mcp__jarvis__" in jarvis_harness.SYSTEM_PREAMBLE+ assert jarvis_harness._SERVER_NAME == "jarvis"+++def test_claude_argv_carries_the_tools_and_the_identity(monkeypatch):+ from jarvis.agent_chat import runner_cli++ monkeypatch.setattr(runner_cli, "claude_argv_prefix", lambda: ["claude"])+ monkeypatch.setattr(runner_cli.jarvis_harness, "control_key", lambda: "k")+ runtime_refs.set_api_base_url("http://127.0.0.1:47821")++ from pathlib import Path++ plan = runner_cli.plan_claude(+ prompt="hi",+ cwd=Path.cwd(),+ model="claude-opus-5",+ effort="high",+ permission_mode="ask",+ resume=None,+ )+ assert "--mcp-config" in plan.argv+ assert "--append-system-prompt" in plan.argv+ assert plan.env["JARVIS_CONTROL_API_KEY"] == "k"+++def test_a_chat_without_a_ready_app_spawns_exactly_as_before(monkeypatch):+ """No tools to offer must never cost the person their turn."""+ from pathlib import Path++ from jarvis.agent_chat import runner_cli++ monkeypatch.setattr(runner_cli, "claude_argv_prefix", lambda: ["claude"])+ monkeypatch.setattr(runner_cli.jarvis_harness, "control_key", lambda: None)++ plan = runner_cli.plan_claude(+ prompt="hi",+ cwd=Path.cwd(),+ model="",+ effort="",+ permission_mode="ask",+ resume=None,+ )+ assert "--mcp-config" not in plan.argv+ assert "--append-system-prompt" not in plan.argv