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): a subscription CLI seat runs as Jarvis — real prompt layers, the chat's transcript, one approval card
rubenluetke10-beep8c2118a90f7c
diff --git a/jarvis/agent_chat/jarvis_harness.py b/jarvis/agent_chat/jarvis_harness.pyindex 0bbfa9dc43..cf1a9da8fc 100644--- a/jarvis/agent_chat/jarvis_harness.py+++ b/jarvis/agent_chat/jarvis_harness.py@@ -1,30 +1,41 @@-"""What makes the chat session Jarvis rather than a coding agent in a folder.+"""What makes a CLI seat's chat session Jarvis rather than a coding agent in a folder.-Two things are handed to the spawned CLI:+Three 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.+ — the same catalog the voice path calls, through the same safety gateway.+ The config carries the chat's session id in a header, so the tool server can+ route an approval the executor asks for back to THIS chat's card;+* an **identity** — Jarvis' real system-prompt layers (soul, persona, the+ assistant file, the user's profile, the identity card, core memory, wiki+ context), the chat's own transcript on a fresh conversation, and the surface+ addendum below that says which hands are whose;+* a **system preamble** (the addendum) 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 forthese turns through a *subscription* (Claude Code, Codex, …), and asubscription only pays for the CLI's own agent loop. Driving the loop fromJarvis' 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.+the wheel and Jarvis lends it the hands AND the head — the model works INSIDE+the Jarvis harness while the seat stays the person's own, and only the vendor's+official binary ever spends the subscription (maintainer, 2026-08-25).-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.+This surface is deliberately additive: a CLI that cannot mount MCP servers, an+app whose tool gateway is not up yet, or a brain that has not finished building+simply runs with less. Nothing here is allowed to make a turn fail."""from __future__ import annotationsimport jsonimport logging-from typing import Final+import re+import uuid+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Finallog = logging.getLogger(__name__)@@ -40,6 +51,14 @@ _MCP_PATH: Final[str] = "/api/control/mcp/"#: must stay in step._SERVER_NAME: Final[str] = "jarvis"+#: The request header that carries the chat's session id to the tool server.+#: ``jarvis.mcp.jarvis_tools_server`` reads it (through+#: ``jarvis.ui.web.mcp_server_routes``) and stamps the executor's approval+#: surface with it, so a gate the CLI reaches over MCP is answered by THIS+#: chat's card. Any other client — or a config without it — gets the+#: unattended surface, exactly as before.+HEADER_NAME: Final[str] = "X-Jarvis-Chat-Session"+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 "@@ -54,6 +73,10 @@ SYSTEM_PREAMBLE: Final[str] = ("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"+ "Two kinds of hands: your own file and shell tools are your hands in the "+ "working folder this chat is open in; `mcp__jarvis__run_shell` and its "+ "siblings are Jarvis' hands on the whole machine. Use the folder's hands for "+ "the folder, Jarvis' for everything else.\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"@@ -69,6 +92,13 @@ SYSTEM_PREAMBLE: Final[str] = (#: security boundary.KEY_ENV_VAR: Final[str] = "JARVIS_CONTROL_API_KEY"+#: How much of the chat's transcript rides along on a fresh conversation.+TRANSCRIPT_MAX_CHARS: Final[int] = 20_000++#: A compact identity for a CLI whose prompt travels on argv (Grok Build):+#: Windows caps a command line at 32 767 characters.+COMPACT_MAX_CHARS: Final[int] = 16_000+def endpoint() -> str | None:"""This app's own MCP URL, or ``None`` before the web server bound."""@@ -84,29 +114,27 @@ def control_key() -> str | None:return ck.get_control_key()-def mcp_config_json() -> str | None:+def mcp_config_json(session_id: str | None = None) -> 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 thenspawns the CLI exactly as before instead of handing it a config that would- fail to connect and cost the turn a confusing error.+ fail to connect and cost the turn a confusing error. With ``session_id``+ the config also carries the chat's session header (see ``HEADER_NAME``)."""try:url = endpoint()if not url or not control_key():return None+ headers: dict[str, str] = {+ # Expanded by the CLI from the child env — see KEY_ENV_VAR.+ "Authorization": f"Bearer ${{{KEY_ENV_VAR}}}",+ }+ if session_id:+ headers[HEADER_NAME] = session_idreturn 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}}}"},- }- }- },+ {"mcpServers": {_SERVER_NAME: {"type": "http", "url": url, "headers": headers}}},ensure_ascii=False,)except Exception: # noqa: BLE001 — no Jarvis tools is a degraded chat, never a broken one@@ -114,24 +142,32 @@ def mcp_config_json() -> str | None:return None-def codex_config_args() -> list[str]:+def codex_config_args(session_id: str | None = None) -> list[str]:"""``-c`` overrides that mount the tool server in ``codex exec``.Codex speaks streamable HTTP MCP with a bearer token read from anenvironment 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``.+ turn never edits the person's own ``~/.codex/config.toml``. With+ ``session_id`` the chat's session header rides along as an+ ``http_headers`` inline table."""try:url = endpoint()if not url or not control_key():return []- return [+ args = ["-c",f'mcp_servers.{_SERVER_NAME}.url="{url}"',"-c",f'mcp_servers.{_SERVER_NAME}.bearer_token_env_var="{KEY_ENV_VAR}"',]+ if session_id:+ args += [+ "-c",+ f'mcp_servers.{_SERVER_NAME}.http_headers={{"{HEADER_NAME}"="{session_id}"}}',+ ]+ return argsexcept Exception: # noqa: BLE001 — see mcp_config_jsonlog.warning("agent chat: could not build the Codex MCP overrides", exc_info=True)return []@@ -155,13 +191,179 @@ def tool_count() -> int:return 0+# ------------------------------------------------------------------ identity+++@dataclass(slots=True)+class Identity:+ """What a CLI seat is told it is, this turn.++ ``text`` is the full identity (Jarvis' layers, the transcript, the+ addendum); ``compact`` a shorter cut for a CLI whose prompt travels on+ argv; ``path`` the file the full text was written to for a CLI that takes+ a system-prompt file (Claude Code), removed by the runner afterwards.+ """++ session_id: str+ text: str+ compact: str+ path: Path | None = None+++def _brain() -> Any | None:+ from jarvis.core import runtime_refs++ return runtime_refs.get_brain_manager()+++async def identity_prompt(+ *,+ user_text: str,+ history: list[dict[str, Any]],+ resume: str | None,+) -> str:+ """Jarvis' real prompt layers + the chat's transcript + the addendum.++ The layers come from the live brain (``BrainManager.render_surface_prompt``:+ soul, persona, the assistant file, the user's profile, contacts, the+ identity card, core memory, the wiki context for ``user_text``, and the+ turn context). Without a brain — before it finished building, or on a+ box that runs the chat alone — the addendum stands in, as it did before:+ nothing here may fail a turn.++ The transcript rides along on a FRESH conversation only: a CLI that+ resumes its own session already carries it, and repeating it there would+ tell the model the same story twice.+ """+ parts: list[str] = []+ brain = _brain()+ render = getattr(brain, "render_surface_prompt", None) if brain is not None else None+ if callable(render):+ try:+ system_prompt, turn_context = await render(user_text=user_text)+ if system_prompt.strip():+ parts.append(system_prompt.strip())+ if turn_context.strip():+ parts.append(turn_context.strip())+ except Exception: # noqa: BLE001 — the addendum alone is still a working chat+ log.warning("agent chat: Jarvis' prompt layers unavailable this turn", exc_info=True)+ if resume is None and history:+ transcript = render_transcript(history)+ if transcript:+ parts.append("## This conversation so far\n\n" + transcript)+ parts.append(SYSTEM_PREAMBLE)+ return "\n\n".join(parts)+++def render_transcript(+ history: list[dict[str, Any]], *, max_chars: int = TRANSCRIPT_MAX_CHARS+) -> str:+ """The chat's log as plain prose, newest last, cut to ``max_chars`` from the front."""+ from jarvis.agent_chat.runner_api import messages_from_events++ lines: list[str] = []+ for message in messages_from_events(history):+ if message.role == "user":+ text = message.content if isinstance(message.content, str) else ""+ if text.strip():+ lines.append(f"Person: {text.strip()}")+ elif message.role == "assistant":+ text = _prose(message.content)+ if text.strip():+ lines.append(f"Jarvis: {text.strip()}")+ out = "\n\n".join(lines)+ if len(out) > max_chars:+ out = "…" + out[-max_chars:]+ return out+++def _prose(content: str | list[dict[str, Any]]) -> str:+ if isinstance(content, str):+ return content+ bits: list[str] = []+ for block in content:+ if block.get("type") == "text":+ bits.append(str(block.get("text") or ""))+ elif block.get("type") == "tool_use":+ bits.append(f"[used tool {block.get('name') or 'tool'}]")+ return "\n".join(b for b in bits if b.strip())+++def compact_identity(text: str, *, max_chars: int = COMPACT_MAX_CHARS) -> str:+ """The identity cut for argv: the addendum is kept whole, the rest trimmed."""+ if len(text) <= max_chars:+ return text+ head_room = max(0, max_chars - len(SYSTEM_PREAMBLE) - 8)+ body = text[: -len(SYSTEM_PREAMBLE)] if text.endswith(SYSTEM_PREAMBLE) else text+ body = body[:head_room].rstrip()+ body = re.sub(r"\n[^\n]*$", "", body) # do not cut a line in half+ return f"{body}\n\n…\n\n{SYSTEM_PREAMBLE}"+++def identity_dir() -> Path:+ """Where identity files live: the app's own data dir, never a shared temp."""+ from jarvis.core.paths import user_data_dir++ return user_data_dir() / "agent_chat" / "identity"+++def write_identity_file(text: str, *, turn_id: str) -> Path:+ """Write the identity for a CLI that takes a system-prompt FILE.++ Claude Code's ``--append-system-prompt-file`` exists because argv cannot+ carry a prompt this size on Windows (32 767 characters for the whole+ command line; Jarvis' layers alone run past 50 000). The runner removes+ the file when the turn ends.+ """+ folder = identity_dir()+ folder.mkdir(parents=True, exist_ok=True)+ path = folder / f"{turn_id or uuid.uuid4().hex}.md"+ path.write_text(text, encoding="utf-8")+ return path+++def remove_identity_file(path: Path | None) -> None:+ if path is None:+ return+ try:+ path.unlink(missing_ok=True)+ except OSError:+ log.debug("agent chat: identity file %s not removed", path, exc_info=True)+++async def build_identity(+ *,+ session_id: str,+ turn_id: str,+ user_text: str,+ history: list[dict[str, Any]],+ resume: str | None,+ with_file: bool,+) -> Identity:+ """The identity for one CLI turn; ``with_file`` for a CLI that takes a file."""+ text = await identity_prompt(user_text=user_text, history=history, resume=resume)+ path = write_identity_file(text, turn_id=turn_id) if with_file else None+ return Identity(session_id=session_id, text=text, compact=compact_identity(text), path=path)++__all__ = [+ "COMPACT_MAX_CHARS",+ "HEADER_NAME","KEY_ENV_VAR","SYSTEM_PREAMBLE",+ "TRANSCRIPT_MAX_CHARS",+ "Identity","apply_env",+ "build_identity","codex_config_args",+ "compact_identity","control_key","endpoint",+ "identity_dir",+ "identity_prompt","mcp_config_json",+ "remove_identity_file",+ "render_transcript","tool_count",+ "write_identity_file",]diff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.pyindex 13f365c301..6478944aef 100644--- a/jarvis/agent_chat/runner_cli.py+++ b/jarvis/agent_chat/runner_cli.py@@ -197,7 +197,14 @@ def claude_stream_input(prompt: str) -> str:def plan_claude(- *, prompt: str, cwd: Path, model: str, effort: str, permission_mode: str, resume: str | None+ *,+ prompt: str,+ cwd: Path,+ model: str,+ effort: str,+ permission_mode: str,+ resume: str | None,+ identity: jarvis_harness.Identity | None = None,) -> CliPlan:mode = normalize_permission("claude-cli", permission_mode)argv = [@@ -223,15 +230,16 @@ def plan_claude(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()+ # yet) — the session then behaves exactly as it did before. On the Jarvis+ # surface the identity is Jarvis' whole head, in a FILE: argv cannot carry+ # it on Windows (32 767 characters for the whole command line).+ mcp_config = jarvis_harness.mcp_config_json(identity.session_id if identity else None)if mcp_config:- argv += [- "--mcp-config",- mcp_config,- "--append-system-prompt",- jarvis_harness.SYSTEM_PREAMBLE,- ]+ argv += ["--mcp-config", mcp_config]+ if identity is not None and identity.path is not None:+ argv += ["--append-system-prompt-file", str(identity.path)]+ else:+ argv += ["--append-system-prompt", jarvis_harness.SYSTEM_PREAMBLE]if resume:argv += ["--resume", resume]sid = resume@@ -250,8 +258,18 @@ def plan_claude(def plan_grok(- *, prompt: str, cwd: Path, model: str, effort: str, permission_mode: str, resume: str | None+ *,+ prompt: str,+ cwd: Path,+ model: str,+ effort: str,+ permission_mode: str,+ resume: str | None,+ identity: jarvis_harness.Identity | None = None,) -> CliPlan:+ # Grok Build takes the prompt on argv, so the identity rides in front of+ # it — the compact cut, and only on a fresh conversation.+ prompt = _with_identity(prompt, identity, resume, compact=True)argv = [*grok_argv_prefix(),"--no-auto-update",@@ -384,9 +402,19 @@ def _nearest_lower(effort: str, ladder: list[str]) -> str:def plan_agy(- *, prompt: str, cwd: Path, model: str, effort: str, permission_mode: str, resume: str | None+ *,+ prompt: str,+ cwd: Path,+ model: str,+ effort: str,+ permission_mode: str,+ resume: str | None,+ identity: jarvis_harness.Identity | None = None,) -> CliPlan:mode = normalize_permission("agy-cli", permission_mode)+ # agy has no system-prompt flag: the identity rides in front of the prompt+ # on stdin, on a fresh conversation (a resumed one already knows).+ prompt = _with_identity(prompt, identity, resume)argv = [*agy_argv_prefix(),"--output-format",@@ -525,9 +553,21 @@ def read_agy_models(timeout_s: float = 8.0) -> list[dict[str, Any]]:def plan_codex(- *, prompt: str, cwd: Path, model: str, effort: str, permission_mode: str, resume: str | None+ *,+ prompt: str,+ cwd: Path,+ model: str,+ effort: str,+ permission_mode: str,+ resume: str | None,+ identity: jarvis_harness.Identity | None = None,) -> CliPlan:mode = normalize_permission("codex-cli", permission_mode)+ # Codex reads the prompt from stdin, which has no length limit: the+ # identity rides in front of it on a fresh conversation. (Its+ # ``model_instructions_file`` REPLACES the CLI's own instructions rather+ # than adding to them, so it is not used here.)+ prompt = _with_identity(prompt, identity, resume)base = codex_argv_prefix()if resume:argv = [*base, "exec", "resume", resume, "--json"]@@ -536,7 +576,7 @@ def plan_codex(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()+ argv += jarvis_harness.codex_config_args(identity.session_id if identity else None)# 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,@@ -577,6 +617,26 @@ def plan_codex(return CliPlan(argv, jarvis_harness.apply_env(_account_env("codex")), text, "codex", resume)+def _with_identity(+ prompt: str,+ identity: jarvis_harness.Identity | None,+ resume: str | None,+ *,+ compact: bool = False,+) -> str:+ """The prompt with the identity in front of it — on a fresh conversation.++ A resumed conversation carries the identity from its first turn; repeating+ fifty thousand characters of it every turn would cost the subscription's+ context for nothing. The block is fenced so the model can tell the head+ from the person's words.+ """+ if identity is None or resume:+ return prompt+ text = identity.compact if compact else identity.text+ return f"<jarvis_identity>\n{text}\n</jarvis_identity>\n\n{prompt}"++_PLANNERS: Final[dict[str, Any]] = {"claude-cli": plan_claude,"grok-cli": plan_grok,@@ -1257,25 +1317,88 @@ def _resume_was_lost(error: str | None) -> bool:return any(m in low for m in _RESUME_LOST_MARKERS)-async def run_cli_turn(handle: TurnHandle, user_text: str, runner: str) -> str | None:+async def run_cli_turn(+ handle: TurnHandle,+ user_text: str,+ runner: str,+ *,+ identity: bool = False,+ bridge: Any | None = None,+ always_allowed: set[str] | None = None,+) -> str | None:"""Run one CLI turn. Returns the vendor session id to persist (or None).A resume the CLI no longer knows is retried once as a fresh conversation(the person keeps typing; only the CLI-side memory is gone, the timelinehere is intact).++ ``identity`` (the Jarvis surface): the CLI runs AS Jarvis — Jarvis' real+ prompt layers and the chat's transcript go in front of it, and the+ approval ``bridge`` is armed with the chat's stance so a Jarvis tool the+ CLI reaches over MCP asks the person on the chat's card (and a tool the+ CLI already asked about on its own channel is not asked about twice)."""t0 = time.perf_counter()- outcome = await _run_cli_once(handle, user_text, runner, handle.session.vendor_session)- # agy answers a lost conversation id with a NEW conversation and exit 0- # (only a stderr warning) — the id that came back is the truth.- if (- outcome.status == "error"- and handle.session.vendor_session- and _resume_was_lost(outcome.error)- and not handle.cancel.is_set()- ):- log.info("agent chat %s: resume lost (%s) — starting fresh", handle.turn_id, outcome.error)- outcome = await _run_cli_once(handle, user_text, runner, None)+ session = handle.session+ resume = session.vendor_session+ ident: jarvis_harness.Identity | None = None+ ref = f"agent-chat:{session.session_id}"+ if identity:+ ident = await jarvis_harness.build_identity(+ session_id=session.session_id,+ turn_id=handle.turn_id,+ user_text=user_text,+ history=handle.history,+ resume=resume,+ with_file=(runner == "claude-cli"),+ )+ if bridge is not None:+ from jarvis.agent_chat.approval_bridge import ChatGrant++ bridge.arm(+ ref,+ ChatGrant(+ session_id=session.session_id,+ turn_id=handle.turn_id,+ stance=handle.stance or "ask",+ always_allowed=always_allowed if always_allowed is not None else set(),+ ask=handle.request_approval,+ ),+ )+ try:+ outcome = await _run_cli_once(+ handle, user_text, runner, resume, identity=ident, bridge=bridge+ )+ # agy answers a lost conversation id with a NEW conversation and exit 0+ # (only a stderr warning) — the id that came back is the truth.+ if (+ outcome.status == "error"+ and resume+ and _resume_was_lost(outcome.error)+ and not handle.cancel.is_set()+ ):+ log.info(+ "agent chat %s: resume lost (%s) — starting fresh", handle.turn_id, outcome.error+ )+ if ident is not None:+ # Fresh conversation: the transcript belongs in front now.+ jarvis_harness.remove_identity_file(ident.path)+ ident = await jarvis_harness.build_identity(+ session_id=session.session_id,+ turn_id=handle.turn_id,+ user_text=user_text,+ history=handle.history,+ resume=None,+ with_file=(runner == "claude-cli"),+ )+ outcome = await _run_cli_once(+ handle, user_text, runner, None, identity=ident, bridge=bridge+ )+ finally:+ if bridge is not None and identity:+ bridge.disarm(ref)+ if ident is not None:+ jarvis_harness.remove_identity_file(ident.path)await handle.emit(make_event("turn_finished",@@ -1293,9 +1416,16 @@ async def run_cli_turn(handle: TurnHandle, user_text: str, runner: str) -> str |async def _run_cli_once(- handle: TurnHandle, user_text: str, runner: str, resume: str | None+ handle: TurnHandle,+ user_text: str,+ runner: str,+ resume: str | None,+ *,+ identity: jarvis_harness.Identity | None = None,+ bridge: Any | None = None,) -> _Outcome:session = handle.session+ approval_ref = f"agent-chat:{session.session_id}"cwd = Path(session.cwd or Path.home())effort = normalize_effort(session.provider, session.effort)planner = _PLANNERS[runner]@@ -1313,6 +1443,7 @@ async def _run_cli_once(effort=effort,permission_mode=session.permission_mode,resume=resume,+ identity=identity,)except CliUnavailable as exc:return _Outcome("error", str(exc), {}, None, None)@@ -1457,6 +1588,10 @@ async def _run_cli_once()if decision in {"allow", "allow_always"}:body: dict[str, Any] = {"behavior": "allow", "updatedInput": req.get("input") or {}}+ if bridge is not None and subtype == "can_use_tool":+ # A Jarvis tool the CLI just asked about will hit the executor's+ # own gate over MCP in a moment; the person has answered once.+ bridge.note_cli_approval(approval_ref, tool_name)else:body = {"behavior": "deny", "message": message}frame = {diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.pyindex bb55b02db5..05b94349aa 100644--- a/jarvis/agent_chat/service.py+++ b/jarvis/agent_chat/service.py@@ -262,7 +262,14 @@ class AgentChatService:always_allowed=self.always_allowed(session_id),)elif supports_cli_runner(runner):- vendor = await run_cli_turn(handle, text, runner)+ vendor = await run_cli_turn(+ handle,+ text,+ runner,+ identity=(session.surface == "jarvis"),+ bridge=self._bridge_for(bus) if session.surface == "jarvis" else None,+ always_allowed=self.always_allowed(session_id),+ )if vendor and vendor != session.vendor_session:self.store.update_session(session_id, vendor_session=vendor)elif runner == "api" and supports_api_runner(session.provider):diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 722a51f06a..ff1466a809 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -3531,6 +3531,34 @@ class BrainManager:kwargs["max_turns"] = override.max_turnsreturn kwargs+ async def render_surface_prompt(self, *, user_text: str) -> tuple[str, str]:+ """(system prompt, turn context) for an external agent that should BE Jarvis.++ A subscription CLI seat on the typed chat runs its own loop, but the+ head it runs with is this one: the same layers ``_build_system_prompt``+ stacks for a voice turn (name, soul, persona, the assistant file, the+ user's profile, people, contacts, the identity card, core memory, the+ skills section, the tool-routing rules), the wiki context this turn's+ text pulls in, and the per-turn context (date, awareness). Read-only:+ nothing is stored on the manager, so a voice turn running alongside+ sees no trace of it.+ """+ base = self._build_system_prompt()+ prompt = base+ if self._wiki_injector is not None:+ try:+ prompt = await self._wiki_injector.maybe_inject(+ user_text=user_text, system_prompt=base+ )+ except Exception: # noqa: BLE001 — the layers without the wiki are still Jarvis+ log.debug("render_surface_prompt: wiki context skipped", exc_info=True)+ try:+ turn_context = self._build_turn_context()+ except Exception: # noqa: BLE001 — the context block is a nicety+ log.debug("render_surface_prompt: turn context skipped", exc_info=True)+ turn_context = ""+ return prompt, turn_context+def _build_tool_ack_emitter(self, user_text: str) -> Callable[[str, dict[str, Any]], Awaitable[None]] | None:diff --git a/jarvis/mcp/jarvis_tools_server.py b/jarvis/mcp/jarvis_tools_server.pyindex 96f2e45636..03f8a89ac3 100644--- a/jarvis/mcp/jarvis_tools_server.py+++ b/jarvis/mcp/jarvis_tools_server.py@@ -30,6 +30,7 @@ from __future__ import annotationsimport jsonimport logging+from contextvars import ContextVarfrom typing import Any, Finalfrom uuid import uuid4@@ -39,6 +40,33 @@ log = logging.getLogger(__name__)#: the audit log use it to tell a chat-driven action from a spoken one.CHAT_ORIGIN: Final[str] = "agent-chat"+#: The agent-chat session a request belongs to, set per HTTP request by+#: ``jarvis.ui.web.mcp_server_routes`` from the ``X-Jarvis-Chat-Session``+#: header the chat put into the CLI's MCP config. Read when a tool is+#: executed: with a session the executor is told the approval surface is the+#: chat's card (``approval_surface: interactive`` + the session's+#: ``approval_ref``), so an ask-tier tool the CLI reaches through here asks+#: the person in the chat instead of failing fast as unattended. Without one+#: the request runs exactly as before.+CHAT_SESSION_REF: ContextVar[str | None] = ContextVar("jarvis.mcp.chat_session_ref", default=None)++#: How long the chat's card may stay open for a gate reached over MCP.+CHAT_APPROVAL_TIMEOUT_S: Final[float] = 600.0+++def approval_snapshot() -> dict[str, Any]:+ """The executor's ``config_snapshot`` for the current request's session."""+ session_id = CHAT_SESSION_REF.get()+ if not session_id:+ return {}+ return {+ "approval_surface": "interactive",+ "approval_ref": f"agent-chat:{session_id}",+ "approval_timeout_s": CHAT_APPROVAL_TIMEOUT_S,+ "tool_origin": CHAT_ORIGIN,+ }++#: 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@@ -161,6 +189,7 @@ def build_server() -> Any:origin=CHAT_ORIGIN,user_utterance="",rationale="agent chat tool call",+ config_snapshot=approval_snapshot(),)try:result = await gateway.execute(name, dict(arguments or {}), request)@@ -174,4 +203,11 @@ def build_server() -> Any:return server-__all__ = ["CHAT_ORIGIN", "build_server", "offered_tools"]+__all__ = [+ "CHAT_APPROVAL_TIMEOUT_S",+ "CHAT_ORIGIN",+ "CHAT_SESSION_REF",+ "approval_snapshot",+ "build_server",+ "offered_tools",+]diff --git a/jarvis/ui/web/mcp_server_routes.py b/jarvis/ui/web/mcp_server_routes.pyindex 329dfce182..e12ab7b592 100644--- a/jarvis/ui/web/mcp_server_routes.py+++ b/jarvis/ui/web/mcp_server_routes.py@@ -41,6 +41,21 @@ def _bearer(scope: dict[str, Any]) -> str | None:return None+#: The agent-chat session header, lower-cased as ASGI hands headers over.+_SESSION_HEADER = b"x-jarvis-chat-session"+++def session_ref(scope: dict[str, Any]) -> str | None:+ """The chat session id a request names, or ``None`` (any other client)."""+ for raw_name, raw_value in scope.get("headers") or ():+ if raw_name == _SESSION_HEADER:+ value = raw_value.decode("latin-1").strip()+ # A session id is a hex uuid; anything else is not ours to trust.+ if value and len(value) <= 64 and value.replace("-", "").isalnum():+ return value+ return None++async def _reject(send: Any, status: int, body: bytes) -> None:await send({@@ -109,9 +124,19 @@ def build_mcp_asgi_app() -> Any:if manager is None:await _reject(send, 503, b'{"error":"Jarvis MCP server is not available."}')return- await manager.handle_request(scope, receive, send)+ # The session travels in a ContextVar: the stateless transport runs+ # the tool call in a task started from this request, which inherits+ # the context, and the tool server reads it when it builds the+ # executor's approval surface (jarvis_tools_server.approval_snapshot).+ from jarvis.mcp.jarvis_tools_server import CHAT_SESSION_REF++ token = CHAT_SESSION_REF.set(session_ref(scope))+ try:+ await manager.handle_request(scope, receive, send)+ finally:+ CHAT_SESSION_REF.reset(token)return app-__all__ = ["build_mcp_asgi_app"]+__all__ = ["build_mcp_asgi_app", "session_ref"]diff --git a/tests/unit/agent_chat/test_jarvis_identity.py b/tests/unit/agent_chat/test_jarvis_identity.pynew file mode 100644index 0000000000..68c2102684--- /dev/null+++ b/tests/unit/agent_chat/test_jarvis_identity.py@@ -0,0 +1,239 @@+"""A subscription CLI seat on the Jarvis surface runs AS Jarvis.++The identity (Jarvis' prompt layers + the chat's transcript + the addendum),+where each CLI takes it, the session header the MCP config carries, and the+tool server's approval surface for a request that names a chat.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++import pytest++from jarvis.agent_chat import jarvis_harness, runner_cli+from jarvis.agent_chat.events import make_event+from jarvis.core import runtime_refs+from jarvis.mcp import jarvis_tools_server as server+from jarvis.ui.web import mcp_server_routes+++class _Brain:+ def __init__(self, *, fail: bool = False) -> None:+ self.fail = fail+ self.asked_with: list[str] = []++ async def render_surface_prompt(self, *, user_text: str) -> tuple[str, str]:+ self.asked_with.append(user_text)+ if self.fail:+ raise RuntimeError("layers unavailable")+ return "YOU ARE GEORGE. Soul, persona, profile.", "Date: today. Awareness: quiet."++[email protected](autouse=True)+def _clean_refs():+ yield+ runtime_refs._reset_for_tests()+++def _history() -> list[dict[str, Any]]:+ return [+ make_event("user_message", {"text": "what did we decide?"}),+ make_event("turn_started", {"turn_id": "t0"}),+ make_event("assistant_text", {"turn_id": "t0", "text": "To ship on Friday."}),+ make_event("turn_finished", {"turn_id": "t0", "status": "done"}),+ ]+++# ------------------------------------------------------------ identity text+++async def test_identity_has_the_jarvis_layers_the_transcript_and_the_addendum(monkeypatch):+ brain = _Brain()+ monkeypatch.setattr(jarvis_harness, "_brain", lambda: brain)+ text = await jarvis_harness.identity_prompt(+ user_text="and now?", history=_history(), resume=None+ )+ assert text.index("YOU ARE GEORGE") < text.index("Date: today")+ assert "Person: what did we decide?" in text and "Jarvis: To ship on Friday." in text+ assert text.endswith(jarvis_harness.SYSTEM_PREAMBLE)+ assert brain.asked_with == ["and now?"], "the wiki context is pulled for THIS turn's text"+++async def test_a_resumed_conversation_carries_no_transcript(monkeypatch):+ monkeypatch.setattr(jarvis_harness, "_brain", lambda: _Brain())+ text = await jarvis_harness.identity_prompt(+ user_text="and now?", history=_history(), resume="vendor-session-1"+ )+ assert "This conversation so far" not in text+ assert "YOU ARE GEORGE" in text+++async def test_without_a_brain_the_addendum_stands_alone(monkeypatch):+ monkeypatch.setattr(jarvis_harness, "_brain", lambda: None)+ text = await jarvis_harness.identity_prompt(user_text="hi", history=[], resume=None)+ assert text == jarvis_harness.SYSTEM_PREAMBLE+++async def test_failing_layers_never_cost_the_turn(monkeypatch):+ monkeypatch.setattr(jarvis_harness, "_brain", lambda: _Brain(fail=True))+ text = await jarvis_harness.identity_prompt(user_text="hi", history=_history(), resume=None)+ assert text.endswith(jarvis_harness.SYSTEM_PREAMBLE) and "Person:" in text+++def test_the_compact_cut_keeps_the_addendum_whole():+ long_text = ("a line of soul\n" * 3000) + "\n\n" + jarvis_harness.SYSTEM_PREAMBLE+ compact = jarvis_harness.compact_identity(long_text, max_chars=4000)+ assert len(compact) <= 4100+ assert compact.endswith(jarvis_harness.SYSTEM_PREAMBLE)+ assert "…" in compact+++def test_the_identity_file_lives_in_the_app_data_dir_and_is_removed(monkeypatch, tmp_path: Path):+ monkeypatch.setattr(jarvis_harness, "identity_dir", lambda: tmp_path / "identity")+ path = jarvis_harness.write_identity_file("who I am", turn_id="turn-1")+ assert path.parent == tmp_path / "identity" and path.read_text(encoding="utf-8") == "who I am"+ jarvis_harness.remove_identity_file(path)+ assert not path.exists()+ jarvis_harness.remove_identity_file(path) # twice is fine+++# --------------------------------------------------------- what each CLI gets+++def _identity(tmp_path: Path) -> jarvis_harness.Identity:+ path = tmp_path / "id.md"+ path.write_text("FULL IDENTITY", encoding="utf-8")+ return jarvis_harness.Identity(+ session_id="sess-1", text="FULL IDENTITY", compact="SHORT IDENTITY", path=path+ )+++def test_claude_takes_the_identity_as_a_file_and_names_the_session(monkeypatch, tmp_path: Path):+ 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")+ plan = runner_cli.plan_claude(+ prompt="hi",+ cwd=tmp_path,+ model="",+ effort="",+ permission_mode="ask",+ resume=None,+ identity=_identity(tmp_path),+ )+ argv = plan.argv+ assert "--append-system-prompt-file" in argv+ assert argv[argv.index("--append-system-prompt-file") + 1] == str(tmp_path / "id.md")+ assert "--append-system-prompt" not in argv+ config = argv[argv.index("--mcp-config") + 1]+ assert jarvis_harness.HEADER_NAME in config and "sess-1" in config+ assert plan.stdin_text and "FULL IDENTITY" not in plan.stdin_text+++def test_claude_without_identity_spawns_exactly_as_before(monkeypatch, tmp_path: Path):+ 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")+ plan = runner_cli.plan_claude(+ prompt="hi", cwd=tmp_path, model="", effort="", permission_mode="ask", resume=None+ )+ assert "--append-system-prompt" in plan.argv+ assert "--append-system-prompt-file" not in plan.argv+ assert jarvis_harness.HEADER_NAME not in plan.argv[plan.argv.index("--mcp-config") + 1]+++def test_codex_gets_the_identity_on_stdin_and_the_session_header(monkeypatch, tmp_path: Path):+ monkeypatch.setattr(runner_cli, "codex_argv_prefix", lambda: ["codex"])+ monkeypatch.setattr(runner_cli, "read_codex_models", lambda: None)+ monkeypatch.setattr(runner_cli.jarvis_harness, "control_key", lambda: "k")+ runtime_refs.set_api_base_url("http://127.0.0.1:47821")+ plan = runner_cli.plan_codex(+ prompt="hi",+ cwd=tmp_path,+ model="",+ effort="",+ permission_mode="ask",+ resume=None,+ identity=_identity(tmp_path),+ )+ assert plan.stdin_text and plan.stdin_text.startswith("<jarvis_identity>\nFULL IDENTITY")+ assert plan.stdin_text.endswith("hi")+ joined = " ".join(plan.argv)+ assert "http_headers" in joined and "sess-1" in joined+ # A resumed conversation already knows who it is.+ resumed = runner_cli.plan_codex(+ prompt="hi",+ cwd=tmp_path,+ model="",+ effort="",+ permission_mode="ask",+ resume="thread-1",+ identity=_identity(tmp_path),+ )+ assert resumed.stdin_text == "hi"+++def test_grok_takes_the_compact_identity_on_argv(monkeypatch, tmp_path: Path):+ monkeypatch.setattr(runner_cli, "grok_argv_prefix", lambda: ["grok"])+ plan = runner_cli.plan_grok(+ prompt="hi",+ cwd=tmp_path,+ model="",+ effort="",+ permission_mode="ask",+ resume=None,+ identity=_identity(tmp_path),+ )+ prompt = plan.argv[plan.argv.index("-p") + 1]+ assert prompt.startswith("<jarvis_identity>\nSHORT IDENTITY") and prompt.endswith("hi")+++def test_agy_takes_the_identity_on_stdin(monkeypatch, tmp_path: Path):+ monkeypatch.setattr(runner_cli, "agy_argv_prefix", lambda: ["agy"])+ monkeypatch.setattr(runner_cli, "_agy_catalog_cached", lambda: None)+ plan = runner_cli.plan_agy(+ prompt="hi",+ cwd=tmp_path,+ model="",+ effort="",+ permission_mode="ask",+ resume=None,+ identity=_identity(tmp_path),+ )+ assert plan.stdin_text and plan.stdin_text.startswith("<jarvis_identity>\nFULL IDENTITY")+++# ------------------------------------------------------- the session header+++def test_the_mcp_route_reads_the_session_header_and_ignores_junk():+ scope = {"headers": [(b"x-jarvis-chat-session", b"0123abcd"), (b"authorization", b"Bearer k")]}+ assert mcp_server_routes.session_ref(scope) == "0123abcd"+ assert mcp_server_routes.session_ref({"headers": []}) is None+ assert mcp_server_routes.session_ref({"headers": [(b"x-jarvis-chat-session", b"../x")]}) is None+++def test_the_tool_server_names_the_chats_card_for_a_session_request():+ assert server.approval_snapshot() == {}+ token = server.CHAT_SESSION_REF.set("sess-9")+ try:+ snapshot = server.approval_snapshot()+ finally:+ server.CHAT_SESSION_REF.reset(token)+ assert snapshot["approval_surface"] == "interactive"+ assert snapshot["approval_ref"] == "agent-chat:sess-9"+ assert snapshot["approval_timeout_s"] == server.CHAT_APPROVAL_TIMEOUT_S+++def test_the_config_names_the_header_only_with_a_session(monkeypatch):+ monkeypatch.setattr(jarvis_harness, "control_key", lambda: "k")+ runtime_refs.set_api_base_url("http://127.0.0.1:47821")+ plain = jarvis_harness.mcp_config_json() or ""+ named = jarvis_harness.mcp_config_json("sess-2") or ""+ assert jarvis_harness.HEADER_NAME not in plain+ assert jarvis_harness.HEADER_NAME in named and "sess-2" in named+ assert "${JARVIS_CONTROL_API_KEY}" in named, "the key still travels by env, never in the config"+ assert not any("http_headers" in a for a in jarvis_harness.codex_config_args())+ assert any("http_headers" in a for a in jarvis_harness.codex_config_args("sess-2"))