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): file coding agents' sub-agents under their spawn call
rubenluetke10-beep87a2c454cf42
diff --git a/jarvis/agent_chat/events.py b/jarvis/agent_chat/events.pyindex d474e95e8a..9322e051f2 100644--- a/jarvis/agent_chat/events.py+++ b/jarvis/agent_chat/events.py@@ -34,14 +34,25 @@ Kinds (``payload`` keys in brackets):``question_resolved`` [turn_id, question_id, answers]``plan_ready`` [turn_id, build_mode] — a coding agent's plan card``plan_resolved`` [turn_id, decision] decision: build | keep+``subagent_started`` [turn_id, agent_id, description, agent_type, prompt, background,+ task_id?, thread_id?] — a coding agent spawned a sub-agent;+ ``agent_id`` is the spawning tool call's id+``subagent_progress`` [turn_id, agent_id, activity, last_tool, tokens?, tool_uses?,+ duration_ms?] — live only: what the sub-agent is doing now+``subagent_finished`` [turn_id, agent_id, status, summary?, tokens?, tool_uses?,+ duration_ms?] status: done | failed | stopped``turn_finished`` [turn_id, status, duration_ms, usage, error, cost_usd]status: done | cancelled | error``session_updated`` [title?, provider?, model?, effort?, cwd?, permission_mode?]``error`` [turn_id?, message]``notice`` [kind, ...] — a system line outside a turn-``text_delta`` / ``reasoning_delta`` / ``reasoning_started`` / ``usage_delta``-are the transient kinds: the finished block carries the whole text and the+A sub-agent's own text, thoughts and calls are the ordinary kinds with an+``agent_id`` in the payload: they belong to that sub-agent's conversation,+never to the main agent's answer.++``text_delta`` / ``reasoning_delta`` / ``reasoning_started`` / ``usage_delta`` /+``subagent_progress`` are the transient kinds: the finished block carries the whole text and the``turn_finished`` event the whole usage, so the log never stores token dust."""@@ -51,7 +62,7 @@ import timefrom typing import Any, FinalTRANSIENT_KINDS: Final[frozenset[str]] = frozenset(- {"text_delta", "reasoning_delta", "reasoning_started", "usage_delta"}+ {"text_delta", "reasoning_delta", "reasoning_started", "usage_delta", "subagent_progress"})diff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.pyindex ad92a10ad7..3bfe5de22c 100644--- a/jarvis/agent_chat/runner_cli.py+++ b/jarvis/agent_chat/runner_cli.py@@ -1431,6 +1431,12 @@ class _ClaudeState:#: Last tool_result that came back as an error — used when the CLI then#: aborts the turn instead of thinking again (Grok print-mode cancel).last_tool_error: str | None = None+ #: A sub-agent's own translator state, by the call that spawned it — its+ #: messages carry ``parent_tool_use_id`` and must never read as the main+ #: agent's words.+ agents: dict[str, _ClaudeState] = field(default_factory=dict)+ #: The CLI's task id -> the spawning call, for task updates that name only the task.+ agent_tasks: dict[str, str] = field(default_factory=dict)#: Streamed characters per estimated output token (English and code average).@@ -1544,6 +1550,134 @@ def _content_text(content: Any) -> str:return "" if content is None else str(content)+#: Claude Code's background-task lines; the agent ones become a sub-agent's card.+_CLAUDE_TASK_SUBTYPES: Final = frozenset(+ {"task_started", "task_progress", "task_updated", "task_notification"}+)+++def subagent_status(raw: str) -> str:+ """A vendor's word for how a sub-agent ended, as ``done`` | ``failed`` | ``stopped``."""+ word = raw.strip().lower()+ if word in {"completed", "complete", "done", "success", "succeeded"}:+ return "done"+ if word in {"failed", "error", "errored"}:+ return "failed"+ return "stopped"+++def _task_usage(obj: dict[str, Any]) -> dict[str, int]:+ usage = obj.get("usage")+ if not isinstance(usage, dict):+ return {}+ keys = {"total_tokens": "tokens", "tool_uses": "tool_uses", "duration_ms": "duration_ms"}+ return {+ ours: int(usage[theirs])+ for theirs, ours in keys.items()+ if isinstance(usage.get(theirs), int | float)+ }+++def _claude_subagent_line(+ obj: dict[str, Any], st: _ClaudeState, parent: str+) -> list[dict[str, Any]]:+ """A sub-agent's own message, filed under the call that spawned it.++ The CLI streams a sub-agent's turns on the parent's stdout, marked only by+ ``parent_tool_use_id``. Each sub-agent gets a translator state of its own,+ so its text, thoughts and calls never merge into the main agent's answer,+ and every event it yields names the agent (``agent_id``). Its partial+ stream and token counts stay out: the finished messages carry the words,+ and the live counter is the main agent's.+ """+ if str(obj.get("type") or "") not in {"assistant", "user"}:+ return []+ child = st.agents.get(parent)+ if child is None:+ child = st.agents[parent] = _ClaudeState(turn_id=st.turn_id)+ out: list[dict[str, Any]] = []+ for event in translate_claude_line({**obj, "parent_tool_use_id": None}, child):+ if event["kind"] == "usage_delta":+ continue+ event["payload"]["agent_id"] = parent+ out.append(event)+ return out+++def _claude_task_events(obj: dict[str, Any], st: _ClaudeState) -> list[dict[str, Any]]:+ """A sub-agent's life from Claude Code's task lines: started, working, finished.++ Background shell commands are tasks too; only agent tasks get a card.+ """+ subtype = str(obj.get("subtype") or "")+ if subtype not in _CLAUDE_TASK_SUBTYPES:+ return []+ task_id = str(obj.get("task_id") or "")+ if subtype == "task_started":+ call_id = str(obj.get("tool_use_id") or "")+ task_type = str(obj.get("task_type") or "")+ if not call_id or not (obj.get("subagent_type") or "agent" in task_type):+ return []+ if task_id:+ st.agent_tasks[task_id] = call_id+ return [+ make_event(+ "subagent_started",+ {+ "turn_id": st.turn_id,+ "agent_id": call_id,+ "task_id": task_id,+ "description": str(obj.get("description") or ""),+ "agent_type": str(obj.get("subagent_type") or ""),+ "prompt": str(obj.get("prompt") or ""),+ "background": bool(obj.get("is_backgrounded")),+ },+ )+ ]+ call_id = st.agent_tasks.get(task_id) or ""+ if not call_id:+ named = str(obj.get("tool_use_id") or "")+ call_id = named if named in st.agents else ""+ if not call_id:+ return []+ if subtype == "task_progress":+ return [+ make_event(+ "subagent_progress",+ {+ "turn_id": st.turn_id,+ "agent_id": call_id,+ "activity": str(obj.get("description") or ""),+ "last_tool": str(obj.get("last_tool_name") or ""),+ **_task_usage(obj),+ },+ )+ ]+ if subtype == "task_updated":+ patch = obj.get("patch") if isinstance(obj.get("patch"), dict) else {}+ status = str(patch.get("status") or "")+ if status in {"", "running", "pending"}:+ return []+ return [+ make_event(+ "subagent_finished",+ {"turn_id": st.turn_id, "agent_id": call_id, "status": subagent_status(status)},+ )+ ]+ return [+ make_event(+ "subagent_finished",+ {+ "turn_id": st.turn_id,+ "agent_id": call_id,+ "status": subagent_status(str(obj.get("status") or "completed")),+ "summary": str(obj.get("summary") or ""),+ **_task_usage(obj),+ },+ )+ ]++def translate_claude_line(obj: dict[str, Any], st: _ClaudeState) -> list[dict[str, Any]]:"""One Claude-shaped NDJSON object -> zero or more agent-chat events."""out: list[dict[str, Any]] = []@@ -1552,8 +1686,14 @@ def translate_claude_line(obj: dict[str, Any], st: _ClaudeState) -> list[dict[stif sid and not st.vendor_session:st.vendor_session = str(sid)+ parent = obj.get("parent_tool_use_id")+ if parent:+ return _claude_subagent_line(obj, st, str(parent))+if kind == "system":- return out # init / hooks / status — nothing the timeline shows+ # init / hooks / status are nothing the timeline shows; a sub-agent's+ # life (started, working, finished) is.+ return _claude_task_events(obj, st)if kind == "stream_event":ev = obj.get("event") or {}@@ -1816,6 +1956,105 @@ class _CodexState:#: The last top-level ``error`` notification (retryable until turn.failed).last_error: str | None = Nonefailed_tools: set[str] = field(default_factory=set)+ #: A sub-agent's thread id -> the ``spawn_agent`` call that started it.+ agents: dict[str, str] = field(default_factory=dict)+ #: Sub-agents whose end was already told, so a later ``close_agent`` that+ #: reports them shut down does not turn a finished agent into a stopped one.+ agents_ended: set[str] = field(default_factory=set)+++#: Codex's word for a sub-agent that is still working.+_CODEX_AGENT_LIVE: Final = frozenset({"pending_init", "running"})+++def _codex_collab_events(item: dict[str, Any], phase: str, st: _CodexState) -> list[dict[str, Any]]:+ """Codex's multi-agent calls (``collab_tool_call``) as sub-agent cards.++ ``spawn_agent`` becomes the card's call; the agent's thread id is+ remembered, so every later call that reports ``agents_states`` (``wait``,+ ``send_input``, ``close_agent``) updates that card. ``codex exec`` does not+ stream a sub-agent's own steps — the card carries its task and its answer.+ """+ out: list[dict[str, Any]] = []+ item_id = str(item.get("id") or uuid.uuid4().hex)+ tool = str(item.get("tool") or "agent")+ prompt = str(item.get("prompt") or "")+ receivers = [str(t) for t in item.get("receiver_thread_ids") or [] if t]+ states = item.get("agents_states") if isinstance(item.get("agents_states"), dict) else {}+ if item_id not in st.items:+ st.items[item_id] = (item_id, tool)+ st.started_at[item_id] = time.perf_counter()+ summary = prompt.strip().splitlines()[0][:200] if prompt.strip() else ""+ args: dict[str, Any] = {"prompt": prompt} if prompt else {}+ if tool != "spawn_agent" and receivers:+ args["agents"] = receivers+ out.append(+ make_event(+ "tool_call",+ {+ "turn_id": st.turn_id,+ "call_id": item_id,+ "name": tool,+ "input": args,+ "summary": summary,+ },+ )+ )+ if tool == "spawn_agent":+ for thread_id in receivers:+ if thread_id in st.agents:+ continue+ st.agents[thread_id] = item_id+ out.append(+ make_event(+ "subagent_started",+ {+ "turn_id": st.turn_id,+ "agent_id": item_id,+ "thread_id": thread_id,+ "description": prompt.strip().splitlines()[0][:120] if prompt else "",+ "agent_type": "",+ "prompt": prompt,+ "background": True,+ },+ )+ )+ for thread_id, raw in states.items():+ agent_id = st.agents.get(str(thread_id))+ state = raw if isinstance(raw, dict) else {}+ status = str(state.get("status") or "")+ if not agent_id or not status or status in _CODEX_AGENT_LIVE:+ continue+ if status in {"shutdown", "not_found"} and agent_id in st.agents_ended:+ continue+ st.agents_ended.add(agent_id)+ out.append(+ make_event(+ "subagent_finished",+ {+ "turn_id": st.turn_id,+ "agent_id": agent_id,+ "status": subagent_status(status),+ "summary": str(state.get("message") or ""),+ },+ )+ )+ if phase == "completed":+ started = st.started_at.get(item_id)+ failed = str(item.get("status") or "") == "failed"+ out.append(+ make_event(+ "tool_result",+ {+ "turn_id": st.turn_id,+ "call_id": item_id,+ "output": ", ".join(receivers) if tool == "spawn_agent" else "done",+ "is_error": failed,+ "duration_ms": int((time.perf_counter() - started) * 1000) if started else None,+ },+ )+ )+ return outdef translate_codex_line(obj: dict[str, Any], st: _CodexState) -> list[dict[str, Any]]:@@ -1898,6 +2137,8 @@ def translate_codex_line(obj: dict[str, Any], st: _CodexState) -> list[dict[str,))return out+ if itype == "collab_tool_call":+ return _codex_collab_events(item, phase, st)if itype in {"command_execution", "file_change", "mcp_tool_call", "web_search"}:if itype == "command_execution":name, args = "RunCommand", {"command": str(item.get("command") or "")}diff --git a/jarvis/agent_chat/subagent_transcripts.py b/jarvis/agent_chat/subagent_transcripts.pynew file mode 100644index 0000000000..918150cb40--- /dev/null+++ b/jarvis/agent_chat/subagent_transcripts.py@@ -0,0 +1,342 @@+"""A coding agent's sub-agents, read from the CLI's own session files.++``codex exec --json`` streams the main agent only: a sub-agent's steps never+reach the thread's stream. Codex files each sub-agent as a rollout of its own,+whose first line (``session_meta``) names the thread that spawned it+(``parent_thread_id``) and the line its own work starts at+(``subagent_history_start_ordinal`` — everything before is the parent's context,+copied in). Read from there, a sub-agent's rollout is its conversation: its+words, its thoughts' summaries and its tool calls with their results.++Every event this returns speaks the agent-chat vocabulary+(``jarvis/agent_chat/events.py``), so the thread folds it with the same reducer+as everything else. Nothing here is OS-specific: paths come from ``pathlib`` and+the CLI's own ``CODEX_HOME``.+"""++from __future__ import annotations++import json+import logging+import os+import re+from collections.abc import Iterable, Iterator+from dataclasses import dataclass, field+from datetime import UTC, datetime, timedelta+from pathlib import Path+from typing import Any, Final++from jarvis.agent_chat.events import make_event++log = logging.getLogger(__name__)++#: A Codex thread id as it appears in a rollout file name.+_THREAD_ID: Final = re.compile(r"^[0-9a-fA-F-]{16,64}$")+#: How many sub-agent levels are followed below the main agent.+_MAX_DEPTH: Final = 4+#: The most rollout files one lookup opens, so a heavy Codex history stays cheap.+_MAX_FILES: Final = 400+#: The longest tool output a step keeps; the thread shows a preview anyway.+_MAX_OUTPUT: Final = 8000+++@dataclass(slots=True)+class CodexSubagent:+ thread_id: str+ parent_thread_id: str+ nickname: str = ""+ role: str = ""+ path: str = ""+ started_ms: int = 0+ updated_ms: int = 0+ status: str = "running"+ summary: str = ""+ events: list[dict[str, Any]] = field(default_factory=list)++ def to_dict(self) -> dict[str, Any]:+ return {+ "thread_id": self.thread_id,+ "parent_thread_id": self.parent_thread_id,+ "nickname": self.nickname,+ "role": self.role,+ "path": self.path,+ "started_ms": self.started_ms,+ "updated_ms": self.updated_ms,+ "status": self.status,+ "summary": self.summary,+ "events": self.events,+ }+++def codex_homes(account_id: str | None = None) -> list[Path]:+ """Every CODEX_HOME a thread's sub-agents may live in: its seat's first."""+ homes: list[Path] = []+ try:+ from jarvis import agent_accounts++ if account_id:+ homes.append(agent_accounts.config_dir_for("codex", account_id)) # type: ignore[arg-type]+ homes.extend(+ agent_accounts.config_dir_for("codex", account.id) # type: ignore[arg-type]+ for account in agent_accounts.list_accounts("codex") # type: ignore[arg-type]+ )+ except Exception as exc: # noqa: BLE001 - the default home below still answers; logged+ log.debug("codex account homes unavailable: %s", type(exc).__name__)+ raw = os.environ.get("CODEX_HOME")+ if raw:+ homes.append(Path(raw).expanduser())+ homes.append(Path.home() / ".codex")+ unique: list[Path] = []+ for home in homes:+ if home not in unique:+ unique.append(home)+ return unique+++def _ms(value: Any) -> int:+ if not isinstance(value, str) or not value:+ return 0+ text = value[:-1] + "+00:00" if value.endswith(("Z", "z")) else value+ try:+ parsed = datetime.fromisoformat(text)+ except ValueError:+ return 0+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=UTC)+ return int(parsed.timestamp() * 1000)+++def _rollouts_since(homes: Iterable[Path], since_ms: int) -> Iterator[Path]:+ """Rollout files from the day before ``since_ms`` onward, newest day first."""+ start = datetime.fromtimestamp(max(0, since_ms) / 1000, UTC).date() - timedelta(days=1)+ today = datetime.now(UTC).date() + timedelta(days=1)+ days: list[Any] = []+ day = today+ while day >= start and len(days) < 60:+ days.append(day)+ day -= timedelta(days=1)+ opened = 0+ for home in homes:+ for day in days:+ folder = home / "sessions" / f"{day.year:04d}" / f"{day.month:02d}" / f"{day.day:02d}"+ if not folder.is_dir():+ continue+ for path in sorted(folder.glob("rollout-*.jsonl")):+ opened += 1+ if opened > _MAX_FILES:+ return+ yield path+++def _first_line(path: Path) -> dict[str, Any] | None:+ try:+ with path.open("r", encoding="utf-8", errors="replace") as handle:+ line = handle.readline()+ except OSError as exc:+ log.debug("codex rollout unreadable %s: %s", path.name, exc)+ return None+ try:+ obj = json.loads(line)+ except ValueError:+ return None+ return obj if isinstance(obj, dict) and obj.get("type") == "session_meta" else None+++def _text_parts(content: Any, *kinds: str) -> str:+ if isinstance(content, str):+ return content+ if not isinstance(content, list):+ return ""+ parts = [+ str(part.get("text") or "")+ for part in content+ if isinstance(part, dict) and part.get("type") in kinds+ ]+ return "\n".join(part for part in parts if part)+++def _arguments(raw: Any) -> dict[str, Any]:+ if isinstance(raw, dict):+ return raw+ if isinstance(raw, str):+ try:+ parsed = json.loads(raw)+ except ValueError:+ return {"input": raw}+ return parsed if isinstance(parsed, dict) else {"input": parsed}+ return {}+++def _call(name: str, args: dict[str, Any]) -> tuple[str, dict[str, Any]]:+ """A Codex tool as the thread names it: shell commands read like the stream's."""+ if name in {"exec_command", "shell", "shell_command", "local_shell"}:+ command = args.get("cmd", args.get("command", ""))+ if isinstance(command, list):+ command = " ".join(str(part) for part in command)+ return "RunCommand", {"command": str(command)}+ return name, args+++def _step_events(obj: dict[str, Any], seen: set[str]) -> list[dict[str, Any]]:+ payload = obj.get("payload") if isinstance(obj.get("payload"), dict) else {}+ kind = str(payload.get("type") or "")+ item_id = str(payload.get("id") or payload.get("call_id") or "")+ out: list[dict[str, Any]] = []+ if kind == "message" and payload.get("role") == "assistant":+ text = _text_parts(payload.get("content"), "output_text", "text")+ if text.strip():+ out.append(make_event("assistant_text", {"message_id": item_id, "text": text}))+ elif kind == "reasoning":+ summary = _text_parts(payload.get("summary"), "summary_text")+ if summary.strip():+ out.append(+ make_event(+ "reasoning", {"message_id": item_id, "text": summary, "duration_ms": None}+ )+ )+ elif kind in {"function_call", "custom_tool_call"}:+ call_id = str(payload.get("call_id") or item_id)+ if not call_id or call_id in seen:+ return out+ seen.add(call_id)+ raw_name = str(payload.get("name") or "tool")+ args = (+ _arguments(payload.get("arguments"))+ if kind == "function_call"+ else {"patch" if raw_name == "apply_patch" else "input": payload.get("input")}+ )+ name, args = _call(raw_name, args)+ out.append(make_event("tool_call", {"call_id": call_id, "name": name, "input": args}))+ elif kind in {"function_call_output", "custom_tool_call_output"}:+ output = payload.get("output")+ text = (+ output+ if isinstance(output, str)+ else _text_parts(output, "input_text", "output_text", "text")+ )+ if isinstance(output, dict):+ text = str(output.get("content") or output.get("output") or "")+ out.append(+ make_event(+ "tool_result",+ {+ "call_id": str(payload.get("call_id") or ""),+ "output": text[:_MAX_OUTPUT],+ "is_error": False,+ "duration_ms": None,+ },+ )+ )+ elif kind == "web_search_call":+ action = payload.get("action") if isinstance(payload.get("action"), dict) else {}+ out.append(+ make_event(+ "tool_call",+ {+ "call_id": item_id,+ "name": "WebSearch",+ "input": {"query": str(action.get("query") or "")},+ },+ )+ )+ out.append(+ make_event("tool_result", {"call_id": item_id, "output": "done", "is_error": False})+ )+ stamp = _ms(obj.get("timestamp"))+ for event in out:+ if stamp:+ event["ts_ms"] = stamp+ return out+++def read_codex_subagent(path: Path, meta: dict[str, Any]) -> CodexSubagent:+ """One sub-agent's own conversation and how it stands, from its rollout."""+ payload = meta.get("payload") if isinstance(meta.get("payload"), dict) else {}+ agent = CodexSubagent(+ thread_id=str(payload.get("id") or ""),+ parent_thread_id=str(payload.get("parent_thread_id") or ""),+ nickname=str(payload.get("agent_nickname") or ""),+ role=str(payload.get("agent_role") or ""),+ path=str(payload.get("agent_path") or ""),+ started_ms=_ms(payload.get("timestamp")) or _ms(meta.get("timestamp")),+ )+ try:+ start = int(payload.get("subagent_history_start_ordinal") or 0)+ except (TypeError, ValueError):+ start = 0+ seen: set[str] = set()+ last_text = ""+ status = "running"+ try:+ handle = path.open("r", encoding="utf-8", errors="replace")+ except OSError as exc:+ log.debug("codex rollout unreadable %s: %s", path.name, exc)+ return agent+ with handle:+ for index, line in enumerate(handle):+ if index == 0 or not line.strip():+ continue+ try:+ obj = json.loads(line)+ except ValueError:+ continue+ if not isinstance(obj, dict):+ continue+ ordinal = obj.get("ordinal")+ if isinstance(ordinal, int) and ordinal < start:+ continue+ agent.updated_ms = max(agent.updated_ms, _ms(obj.get("timestamp")))+ if obj.get("type") == "event_msg":+ event = obj.get("payload") if isinstance(obj.get("payload"), dict) else {}+ etype = str(event.get("type") or "")+ if etype == "task_started":+ status = "running"+ elif etype == "task_complete":+ status = "done"+ message = event.get("last_agent_message")+ if isinstance(message, str) and message.strip():+ last_text = message+ elif etype == "turn_aborted":+ status = "stopped"+ elif etype == "error":+ status = "failed"+ last_text = str(event.get("message") or last_text)+ continue+ if obj.get("type") != "response_item":+ continue+ for event in _step_events(obj, seen):+ if event["kind"] == "assistant_text":+ last_text = str(event["payload"]["text"])+ agent.events.append(event)+ agent.status = status+ agent.summary = last_text+ return agent+++def codex_subagents(+ parent_thread_id: str, *, since_ms: int, homes: list[Path] | None = None+) -> list[CodexSubagent]:+ """Every sub-agent below ``parent_thread_id``, nested ones after their parent."""+ if not _THREAD_ID.match(parent_thread_id or ""):+ return []+ children: dict[str, list[tuple[Path, dict[str, Any]]]] = {}+ for path in _rollouts_since(homes if homes is not None else codex_homes(), since_ms):+ meta = _first_line(path)+ payload = meta.get("payload") if meta and isinstance(meta.get("payload"), dict) else None+ if not payload or payload.get("thread_source") not in (None, "subagent"):+ continue+ parent = str(payload.get("parent_thread_id") or "")+ if parent and payload.get("id"):+ children.setdefault(parent, []).append((path, meta)) # type: ignore[arg-type]+ out: list[CodexSubagent] = []++ def walk(thread_id: str, depth: int) -> None:+ if depth > _MAX_DEPTH:+ return+ for path, meta in sorted(children.get(thread_id, []), key=lambda row: row[0].name):+ agent = read_codex_subagent(path, meta)+ out.append(agent)+ walk(agent.thread_id, depth + 1)++ walk(parent_thread_id, 0)+ return outdiff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.pyindex b1f13e113b..f9b4e7d8c8 100644--- a/jarvis/ui/web/agent_chat_routes.py+++ b/jarvis/ui/web/agent_chat_routes.py@@ -985,6 +985,34 @@ def get_session(return {"session": d, "events": svc.store.list_events(session_id, tail=tail)}+ "/sessions/{session_id}/subagents",+ summary="The sub-agents a coding agent spawned, read from the CLI's own session files",+ openapi_extra={"x-jarvis-readonly": True},+)+async def list_subagents(session_id: str, request: Request) -> dict[str, Any]:+ """A thread's sub-agents whose steps the CLI does not stream (Codex).++ Claude Code streams its sub-agents into the thread itself; Codex files each+ one as a rollout of its own. ``agents`` is empty for every other CLI.+ """+ from jarvis.agent_chat.subagent_transcripts import codex_homes, codex_subagents++ svc = _service(request)+ session = svc.store.get_session(session_id)+ if session is None:+ raise HTTPException(status_code=404, detail="session not found")+ runner = resolve_runner(session.provider, surface=session.surface, runtime=session.runtime)+ if runner != "codex-cli" or not session.vendor_session:+ return {"agents": []}+ parent, since, account = session.vendor_session, session.created_ms, session.account_id+ # Reading rollouts is file work: off the event loop.+ agents = await asyncio.to_thread(+ lambda: codex_subagents(parent, since_ms=since, homes=codex_homes(account or None))+ )+ return {"agents": [agent.to_dict() for agent in agents]}++@router.patch("/sessions/{session_id}")async def patch_session(session_id: str, body: PatchSessionBody, request: Request@@ -1161,6 +1189,15 @@ async def cancel_turn(session_id: str, request: Request) -> dict[str, Any]:raise HTTPException(status_code=404, detail="session not found")session = svc.store.get_session(session_id)cancelled = svc.is_running(session_id)+ # Who ended a turn is otherwise invisible: name the control that asked.+ headers = request.headers+ log.info(+ "agent chat %s: stop requested over HTTP (via=%s, running=%s, fetch-site=%s)",+ session_id,+ (headers.get("x-jarvis-stop-via") or "unnamed")[:40],+ cancelled,+ (headers.get("sec-fetch-site") or "none")[:20],+ )if session.surface in ("jarvis", "society"):await svc.controls.pause(session_id, "Stopped by the user")else:diff --git a/tests/unit/agent_chat/test_subagent_transcripts.py b/tests/unit/agent_chat/test_subagent_transcripts.pynew file mode 100644index 0000000000..86b215d1eb--- /dev/null+++ b/tests/unit/agent_chat/test_subagent_transcripts.py@@ -0,0 +1,173 @@+"""Codex sub-agents read from their own rollout files."""++from __future__ import annotations++import json+from datetime import UTC, datetime+from pathlib import Path+from typing import Any++from jarvis.agent_chat.subagent_transcripts import codex_subagents++PARENT = "01a0debc-8389-7101-baa5-462e6e90a3c4"+CHILD = "01a0debd-5013-7810-9557-0fe75ec805fc"+GRANDCHILD = "01a0debf-1111-7810-9557-0fe75ec805fc"+OTHER = "01a0dec0-2222-7810-9557-0fe75ec805fc"+++def _meta(thread: str, parent: str, *, start: int, path: str) -> dict[str, Any]:+ return {+ "timestamp": "2026-09-26T17:22:24.088Z",+ "ordinal": 0,+ "type": "session_meta",+ "payload": {+ "id": thread,+ "parent_thread_id": parent,+ "timestamp": "2026-09-26T17:22:24.088Z",+ "thread_source": "subagent",+ "agent_nickname": "Heisenberg",+ "agent_role": "default",+ "agent_path": path,+ "subagent_history_start_ordinal": str(start),+ },+ }+++def _item(ordinal: int, payload: dict[str, Any], kind: str = "response_item") -> dict[str, Any]:+ return {+ "timestamp": "2026-09-26T17:22:30.000Z",+ "ordinal": ordinal,+ "type": kind,+ "payload": payload,+ }+++def _write(home: Path, thread: str, lines: list[dict[str, Any]], day: str = "2026/09/26") -> None:+ folder = home / "sessions" / Path(day)+ folder.mkdir(parents=True, exist_ok=True)+ body = "\n".join(json.dumps(line) for line in lines) + "\n"+ (folder / f"rollout-2026-09-26T19-22-24-{thread}.jsonl").write_text(body, encoding="utf-8")+++def _child_lines() -> list[dict[str, Any]]:+ return [+ _meta(CHILD, PARENT, start=3, path="/root/research"),+ # Before the start ordinal: the parent's context, copied in — never shown.+ _item(+ 1,+ {+ "type": "message",+ "role": "assistant",+ "content": [{"type": "output_text", "text": "PARENT WORDS"}],+ },+ ),+ _item(3, {"type": "task_started"}, kind="event_msg"),+ _item(+ 4,+ {+ "type": "reasoning",+ "id": "rs1",+ "summary": [{"type": "summary_text", "text": "**Reading the docs**"}],+ },+ ),+ _item(+ 5,+ {+ "type": "function_call",+ "name": "exec_command",+ "call_id": "c1",+ "arguments": json.dumps({"cmd": "ls -la"}),+ },+ ),+ _item(6, {"type": "function_call_output", "call_id": "c1", "output": "total 0"}),+ _item(+ 7,+ {+ "type": "message",+ "id": "m1",+ "role": "assistant",+ "content": [{"type": "output_text", "text": "Found nothing."}],+ },+ ),+ _item(+ 8, {"type": "task_complete", "last_agent_message": "Found nothing."}, kind="event_msg"+ ),+ ]+++def test_reads_a_subagents_own_steps_from_its_rollout(tmp_path: Path) -> None:+ _write(tmp_path, CHILD, _child_lines())+ agents = codex_subagents(PARENT, since_ms=1790443000000, homes=[tmp_path])+ assert len(agents) == 1+ agent = agents[0]+ assert (agent.thread_id, agent.parent_thread_id, agent.nickname, agent.path) == (+ CHILD,+ PARENT,+ "Heisenberg",+ "/root/research",+ )+ assert agent.status == "done"+ assert agent.summary == "Found nothing."+ kinds = [+ (ev["kind"], ev["payload"].get("name") or ev["payload"].get("text")) for ev in agent.events+ ]+ assert kinds == [+ ("reasoning", "**Reading the docs**"),+ ("tool_call", "RunCommand"),+ ("tool_result", None),+ ("assistant_text", "Found nothing."),+ ]+ assert agent.events[1]["payload"]["input"] == {"command": "ls -la"}+ assert "PARENT WORDS" not in json.dumps(agent.events)+++def test_follows_nested_subagents_and_skips_strangers(tmp_path: Path) -> None:+ _write(tmp_path, CHILD, _child_lines())+ _write(+ tmp_path,+ GRANDCHILD,+ [+ _meta(GRANDCHILD, CHILD, start=1, path="/root/research/tests"),+ _item(1, {"type": "task_started"}, kind="event_msg"),+ ],+ )+ _write(+ tmp_path,+ OTHER,+ [_meta(OTHER, "01a0ffff-0000-7810-9557-0fe75ec805fc", start=1, path="/root/x")],+ )+ agents = codex_subagents(PARENT, since_ms=1790443000000, homes=[tmp_path])+ assert [(a.thread_id, a.status) for a in agents] == [(CHILD, "done"), (GRANDCHILD, "running")]+++def test_refuses_a_thread_id_that_is_no_id(tmp_path: Path) -> None:+ assert codex_subagents("../../etc", since_ms=0, homes=[tmp_path]) == []+++def test_route_lists_a_codex_threads_subagents(tmp_path: Path, monkeypatch) -> None:+ from fastapi import FastAPI+ from fastapi.testclient import TestClient++ from jarvis.agent_chat import subagent_transcripts+ from jarvis.agent_chat.service import AgentChatService+ from jarvis.agent_chat.store import AgentChatStore+ from jarvis.ui.web.agent_chat_routes import router++ # The thread was created just now; its sub-agent's rollout is filed under today.+ _write(tmp_path, CHILD, _child_lines(), day=datetime.now(UTC).strftime("%Y/%m/%d"))+ monkeypatch.setattr(subagent_transcripts, "codex_homes", lambda account_id=None: [tmp_path])+ svc = AgentChatService(AgentChatStore(":memory:"))+ codex = svc.create_session(provider="openai-codex", cwd=str(tmp_path), surface="agent")+ svc.store.update_session(codex.session_id, vendor_session=PARENT)+ claude = svc.create_session(provider="claude-api", cwd=str(tmp_path), surface="agent")+ app = FastAPI()+ app.include_router(router)+ app.state.agent_chat = svc+ with TestClient(app) as client:+ body = client.get(f"/api/agent-chat/sessions/{codex.session_id}/subagents").json()+ assert [agent["thread_id"] for agent in body["agents"]] == [CHILD]+ assert body["agents"][0]["status"] == "done"+ # Claude Code streams its sub-agents; nothing to read from files.+ other = client.get(f"/api/agent-chat/sessions/{claude.session_id}/subagents").json()+ assert other == {"agents": []}+ assert client.get("/api/agent-chat/sessions/nope/subagents").status_code == 404diff --git a/tests/unit/agent_chat/test_subagent_translation.py b/tests/unit/agent_chat/test_subagent_translation.pynew file mode 100644index 0000000000..56e251070b--- /dev/null+++ b/tests/unit/agent_chat/test_subagent_translation.py@@ -0,0 +1,232 @@+"""Sub-agents in a coding agent's stream: their own conversation, never the main answer.++The Claude lines are trimmed from a real ``claude -p --output-format stream-json``+run (Claude Code 2.1) that spawned one background agent; the Codex items follow+the ``collab_tool_call`` shape of ``codex exec --json``.+"""++from __future__ import annotations++from typing import Any++from jarvis.agent_chat.events import is_transient+from jarvis.agent_chat.runner_cli import (+ _ClaudeState,+ _CodexState,+ subagent_status,+ translate_claude_line,+ translate_codex_line,+)++SPAWN = "toolu_spawn"+TASK = "a73c1e05f008ad14"+++def _assistant(+ content: list[dict[str, Any]], *, mid: str, parent: str | None = None+) -> dict[str, Any]:+ return {+ "type": "assistant",+ "message": {"id": mid, "role": "assistant", "content": content},+ "parent_tool_use_id": parent,+ "session_id": "s1",+ }+++def _tool_result(call_id: str, text: str, *, parent: str | None = None) -> dict[str, Any]:+ return {+ "type": "user",+ "message": {+ "role": "user",+ "content": [{"type": "tool_result", "tool_use_id": call_id, "content": text}],+ },+ "parent_tool_use_id": parent,+ "session_id": "s1",+ }+++CLAUDE_LINES: list[dict[str, Any]] = [+ _assistant(+ [+ {+ "type": "tool_use",+ "id": SPAWN,+ "name": "Agent",+ "input": {+ "description": "Count files",+ "prompt": "Run echo",+ "run_in_background": True,+ },+ }+ ],+ mid="m1",+ ),+ {+ "type": "system",+ "subtype": "task_started",+ "task_id": TASK,+ "tool_use_id": SPAWN,+ "description": "Count files",+ "subagent_type": "general-purpose",+ "is_backgrounded": True,+ "task_type": "local_agent",+ "prompt": "Run echo",+ },+ _tool_result(SPAWN, "Async agent launched successfully."),+ _assistant(+ [{"type": "tool_use", "id": "toolu_bash", "name": "Bash", "input": {"command": "echo hi"}}],+ mid="sub1",+ parent=SPAWN,+ ),+ {+ "type": "system",+ "subtype": "task_progress",+ "task_id": TASK,+ "tool_use_id": SPAWN,+ "description": "Running echo",+ "usage": {"total_tokens": 23416, "tool_uses": 1, "duration_ms": 2265},+ "last_tool_name": "Bash",+ },+ _tool_result("toolu_bash", "hi", parent=SPAWN),+ _assistant([{"type": "text", "text": "hi"}], mid="sub2", parent=SPAWN),+ {+ "type": "system",+ "subtype": "task_notification",+ "task_id": TASK,+ "tool_use_id": SPAWN,+ "status": "completed",+ "summary": "hi",+ "usage": {"total_tokens": 25617, "tool_uses": 1, "duration_ms": 5509},+ },+ _assistant([{"type": "text", "text": "The agent said hi."}], mid="m2"),+]+++def _claude_events() -> list[dict[str, Any]]:+ st = _ClaudeState(turn_id="t1")+ return [ev for line in CLAUDE_LINES for ev in translate_claude_line(line, st)]+++def test_claude_subagent_messages_are_filed_under_their_spawn_call() -> None:+ events = _claude_events()+ sub = [ev for ev in events if ev["payload"].get("agent_id") == SPAWN]+ kinds = [ev["kind"] for ev in sub]+ assert kinds == [+ "subagent_started",+ "tool_call",+ "subagent_progress",+ "tool_result",+ "assistant_text",+ "subagent_finished",+ ]+ started = sub[0]["payload"]+ assert started["description"] == "Count files"+ assert started["agent_type"] == "general-purpose"+ assert started["background"] is True+ finished = sub[-1]["payload"]+ assert finished["status"] == "done"+ assert finished["summary"] == "hi"+ assert finished["tokens"] == 25617+ assert finished["tool_uses"] == 1+++def test_claude_subagent_text_never_reads_as_the_main_answer() -> None:+ main_text = [+ ev["payload"]["text"]+ for ev in _claude_events()+ if ev["kind"] == "assistant_text" and "agent_id" not in ev["payload"]+ ]+ assert main_text == ["The agent said hi."]+++def test_claude_background_shell_task_gets_no_agent_card() -> None:+ st = _ClaudeState(turn_id="t1")+ line = {+ "type": "system",+ "subtype": "task_started",+ "task_id": "b1",+ "tool_use_id": "toolu_shell",+ "description": "sleep 8",+ "task_type": "local_bash",+ }+ assert translate_claude_line(line, st) == []+ done = {+ "type": "system",+ "subtype": "task_notification",+ "task_id": "b1",+ "status": "completed",+ }+ assert translate_claude_line(done, st) == []+++def test_subagent_progress_is_live_only() -> None:+ progress = [ev for ev in _claude_events() if ev["kind"] == "subagent_progress"]+ assert progress and all(is_transient(ev) for ev in progress)+ assert not any(is_transient(ev) for ev in _claude_events() if ev["kind"] == "subagent_finished")+++def test_subagent_status_words() -> None:+ assert subagent_status("completed") == "done"+ assert subagent_status("errored") == "failed"+ assert subagent_status("killed") == "stopped"+ assert subagent_status("interrupted") == "stopped"+++def _collab(phase: str, item: dict[str, Any]) -> dict[str, Any]:+ return {"type": f"item.{phase}", "item": {"type": "collab_tool_call", **item}}+++def test_codex_spawn_and_wait_become_one_agent_card() -> None:+ st = _CodexState(turn_id="t1")+ spawn = {+ "id": "item_3",+ "tool": "spawn_agent",+ "sender_thread_id": "root",+ "receiver_thread_ids": [],+ "prompt": "Reply with PONG",+ "agents_states": {},+ "status": "in_progress",+ }+ events = translate_codex_line(_collab("started", spawn), st)+ events += translate_codex_line(+ _collab("completed", {**spawn, "receiver_thread_ids": ["child-1"], "status": "completed"}),+ st,+ )+ wait = {+ "id": "item_4",+ "tool": "wait",+ "sender_thread_id": "root",+ "receiver_thread_ids": ["child-1"],+ "prompt": None,+ "agents_states": {"child-1": {"status": "completed", "message": "PONG"}},+ "status": "completed",+ }+ events += translate_codex_line(_collab("completed", wait), st)+ close = {+ "id": "item_5",+ "tool": "close_agent",+ "receiver_thread_ids": ["child-1"],+ "agents_states": {"child-1": {"status": "shutdown", "message": None}},+ "status": "completed",+ }+ events += translate_codex_line(_collab("completed", close), st)++ started = [ev["payload"] for ev in events if ev["kind"] == "subagent_started"]+ assert started == [+ {+ "turn_id": "t1",+ "agent_id": "item_3",+ "thread_id": "child-1",+ "description": "Reply with PONG",+ "agent_type": "",+ "prompt": "Reply with PONG",+ "background": True,+ }+ ]+ finished = [ev["payload"] for ev in events if ev["kind"] == "subagent_finished"]+ # The close after a finished agent does not turn it into a stopped one.+ assert [(f["agent_id"], f["status"], f["summary"]) for f in finished] == [+ ("item_3", "done", "PONG")+ ]+ calls = [ev["payload"]["name"] for ev in events if ev["kind"] == "tool_call"]+ assert calls == ["spawn_agent", "wait", "close_agent"]