Skip to content

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

feat(agentic-ide): the chat stage reads Grok Build, Antigravity, OpenCode and Kimi panes too

rubenluetke10-beep9e53996bf7a8
diff --git a/jarvis/agentic_ide/agent_transcript.py b/jarvis/agentic_ide/agent_transcript.py
index 29643dcb30..3790ee62e4 100644
--- a/jarvis/agentic_ide/agent_transcript.py
+++ b/jarvis/agentic_ide/agent_transcript.py
@@ -189,14 +189,25 @@ def _rows(path: Path, *, max_bytes: int = MAX_READ_BYTES) -> Iterator[dict[str,
_TARGET_KEYS = (
"file_path",
"path",
+ # Grok Build, OpenCode and Antigravity spell the same argument their way.
+ "target_file",
+ "filePath",
+ "absolute_path",
+ "AbsolutePath",
"notebook_path",
"command",
+ "CommandLine",
+ "cmd",
"pattern",
+ "Pattern",
"query",
+ "Query",
"url",
"prompt",
"description",
"subject",
+ "target_directory",
+ "SearchDirectory",
)
@@ -526,9 +537,25 @@ _OPENERS: dict[str, Callable[[str, Path | None], str | None]] = {
}
+def _agent_key(agent: str) -> str:
+ """The registry key ``agent`` reads through: its own name, or its binary's.
+
+ A launch profile over another CLI's binary (GLM Coding Plan drives Claude
+ Code) writes that CLI's record, so it reads through that CLI's entry — the
+ same indirection :func:`agent_sessions._adapter_for` uses to resume it.
+ """
+ name = str(agent or "").strip().lower()
+ if not name:
+ return ""
+ from jarvis.workspace import agents as workspace_agents
+
+ entry = workspace_agents.get_agent(name)
+ return entry.adapter_key if entry is not None else name
+
+
def can_read(agent: str) -> bool:
"""Does this CLI keep a conversation this module knows how to read?"""
- return str(agent or "").strip().lower() in _READERS
+ return _agent_key(agent) in _READERS
def first_user_text(agent: str, session_id: str, *, home: Path | None = None) -> str | None:
@@ -540,7 +567,7 @@ def first_user_text(agent: str, session_id: str, *, home: Path | None = None) ->
Reads the head of the file only (:data:`MAX_HEAD_BYTES`); the tail readers
above are for the conversation's recent past.
"""
- opener = _OPENERS.get(str(agent or "").strip().lower())
+ opener = _OPENERS.get(_agent_key(agent))
if opener is None or not str(session_id or "").strip():
return None
try:
@@ -558,7 +585,7 @@ def read(agent: str, session_id: str, *, home: Path | None = None) -> list[Turn]
started), or when the file cannot be read. The caller shows the live pane in
that case, which is always correct and never empty.
"""
- reader = _READERS.get(str(agent or "").strip().lower())
+ reader = _READERS.get(_agent_key(agent))
if reader is None or not str(session_id or "").strip():
return None
try:
@@ -1068,7 +1095,9 @@ def _codex_events(session_id: str, home: Path | None, live: bool) -> list[dict[s
return log.finish()
-_EVENT_READERS: dict[str, Callable[[str, Path | None, bool], list[dict[str, Any]] | None]] = {
+_EVENT_READERS: dict[
+ str, Callable[[str, Path | None, bool], list[dict[str, Any]] | _EventLog | None]
+] = {
"claude": _claude_events,
"codex": _codex_events,
}
@@ -1088,16 +1117,802 @@ def read_events(
says whether the pane is still working, which decides how the last turn
ends (see :class:`_EventLog`).
"""
- reader = _EVENT_READERS.get(str(agent or "").strip().lower())
+ reader = _EVENT_READERS.get(_agent_key(agent))
if reader is None or not str(session_id or "").strip():
return None
try:
- return reader(session_id.strip(), home, live)
+ read_result = reader(session_id.strip(), home, live)
except OSError as exc:
logger.warning(
"Agent transcript: {} session {} unreadable as events: {}", agent, session_id, exc
)
return None
+ # The newer readers answer with the log itself, whose events are the list.
+ return read_result.events if isinstance(read_result, _EventLog) else read_result
+
+
+# --------------------------------------------------------------------------- #
+# the other CLIs — one adapter each, all answering in the event vocabulary
+# --------------------------------------------------------------------------- #
+#
+# Every reader below builds an :class:`_EventLog` and nothing else; the turn
+# summary (:func:`read`) and the opening line (:func:`first_user_text`) are
+# derived from that log rather than parsed a second time, so a CLI costs one
+# parser, not three that drift. Each parser reads the layout it was MEASURED
+# against — a live install of the CLI on the maintainer's box, or, where no
+# conversation existed to measure, the CLI's own source — and says so.
+
+
+def _turns_from_events(events: list[dict[str, Any]]) -> list[Turn]:
+ """The turn summary of an event log — what :func:`read` answers."""
+ turns: list[Turn] = []
+ for event in events:
+ kind = event.get("kind")
+ payload = event.get("payload") or {}
+ if kind == "user_message":
+ _append(turns, "user", str(payload.get("text") or ""))
+ elif kind == "assistant_text":
+ _append(turns, "assistant", str(payload.get("text") or ""))
+ elif kind == "tool_call":
+ target, detail = _headline(payload.get("input"))
+ name = str(payload.get("name") or "tool")
+ _step(turns, Step(tool=name, target=target, detail=detail))
+ return turns
+
+
+def _turns_via(
+ reader: Callable[[str, Path | None, bool], _EventLog | None],
+) -> Callable[[str, Path | None], list[Turn] | None]:
+ """A :data:`_READERS` entry built on an event reader."""
+
+ def _read(session_id: str, home: Path | None) -> list[Turn] | None:
+ log = reader(session_id, home, False)
+ return None if log is None else _turns_from_events(log.events)
+
+ return _read
+
+
+def _opener_via(
+ reader: Callable[[str, Path | None, bool], _EventLog | None],
+) -> Callable[[str, Path | None], str | None]:
+ """A :data:`_OPENERS` entry built on an event reader.
+
+ ``None`` when there is no file, ``""`` when nobody has spoken in it yet —
+ the same two answers the head readers give, so :mod:`.opening` treats
+ every CLI alike.
+ """
+
+ def _first(session_id: str, home: Path | None) -> str | None:
+ log = reader(session_id, home, False)
+ if log is None:
+ return None
+ spoken = [e for e in log.events if e.get("kind") == "user_message"]
+ if len(spoken) >= MAX_TURNS:
+ # The log is a window on the recent past; a session this long has
+ # its opening outside it, and a later message is not the opening.
+ return ""
+ return str((spoken[0].get("payload") or {}).get("text") or "") if spoken else ""
+
+ return _first
+
+
+def _own_id(session_id: str) -> str:
+ """``session_id`` when it can name a directory, else "" — never a path."""
+ value = str(session_id or "").strip()
+ return "" if not value or "/" in value or "\\" in value or value in (".", "..") else value
+
+
+def _decode_json(value: Any) -> Any:
+ """``value`` parsed when it is JSON text, else as it came.
+
+ Antigravity writes every argument as JSON inside JSON (``"4"``,
+ ``"\\"*.png\\""``), OpenCode stores a row's body as text, Kimi streams a
+ call's arguments as a string; a path or a sentence is none of those and
+ stays a string.
+ """
+ if isinstance(value, str):
+ stripped = value.strip()
+ if stripped[:1] in ('"', "{", "[", "-") or stripped[:1].isdigit():
+ try:
+ return json.loads(stripped)
+ except (ValueError, TypeError):
+ # The CLI's argument text was not JSON after all — shown as is.
+ return value
+ return value
+
+
+def _count_tokens(usage: Any, names: dict[str, str]) -> dict[str, int]:
+ """A CLI's token report in the chat's own key names — numbers only."""
+ if not isinstance(usage, dict):
+ return {}
+ counted: dict[str, int] = {}
+ for theirs, ours in names.items():
+ value = usage.get(theirs)
+ if isinstance(value, int | float) and not isinstance(value, bool):
+ counted[ours] = int(value)
+ return counted
+
+
+# ------------------------------------------------------------------ Grok Build
+#
+# ~/.grok/sessions/<cwd-group>/<session-id>/updates.jsonl — the ACP
+# ``session/update`` stream the TUI itself is drawn from, one JSON-RPC
+# notification per line, each carrying the agent's own clock. The session
+# directory also holds ``chat_history.jsonl`` (the model's context: whole
+# messages, but no timestamps) and ``summary.json`` (the model and effort the
+# session runs on); the stream is what is read, and the summary is read once
+# for the two facts the stream states nowhere. MEASURED on grok-build sessions
+# of 2026-08-27; the same file `agent_sessions._grok_conversation_exists`
+# decides on. A message streams as consecutive ``*_chunk`` records and is
+# joined back into one here.
+
+_GROK_USAGE = {
+ "inputTokens": "input_tokens",
+ "outputTokens": "output_tokens",
+ "cachedReadTokens": "cache_read_input_tokens",
+ "cacheCreationTokens": "cache_creation_input_tokens",
+ "reasoningTokens": "thinking_tokens",
+}
+
+
+class _Chunks:
+ """Consecutive stream chunks of one message, joined back into the message.
+
+ A thought's duration is read from the record that FOLLOWS it (see
+ :class:`_EventLog`), so a thought streamed as forty chunks must reach the
+ log as one — forty would make thirty-nine of them a millisecond long.
+ """
+
+ def __init__(self, log: _EventLog) -> None:
+ self.log = log
+ self.kind = ""
+ self.key = ""
+ self.parts: list[str] = []
+ self.started = 0
+ self.count = 0
+
+ def add(self, kind: str, text: str, ts: int, key: str = "") -> None:
+ """``key`` tells two messages of one kind apart when nothing else does.
+
+ Two prompts sent back to back are two ``user_message_chunk`` runs with
+ no record between them; the prompt index in the chunk's own metadata
+ is what separates them.
+ """
+ if kind != self.kind or key != self.key:
+ self.flush()
+ if not self.parts:
+ self.started = ts
+ self.count += 1
+ self.kind = kind
+ self.key = key
+ self.parts.append(text)
+
+ def flush(self) -> None:
+ if not self.parts:
+ self.kind = ""
+ return
+ text, kind, started = "".join(self.parts), self.kind, self.started
+ self.parts, self.kind = [], ""
+ message_id = f"chunk-{self.count}"
+ if kind == "user":
+ self.log.user(_spoken(text), started)
+ elif kind == "thought":
+ self.log.thinking(text, message_id, started)
+ elif kind == "text":
+ self.log.text(text, message_id, started)
+
+
+def _grok_file(session_id: str, home: Path | None) -> Path | None:
+ own = _own_id(session_id)
+ if not own:
+ return None
+ root = agent_sessions._grok_home(home) / "sessions"
+ if not root.is_dir():
+ return None
+ folder = next((p for p in root.glob(f"*/{own}") if p.is_dir()), None)
+ if folder is None:
+ return None
+ path = folder / "updates.jsonl"
+ return path if path.is_file() else None
+
+
+def _grok_summary(folder: Path) -> dict[str, Any]:
+ """``summary.json`` of a session — the model and effort it runs on, or {}."""
+ path = folder / "summary.json"
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8")) if path.is_file() else None
+ except (OSError, ValueError) as exc:
+ logger.debug("Agent transcript: grok summary unreadable: {}", exc)
+ return {}
+ return payload if isinstance(payload, dict) else {}
+
+
+def _grok_chunk_text(update: dict[str, Any]) -> str:
+ content = update.get("content")
+ if isinstance(content, dict):
+ return str(content.get("text") or "")
+ return _result_text(content)
+
+
+def _grok_tool_name(update: dict[str, Any]) -> str:
+ meta = update.get("_meta")
+ tool = meta.get("x.ai/tool") if isinstance(meta, dict) else None
+ if isinstance(tool, dict) and tool.get("name"):
+ return str(tool["name"])
+ return str(update.get("title") or "tool")
+
+
+def _first_text(value: Any, depth: int = 0) -> Any:
+ """The text inside a CLI's typed output envelope, or the envelope itself.
+
+ Grok Build returns ``{"type": "ListDir", "Content": {"content": "…"}}``:
+ a shape per tool, with the text a couple of keys down. The envelope is
+ kept whole when no text is found in it.
+ """
+ if isinstance(value, dict) and depth < 3:
+ for key, inner in value.items():
+ if str(key).lower() in ("content", "output", "text", "stdout", "result"):
+ found = _first_text(inner, depth + 1)
+ if isinstance(found, str) and found:
+ return found
+ # ``{"type": "ReadFile", "FileNotFound": "Error: …"}`` — one payload
+ # under a name only that tool knows.
+ rest = [inner for key, inner in value.items() if key != "type"]
+ if len(rest) == 1:
+ found = _first_text(rest[0], depth + 1)
+ if isinstance(found, str) and found:
+ return found
+ return value
+
+
+def _grok_output(update: dict[str, Any]) -> Any:
+ """What a finished call returned: its content blocks, else the raw output."""
+ blocks = update.get("content")
+ if isinstance(blocks, list) and blocks:
+ parts: list[str] = []
+ for block in blocks:
+ inner = block.get("content") if isinstance(block, dict) else None
+ if isinstance(inner, dict):
+ if inner.get("type") == "image":
+ parts.append("[image]")
+ else:
+ parts.append(str(inner.get("text") or ""))
+ return "\n".join(p for p in parts if p)
+ return _first_text(update.get("rawOutput"))
+
+
+def _grok_events(session_id: str, home: Path | None, live: bool) -> _EventLog | None:
+ path = _grok_file(session_id, home)
+ if path is None:
+ return None
+ log = _EventLog(provider="grok-build", live=live)
+ summary = _grok_summary(path.parent)
+ log.model = str(summary.get("current_model_id") or "")
+ log.effort = str(summary.get("reasoning_effort") or "")
+ chunks = _Chunks(log)
+ # A background task reports its call as completed twice (once when it is
+ # backgrounded, once when it ends); a result lands on its call once.
+ answered: set[str] = set()
+ for row in _rows(path):
+ params = row.get("params")
+ if not isinstance(params, dict):
+ continue
+ update = params.get("update")
+ if not isinstance(update, dict):
+ continue
+ meta = params.get("_meta")
+ ts = (
+ (_ts_ms(meta.get("agentTimestampMs")) if isinstance(meta, dict) else None)
+ or _ts_ms(row.get("timestamp"))
+ or log.last_ms
+ )
+ kind = str(update.get("sessionUpdate") or "")
+ if kind == "user_message_chunk":
+ raw_meta = update.get("_meta")
+ own_meta: dict[str, Any] = raw_meta if isinstance(raw_meta, dict) else {}
+ if own_meta.get("modelId"):
+ log.model = str(own_meta["modelId"])
+ prompt = str(own_meta.get("promptIndex", ""))
+ chunks.add("user", _grok_chunk_text(update), ts, key=prompt)
+ continue
+ if kind == "agent_thought_chunk":
+ chunks.add("thought", _grok_chunk_text(update), ts)
+ continue
+ if kind == "agent_message_chunk":
+ chunks.add("text", _grok_chunk_text(update), ts)
+ continue
+ chunks.flush()
+ if kind == "tool_call":
+ call_id = str(update.get("toolCallId") or f"call-{len(log.events)}")
+ log.tool_call(call_id, _grok_tool_name(update), update.get("rawInput"), ts)
+ elif kind == "tool_call_update":
+ # The first update of a call refines its title and locations; only
+ # one with a terminal status carries what the call returned.
+ status = str(update.get("status") or "")
+ call_id = str(update.get("toolCallId") or "")
+ if status not in ("completed", "failed") or not call_id or call_id in answered:
+ continue
+ answered.add(call_id)
+ log.tool_result(call_id, _grok_output(update), status == "failed", ts)
+ elif kind == "turn_completed":
+ log.usage_total(_count_tokens(update.get("usage"), _GROK_USAGE), ts)
+ stop = str(update.get("stop_reason") or "")
+ log.close_turn(ts, "cancelled" if stop in ("cancelled", "aborted") else "done")
+ # hook runs, plans, background-task bookkeeping, sub-agent spawns and
+ # the session recap are the CLI's own housekeeping, not the conversation.
+ chunks.flush()
+ log.events = log.finish()
+ return log
+
+
+# ----------------------------------------------------------------- Antigravity
+#
+# <gemini-home>/antigravity-cli/brain/<id>/.system_generated/logs/transcript.jsonl
+# — one step per line: the person's request (``USER_INPUT``, wrapped in a
+# ``<USER_REQUEST>`` block beside the harness's metadata), the model's step
+# (``PLANNER_RESPONSE``: its thinking, its prose, its tool calls), each call's
+# output as the ``GENERIC`` step that follows in order, and the system's
+# checkpoints and messages. Tool-call arguments are JSON-encoded strings
+# inside JSON. MEASURED on agy 1.1.20 (2026-08-25). The record names no
+# model, so the pane's own picks stand.
+
+_AGY_REQUEST = re.compile(r"<USER_REQUEST>\s*(.*?)\s*</USER_REQUEST>", re.DOTALL)
+
+
+def _agy_file(session_id: str, home: Path | None) -> Path | None:
+ own = _own_id(session_id)
+ if not own:
+ return None
+ path = agent_sessions._agy_transcript(agent_sessions._agy_cli_root(home), own)
+ return path if path.is_file() else None
+
+
+def _agy_args(args: Any) -> Any:
+ if not isinstance(args, dict):
+ return _decode_json(args)
+ return {str(key): _decode_json(value) for key, value in args.items()}
+
+
+def _agy_events(session_id: str, home: Path | None, live: bool) -> _EventLog | None:
+ path = _agy_file(session_id, home)
+ if path is None:
+ return None
+ log = _EventLog(provider="antigravity", live=live)
+ # Calls whose output has not arrived yet, in the order the model made them
+ # — the transcript pairs a result with its call by position, not by id.
+ pending: list[str] = []
+ for row in _rows(path):
+ kind = str(row.get("type") or "")
+ ts = _ts_ms(row.get("created_at")) or log.last_ms
+ step = str(row.get("step_index") if row.get("step_index") is not None else len(log.events))
+ content = str(row.get("content") or "")
+ if kind == "USER_INPUT":
+ if str(row.get("source") or "") != "USER_EXPLICIT":
+ continue
+ match = _AGY_REQUEST.search(content)
+ log.user(match.group(1) if match else _spoken(content), ts)
+ elif kind == "PLANNER_RESPONSE":
+ thinking = row.get("thinking")
+ if isinstance(thinking, str) and thinking.strip():
+ log.thinking(thinking, f"step-{step}", ts)
+ if content:
+ log.text(content, f"step-{step}", ts)
+ calls = row.get("tool_calls")
+ if isinstance(calls, list):
+ for index, call in enumerate(calls):
+ if not isinstance(call, dict):
+ continue
+ call_id = f"step-{step}-{index}"
+ log.tool_call(
+ call_id, str(call.get("name") or "tool"), _agy_args(call.get("args")), ts
+ )
+ pending.append(call_id)
+ elif kind == "GENERIC":
+ if pending:
+ # The record does not say whether the call failed; the output
+ # itself does, and it is shown whole.
+ log.tool_result(pending.pop(0), content, False, ts)
+ elif kind == "ERROR_MESSAGE" and content:
+ # What the pane showed in place of an answer — the model retries
+ # after it, so the turn stays open.
+ log.text(content, f"step-{step}", ts)
+ # CHECKPOINT and SYSTEM_MESSAGE are the harness talking to the model.
+ log.events = log.finish()
+ return log
+
+
+# -------------------------------------------------------------------- OpenCode
+#
+# The session database (see `agent_sessions._opencode_db`): a ``message`` row
+# per message (role, model, variant, token totals, timestamps) and ``part``
+# rows for its body — ``text``, ``reasoning`` with its own start and end,
+# ``tool`` with the call's input and its state, ``step-start``/``step-finish``.
+# MEASURED on opencode 1.18.23 (2026-08-26). Bounded by message count rather
+# than bytes, because this is a database and not a file.
+
+_OPENCODE_MAX_MESSAGES = 600
+
+_OPENCODE_TOKENS = {
+ "input": "input_tokens",
+ "output": "output_tokens",
+ "reasoning": "thinking_tokens",
+}
+
+
+def _opencode_tokens(tokens: Any) -> dict[str, Any]:
+ """A message's token report in the shape :meth:`_EventLog.usage` reads."""
+ counted: dict[str, Any] = _count_tokens(tokens, _OPENCODE_TOKENS)
+ cache = tokens.get("cache") if isinstance(tokens, dict) else None
+ counted.update(
+ _count_tokens(
+ cache,
+ {"read": "cache_read_input_tokens", "write": "cache_creation_input_tokens"},
+ )
+ )
+ thinking = counted.pop("thinking_tokens", None)
+ if thinking is not None:
+ counted["output_tokens_details"] = {"thinking_tokens": thinking}
+ return counted
+
+
+def _opencode_events(session_id: str, home: Path | None, live: bool) -> _EventLog | None:
+ own = str(session_id or "").strip()
+ if not own or not agent_sessions._opencode_rows(
+ home, "SELECT 1 FROM session WHERE id = ? LIMIT 1", (own,)
+ ):
+ return None
+ log = _EventLog(provider="opencode", live=live)
+ messages = agent_sessions._opencode_rows(
+ home,
+ "SELECT id, time_created, data FROM message WHERE session_id = ? "
+ "ORDER BY time_created DESC LIMIT ?",
+ (own, _OPENCODE_MAX_MESSAGES),
+ )
+ messages.reverse()
+ if not messages:
+ log.events = log.finish()
+ return log
+ parts_by_message: dict[str, list[tuple[str, Any, Any, dict[str, Any]]]] = {}
+ for part_id, message_id, created, updated, data in agent_sessions._opencode_rows(
+ home,
+ "SELECT id, message_id, time_created, time_updated, data FROM part "
+ "WHERE session_id = ? AND time_created >= ? ORDER BY time_created",
+ (own, messages[0][1]),
+ ):
+ part = _decode_json(data)
+ if isinstance(part, dict):
+ parts_by_message.setdefault(str(message_id), []).append(
+ (str(part_id), created, updated, part)
+ )
+ for message_id, created, data in messages:
+ message = _decode_json(data)
+ if not isinstance(message, dict):
+ continue
+ clock = message.get("time")
+ ts = (
+ (_ts_ms(clock.get("created")) if isinstance(clock, dict) else None)
+ or _ts_ms(created)
+ or log.last_ms
+ )
+ parts = parts_by_message.get(str(message_id), [])
+ role = str(message.get("role") or "")
+ if role == "user":
+ texts = [str(p.get("text") or "") for _, _, _, p in parts if p.get("type") == "text"]
+ log.user(_spoken("\n\n".join(t for t in texts if t)), ts)
+ continue
+ if role != "assistant":
+ continue
+ if isinstance(message.get("modelID"), str) and message["modelID"]:
+ log.model = message["modelID"]
+ if isinstance(message.get("variant"), str) and message["variant"]:
+ log.effort = message["variant"]
+ for part_id, part_created, part_updated, part in parts:
+ ptype = str(part.get("type") or "")
+ pts = _ts_ms(part_created) or ts
+ if ptype == "reasoning":
+ span = part.get("time")
+ started = (_ts_ms(span.get("start")) if isinstance(span, dict) else None) or pts
+ log.thinking(str(part.get("text") or ""), part_id, started)
+ elif ptype == "text":
+ log.text(str(part.get("text") or ""), part_id, pts)
+ elif ptype == "tool":
+ raw_state = part.get("state")
+ state: dict[str, Any] = raw_state if isinstance(raw_state, dict) else {}
+ call_id = str(part.get("callID") or part_id)
+ span = state.get("time")
+ started = (_ts_ms(span.get("start")) if isinstance(span, dict) else None) or pts
+ log.tool_call(call_id, str(part.get("tool") or "tool"), state.get("input"), started)
+ status = str(state.get("status") or "")
+ if status in ("completed", "error"):
+ ended = (
+ (_ts_ms(span.get("end")) if isinstance(span, dict) else None)
+ or _ts_ms(part_updated)
+ or pts
+ )
+ output = state.get("error") if status == "error" else state.get("output")
+ log.tool_result(call_id, output, status == "error", ended)
+ log.usage(str(message_id), _opencode_tokens(message.get("tokens")), max(ts, log.last_ms))
+ error = message.get("error")
+ if isinstance(error, dict) and (error.get("message") or error.get("name")):
+ log.error = str(error.get("message") or error.get("name"))
+ elif isinstance(error, str) and error:
+ log.error = error
+ log.events = log.finish()
+ return log
+
+
+# ------------------------------------------------------------------------ Kimi
+#
+# <root>/sessions/<bucket>/<session-id>/agents/main/wire.jsonl (current
+# generation) or <root>/sessions/<bucket>/<session-id>/wire.jsonl (legacy) —
+# the wire log both generations replay a session from. Two record shapes:
+#
+# * **Wrapped** (legacy, protocol 1.1): ``{"timestamp": s, "message":
+# {"type", "payload"}}`` — ``TurnBegin`` with the person's input,
+# ``ContentPart`` (a ``think`` or ``text`` part), ``ToolCall``,
+# ``ToolResult``, ``StatusUpdate`` with the step's token usage. MEASURED on
+# a kimi-cli session of 2026-02-05.
+# * **Flat** (current, protocol 1.4): ``{"type", ..., "time": ms}`` —
+# ``context.append_message`` for the person (and the harness's reminders,
+# told apart by ``origin.kind``), ``context.append_loop_event`` carrying the
+# agent's ``content.part`` / ``tool.call`` / ``tool.result`` / ``step.end``,
+# ``usage.record`` naming the model. Taken from the CLI's own writer
+# (kimi-code 0.29.2, ``agent-core/context`` and ``turn_step``): no signed-in
+# install existed to record a live conversation with, so the shapes are the
+# source's, and a future record shape degrades to fewer rows, never an error.
+
+_KIMI_USAGE = {
+ "output": "output_tokens",
+ "input_other": "input_tokens",
+ "inputOther": "input_tokens",
+ "input_cache_read": "cache_read_input_tokens",
+ "inputCacheRead": "cache_read_input_tokens",
+ "input_cache_creation": "cache_creation_input_tokens",
+ "inputCacheCreation": "cache_creation_input_tokens",
+}
+
+
+def _kimi_file(session_id: str, home: Path | None) -> Path | None:
+ own = _own_id(session_id)
+ if not own:
+ return None
+ root = agent_sessions._kimi_root(home)
+ if root is None:
+ return None
+ sessions = root / "sessions"
+ if not sessions.is_dir():
+ return None
+ folder = next((p for p in sessions.glob(f"*/{own}") if p.is_dir()), None)
+ if folder is None:
+ return None
+ for candidate in (folder / "agents" / "main" / "wire.jsonl", folder / "wire.jsonl"):
+ if candidate.is_file():
+ return candidate
+ return None
+
+
+def _kimi_text(content: Any) -> str:
+ """The prose of a Kimi message body: text parts joined, other media named."""
+ if isinstance(content, str):
+ return content
+ if not isinstance(content, list):
+ return ""
+ parts: list[str] = []
+ for block in content:
+ if not isinstance(block, dict):
+ continue
+ btype = str(block.get("type") or "")
+ if btype == "text":
+ parts.append(str(block.get("text") or ""))
+ elif btype.endswith("_url"):
+ parts.append(f"[{btype[:-4]}]")
+ return "\n".join(p for p in parts if p)
+
+
+def _kimi_call(log: _EventLog, call: Any, ts: int) -> None:
+ if not isinstance(call, dict):
+ return
+ raw = call.get("function")
+ function: dict[str, Any] = raw if isinstance(raw, dict) else {}
+ name = str(function.get("name") or call.get("name") or "tool")
+ arguments = function.get("arguments") if function else call.get("args")
+ call_id = str(call.get("id") or f"call-{len(log.events)}")
+ log.tool_call(call_id, name, _decode_json(arguments), ts)
+
+
+def _kimi_part(log: _EventLog, part: Any, message_id: str, ts: int) -> None:
+ if not isinstance(part, dict):
+ return
+ ptype = str(part.get("type") or "")
+ if ptype == "think":
+ log.thinking(str(part.get("think") or part.get("text") or ""), message_id, ts)
+ elif ptype == "text":
+ log.text(str(part.get("text") or ""), message_id, ts)
+
+
+class _KimiCall:
+ """A legacy ``ToolCall`` held back while its ``ToolCallPart`` deltas arrive.
+
+ The legacy wire records a call before its arguments have streamed, then the
+ arguments in parts; emitting on the first record would show every such
+ call without its target.
+ """
+
+ def __init__(self, log: _EventLog) -> None:
+ self.log = log
+ self.held: tuple[dict[str, Any], int] | None = None
+
+ def hold(self, payload: dict[str, Any], ts: int) -> None:
+ self.flush()
+ self.held = (payload, ts)
+
+ def extend(self, part: str) -> None:
+ if self.held is None:
+ return
+ payload, _ts = self.held
+ function = payload.get("function")
+ if isinstance(function, dict):
+ function["arguments"] = str(function.get("arguments") or "") + part
+
+ def flush(self, unless_before: str | None = None) -> None:
+ """Emit the held call — except when ``unless_before`` names another call.
+
+ Results of EARLIER calls land while a later call's arguments are still
+ streaming (measured: the third of three parallel reads); such a result
+ is not what closes the held call.
+ """
+ if self.held is None:
+ return
+ payload, ts = self.held
+ if unless_before is not None and unless_before != str(payload.get("id") or ""):
+ return
+ self.held = None
+ _kimi_call(self.log, payload, ts)
+
+
+def _kimi_wrapped(log: _EventLog, message: dict[str, Any], ts: int, calls: _KimiCall) -> None:
+ """One legacy wire record — ``message.type`` names it, ``payload`` is it."""
+ kind = str(message.get("type") or "")
+ payload = message.get("payload")
+ if not isinstance(payload, dict):
+ return
+ if kind == "ToolCall":
+ calls.hold(payload, ts)
+ return
+ if kind == "ToolCallPart":
+ calls.extend(str(payload.get("arguments_part") or ""))
+ return
+ if kind == "ToolResult":
+ calls.flush(unless_before=str(payload.get("tool_call_id") or ""))
+ else:
+ # A token report marks the end of the model's step: every call of it
+ # has its arguments by then.
+ calls.flush()
+ if kind == "TurnBegin":
+ log.user(_spoken(_kimi_text(payload.get("user_input"))), ts)
+ elif kind == "ContentPart":
+ _kimi_part(log, payload, f"part-{len(log.events)}", ts)
+ elif kind == "ToolResult":
+ returned = payload.get("return_value")
+ returned = returned if isinstance(returned, dict) else {"output": returned}
+ log.tool_result(
+ str(payload.get("tool_call_id") or ""),
+ returned.get("output"),
+ bool(returned.get("is_error")),
+ ts,
+ )
+ elif kind == "StatusUpdate":
+ message_id = str(payload.get("message_id") or f"status-{len(log.events)}")
+ log.usage(message_id, _count_tokens(payload.get("token_usage"), _KIMI_USAGE), ts)
+ # StepBegin and the approval exchange are the TUI's own bookkeeping.
+
+
+def _kimi_flat(log: _EventLog, row: dict[str, Any], ts: int) -> None:
+ """One current-generation wire record — ``type`` names it."""
+ kind = str(row.get("type") or "")
+ if kind == "context.append_message":
+ message = row.get("message")
+ if not isinstance(message, dict):
+ return
+ origin = message.get("origin")
+ source = str(origin.get("kind") or "user") if isinstance(origin, dict) else "user"
+ role = str(message.get("role") or "")
+ if role == "user":
+ # A reminder the harness appends in the person's name says so in
+ # its origin; the person's own prompt is the one with kind "user".
+ if source == "user":
+ log.user(_spoken(_kimi_text(message.get("content"))), ts)
+ elif role == "assistant":
+ message_id = f"message-{len(log.events)}"
+ content = message.get("content")
+ if isinstance(content, list):
+ for part in content:
+ _kimi_part(log, part, message_id, ts)
+ elif isinstance(content, str):
+ log.text(content, message_id, ts)
+ calls = message.get("toolCalls") or message.get("tool_calls")
+ if isinstance(calls, list):
+ for call in calls:
+ _kimi_call(log, call, ts)
+ elif role == "tool":
+ log.tool_result(
+ str(message.get("toolCallId") or message.get("tool_call_id") or ""),
+ _kimi_text(message.get("content")),
+ bool(message.get("isError") or message.get("is_error")),
+ ts,
+ )
+ return
+ if kind == "context.append_loop_event":
+ event = row.get("event")
+ if not isinstance(event, dict):
+ return
+ etype = str(event.get("type") or "")
+ if etype == "content.part":
+ part_id = str(event.get("uuid") or f"part-{len(log.events)}")
+ _kimi_part(log, event.get("part"), part_id, ts)
+ elif etype == "tool.call":
+ log.tool_call(
+ str(event.get("toolCallId") or event.get("uuid") or f"call-{len(log.events)}"),
+ str(event.get("name") or "tool"),
+ event.get("args"),
+ ts,
+ )
+ elif etype == "tool.result":
+ result = event.get("result")
+ result = result if isinstance(result, dict) else {"output": result}
+ log.tool_result(
+ str(event.get("toolCallId") or event.get("parentUuid") or ""),
+ result.get("output"),
+ bool(result.get("isError") or result.get("is_error")),
+ ts,
+ )
+ elif etype == "step.end":
+ message_id = str(event.get("uuid") or f"step-{len(log.events)}")
+ log.usage(message_id, _count_tokens(event.get("usage"), _KIMI_USAGE), ts)
+ return
+ if kind == "usage.record":
+ model = row.get("model")
+ if isinstance(model, str) and model:
+ log.model = model
+ elif kind == "turn.cancel":
+ log.close_turn(ts, "cancelled")
+ # turn.prompt duplicates the append_message the prompt becomes; the rest
+ # (config, tools, compaction, permission and plan-mode records) is state.
+
+
+def _kimi_events(session_id: str, home: Path | None, live: bool) -> _EventLog | None:
+ path = _kimi_file(session_id, home)
+ if path is None:
+ return None
+ log = _EventLog(provider="kimi", live=live)
+ calls = _KimiCall(log)
+ for row in _rows(path):
+ message = row.get("message")
+ if isinstance(message, dict) and "payload" in message:
+ _kimi_wrapped(log, message, _ts_ms(row.get("timestamp")) or log.last_ms, calls)
+ else:
+ calls.flush()
+ _kimi_flat(log, row, _ts_ms(row.get("time")) or log.last_ms)
+ calls.flush()
+ log.events = log.finish()
+ return log
+
+
+# --------------------------------------------------------------- registration
+#
+# Keyed by the adapter key of `jarvis.workspace.agents` — a launch profile
+# over another CLI's binary (GLM Coding Plan drives Claude Code) writes that
+# CLI's record and resolves to it through :func:`_agent_key`.
+
+_MORE_EVENT_READERS: dict[str, Callable[[str, Path | None, bool], _EventLog | None]] = {
+ "grok-build": _grok_events,
+ "antigravity": _agy_events,
+ "opencode": _opencode_events,
+ "kimi": _kimi_events,
+}
+_EVENT_READERS.update(_MORE_EVENT_READERS)
+_READERS.update({key: _turns_via(reader) for key, reader in _MORE_EVENT_READERS.items()})
+_OPENERS.update({key: _opener_via(reader) for key, reader in _MORE_EVENT_READERS.items()})
__all__ = [
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/toolView.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/toolView.test.ts
index a0aa7f7c23..7016bbc540 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/toolView.test.ts
+++ b/jarvis/ui/web/frontend/src/components/agentchat/toolView.test.ts
@@ -36,6 +36,34 @@ describe("agentToolView", () => {
expect(agentToolView("Task", { prompt: "go" }).family).toBe("agent");
});
+ it("reads the other CLIs' tool names and argument spellings the same way", () => {
+ // Grok Build
+ expect(agentToolView("read_file", { target_file: "a.py" })).toMatchObject({
+ family: "read",
+ summary: "a.py",
+ });
+ expect(agentToolView("search_replace", { target_file: "a.py" }).family).toBe("edit");
+ expect(agentToolView("list_dir", { target_directory: "src" }).summary).toBe("src");
+ // OpenCode
+ expect(agentToolView("read", { filePath: "run.bat" }).summary).toBe("run.bat");
+ // Antigravity
+ expect(agentToolView("find_by_name", { Pattern: "*.png", SearchDirectory: "src" })).toMatchObject({
+ family: "search",
+ summary: "*.png",
+ });
+ expect(agentToolView("run_command", { CommandLine: "npm test" })).toMatchObject({
+ family: "shell",
+ summary: "npm test",
+ });
+ expect(agentToolView("write_to_file", { TargetFile: "x.md" }).family).toBe("write");
+ expect(agentToolView("view_file", { AbsolutePath: "C:/w/a.png" }).family).toBe("read");
+ // Kimi
+ expect(agentToolView("ReadFile", { path: "NOTES.md" })).toMatchObject({
+ family: "read",
+ summary: "NOTES.md",
+ });
+ });
+
it("names an MCP call after its server and wears the vendor mark when there is one", () => {
const gh = agentToolView("mcp__github__create_issue", { title: "Bug" });
expect(gh.family).toBe("mcp");
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/toolView.ts b/jarvis/ui/web/frontend/src/components/agentchat/toolView.ts
index 87521a834e..48a9913b7e 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/toolView.ts
+++ b/jarvis/ui/web/frontend/src/components/agentchat/toolView.ts
@@ -47,14 +47,22 @@ export interface AgentToolView {
family: "shell" | "edit" | "write" | "read" | "search" | "web" | "agent" | "plan" | "ask" | "skill" | "tools" | "mcp" | "jarvis" | "other";
}
-/** Claude Code, Codex and agy tool names — the agent's own vocabulary. */
+/**
+ * Claude Code, Codex, Grok Build, OpenCode, Kimi and agy tool names — the
+ * agent's own vocabulary, one regex per family. A name none of them match
+ * still gets its row; it just wears the plain wrench.
+ */
const CLI_TOOLS: Array<[RegExp, AgentToolView["family"], LucideIcon]> = [
[/^(bash|powershell|shell|run_?command|command|exec|terminal|cmd)$/i, "shell", TerminalSquare],
- [/^(edit|multi_?edit|apply_?patch|str_replace(_based_edit_tool)?|notebook_?edit)$/i, "edit", FileDiff],
- [/^(write|create_?file|write_?file)$/i, "write", FilePen],
- [/^(read|cat|view|open_?file|read_?file)$/i, "read", FileText],
- [/^(glob|ls|list_?dir(ectory)?)$/i, "search", FolderSearch],
- [/^(grep|search|find|rg|code_?search)$/i, "search", Search],
+ [
+ /^(edit|multi_?edit|apply_?patch|str_replace(_based_edit_tool)?|notebook_?edit|search_?replace|(multi_?)?replace_?file_?content|edit_?file)$/i,
+ "edit",
+ FileDiff,
+ ],
+ [/^(write|create_?file|write_?file|write_?to_?file)$/i, "write", FilePen],
+ [/^(read|cat|view|open_?file|read_?file|view_?file|read_?media_?file|view_?code_?item)$/i, "read", FileText],
+ [/^(glob|ls|list_?dir(ectory)?|find_?by_?name)$/i, "search", FolderSearch],
+ [/^(grep|search|find|rg|code_?search|grep_?search|search_?web)$/i, "search", Search],
[/^tool_?search$/i, "tools", PackageSearch],
[/^(web_?fetch|web_?search|fetch|browse|http)$/i, "web", Globe],
[/^(agent|task|sub_?agent|spawn(_?agents?)?|delegate)$/i, "agent", Bot],
@@ -74,11 +82,11 @@ const CLI_TOOLS: Array<[RegExp, AgentToolView["family"], LucideIcon]> = [
* first and falls through to the generic list after.
*/
const SUMMARY_KEYS: Record<string, string[]> = {
- shell: ["command", "cmd", "script"],
- search: ["pattern", "query", "glob", "path", "file_path"],
- read: ["file_path", "path", "notebook_path", "url"],
- write: ["file_path", "path"],
- edit: ["file_path", "path", "notebook_path"],
+ shell: ["command", "CommandLine", "cmd", "script"],
+ search: ["pattern", "Pattern", "query", "Query", "glob", "path", "target_directory", "SearchDirectory", "file_path"],
+ read: ["file_path", "path", "target_file", "filePath", "AbsolutePath", "absolute_path", "notebook_path", "url"],
+ write: ["file_path", "path", "target_file", "filePath", "TargetFile", "AbsolutePath"],
+ edit: ["file_path", "path", "target_file", "filePath", "TargetFile", "AbsolutePath", "notebook_path"],
web: ["url", "query", "prompt"],
agent: ["description", "prompt", "task"],
plan: ["description", "plan", "todos"],
@@ -89,11 +97,17 @@ const SUMMARY_KEYS: Record<string, string[]> = {
const GENERIC_SUMMARY_KEYS = [
"command",
+ "CommandLine",
"cmd",
"pattern",
+ "Pattern",
"query",
+ "Query",
"file_path",
"path",
+ "target_file",
+ "filePath",
+ "AbsolutePath",
"url",
"prompt",
"description",
diff --git a/tests/unit/agentic_ide/test_agent_transcript_clis.py b/tests/unit/agentic_ide/test_agent_transcript_clis.py
new file mode 100644
index 0000000000..67e600c2ca
--- /dev/null
+++ b/tests/unit/agentic_ide/test_agent_transcript_clis.py
@@ -0,0 +1,912 @@
+"""The transcript readers of the CLIs beyond Claude Code and Codex.
+
+Fixtures are written in the shape each CLI actually puts on disk — measured on
+the maintainer's box (Grok Build, Antigravity, OpenCode, the legacy Kimi wire)
+or taken from the CLI's own writer (the current Kimi wire) — for the reason the
+sibling test files give: the reader's whole point is that it reads THAT file,
+and a tidied-up fixture passes while the chat stage stays blank.
+
+What the stage depends on is what is checked: a streamed message reaches the
+log as one message, a call gets its result and its name, the person's words
+come out of the harness's wrapping, the token report lands in the chat's own
+key names, and a launch profile over another CLI's binary reads that CLI's
+record.
+"""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+from pathlib import Path
+
+from jarvis.agentic_ide import agent_transcript
+
+
+def _write(path: Path, rows: list[dict]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ "\n".join(json.dumps(row, ensure_ascii=False) for row in rows) + "\n",
+ encoding="utf-8",
+ )
+
+
+def _kinds(events: list[dict]) -> list[str]:
+ return [event["kind"] for event in events]
+
+
+def _by_kind(events: list[dict], kind: str) -> list[dict]:
+ return [event["payload"] for event in events if event["kind"] == kind]
+
+
+# --------------------------------------------------------------------------- #
+# Grok Build
+# --------------------------------------------------------------------------- #
+
+
+#: A real clock — the readers take a small number for seconds, as the CLIs
+#: that write seconds need them to, so a fixture's milliseconds must look like
+#: milliseconds.
+T0 = 1_787_823_800_000
+
+
+def _grok_update(update: dict, at_ms: int, method: str = "session/update") -> dict:
+ at_ms += T0
+ return {
+ "timestamp": at_ms // 1000,
+ "method": method,
+ "params": {
+ "sessionId": "grok-1",
+ "update": update,
+ "_meta": {"eventId": f"grok-1-{at_ms}", "agentTimestampMs": at_ms},
+ },
+ }
+
+
+def _grok_session(home: Path, rows: list[dict], summary: dict | None = None) -> None:
+ folder = home / "sessions" / "C%3A%5Cwork" / "grok-1"
+ _write(folder / "updates.jsonl", rows)
+ if summary is not None:
+ (folder / "summary.json").write_text(json.dumps(summary), encoding="utf-8")
+
+
+def _grok_rows() -> list[dict]:
+ text = {"type": "text"}
+ return [
+ _grok_update(
+ {"sessionUpdate": "hook_execution", "event_name": "session_start", "runs": []},
+ 1_000,
+ method="_x.ai/session/update",
+ ),
+ _grok_update(
+ {
+ "sessionUpdate": "user_message_chunk",
+ "content": {**text, "text": "Fix the sidebar"},
+ "_meta": {"modelId": "grok-4.6", "promptIndex": 0},
+ },
+ 2_000,
+ ),
+ _grok_update(
+ {"sessionUpdate": "agent_thought_chunk", "content": {**text, "text": "The user "}},
+ 3_000,
+ ),
+ _grok_update(
+ {"sessionUpdate": "agent_thought_chunk", "content": {**text, "text": "wants a fix."}},
+ 3_100,
+ ),
+ _grok_update(
+ {"sessionUpdate": "agent_message_chunk", "content": {**text, "text": "Looking."}},
+ 4_000,
+ ),
+ _grok_update(
+ {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "call-1",
+ "title": "read_file",
+ "rawInput": {"target_file": "sidebar.tsx"},
+ "_meta": {"x.ai/tool": {"name": "read_file", "kind": "read"}},
+ },
+ 5_000,
+ ),
+ # The refinement — a title and locations, no status — is not a result.
+ _grok_update(
+ {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "call-1",
+ "kind": "read",
+ "title": "Read `sidebar.tsx`",
+ "locations": [{"path": "sidebar.tsx"}],
+ "rawInput": {"target_file": "sidebar.tsx"},
+ },
+ 5_001,
+ ),
+ _grok_update(
+ {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "call-1",
+ "status": "completed",
+ "content": [{"type": "content", "content": {**text, "text": "export const x"}}],
+ "rawOutput": {"type": "ReadFile", "Content": {"content": "export const x"}},
+ },
+ 5_250,
+ ),
+ _grok_update(
+ {
+ "sessionUpdate": "tool_call",
+ "toolCallId": "call-2",
+ "title": "list_dir",
+ "rawInput": {"target_directory": "src"},
+ "_meta": {"x.ai/tool": {"name": "list_dir", "kind": "read"}},
+ },
+ 6_000,
+ ),
+ _grok_update(
+ {
+ "sessionUpdate": "tool_call_update",
+ "toolCallId": "call-2",
+ "status": "failed",
+ "rawOutput": {"type": "ListDir", "NotFound": "Error: src does not exist"},
+ },
+ 6_100,
+ ),
+ # A background task reports its call as completed once more when it
+ # ends; the result already landed.
+ _grok_update(
+ {"sessionUpdate": "tool_call_update", "toolCallId": "call-1", "status": "completed"},
+ 6_200,
+ ),
+ _grok_update(
+ {"sessionUpdate": "agent_message_chunk", "content": {**text, "text": "Done."}},
+ 7_000,
+ ),
+ _grok_update(
+ {
+ "sessionUpdate": "turn_completed",
+ "prompt_id": "p-1",
+ "stop_reason": "end_turn",
+ "usage": {
+ "inputTokens": 5000,
+ "outputTokens": 120,
+ "cachedReadTokens": 4000,
+ "cacheCreationTokens": 0,
+ "reasoningTokens": 80,
+ "modelCalls": 3,
+ },
+ },
+ 8_000,
+ method="_x.ai/session/update",
+ ),
+ ]
+
+
+class TestGrokBuild:
+ def test_the_stream_folds_into_the_chat_events(self, tmp_path: Path) -> None:
+ _grok_session(
+ tmp_path, _grok_rows(), {"current_model_id": "grok-4.6", "reasoning_effort": "xhigh"}
+ )
+ log = agent_transcript._grok_events("grok-1", tmp_path, False)
+ assert log is not None and (log.model, log.effort) == ("grok-4.6", "xhigh")
+ events = agent_transcript.read_events("grok-build", "grok-1", home=tmp_path)
+ assert events is not None
+ assert _kinds(events) == [
+ "user_message",
+ "turn_started",
+ "reasoning",
+ "assistant_text",
+ "tool_call",
+ "tool_result",
+ "tool_call",
+ "tool_result",
+ "assistant_text",
+ "usage_delta",
+ "turn_finished",
+ ]
+ assert _by_kind(events, "user_message")[0]["text"] == "Fix the sidebar"
+ # Two chunks, one thought — timed from its first chunk to the prose.
+ thought = _by_kind(events, "reasoning")[0]
+ assert thought["text"] == "The user wants a fix."
+ assert thought["duration_ms"] == 1_000
+ calls = _by_kind(events, "tool_call")
+ assert [c["name"] for c in calls] == ["read_file", "list_dir"]
+ assert calls[0]["summary"] == "sidebar.tsx"
+ assert calls[1]["summary"] == "src"
+ results = _by_kind(events, "tool_result")
+ assert results[0] == {
+ "turn_id": "turn-1",
+ "call_id": "call-1",
+ "output": "export const x",
+ "is_error": False,
+ "duration_ms": 250,
+ }
+ assert results[1]["is_error"] is True
+ assert results[1]["output"].startswith("Error: src does not exist")
+ finished = _by_kind(events, "turn_finished")[0]
+ assert finished["status"] == "done"
+ assert finished["usage"]["output_tokens"] == 120
+ assert finished["usage"]["thinking_tokens"] == 80
+ assert finished["usage"]["cache_read_input_tokens"] == 4000
+
+ def test_the_summary_and_the_opening_come_from_the_same_read(self, tmp_path: Path) -> None:
+ _grok_session(tmp_path, _grok_rows())
+ turns = agent_transcript.read("grok-build", "grok-1", home=tmp_path)
+ assert turns is not None
+ assert [(t.role, len(t.steps)) for t in turns] == [("user", 0), ("assistant", 2)]
+ assert turns[1].text == "Looking.\n\nDone."
+ assert turns[1].steps[0].tool == "read_file"
+ assert agent_transcript.first_user_text("grok-build", "grok-1", home=tmp_path) == (
+ "Fix the sidebar"
+ )
+
+ def test_a_pane_still_working_keeps_its_turn_open(self, tmp_path: Path) -> None:
+ rows = _grok_rows()[:4] # asked, and thinking
+ _grok_session(tmp_path, rows)
+ events = agent_transcript.read_events("grok-build", "grok-1", home=tmp_path, live=True)
+ assert events is not None
+ assert _kinds(events) == [
+ "user_message",
+ "turn_started",
+ "reasoning_started",
+ "reasoning_delta",
+ ]
+ assert _by_kind(events, "reasoning_delta")[0]["text"] == "The user wants a fix."
+
+ def test_no_file_yet_is_none_and_a_bare_hook_run_is_silence(self, tmp_path: Path) -> None:
+ assert agent_transcript.read_events("grok-build", "grok-1", home=tmp_path) is None
+ assert agent_transcript.read_events("grok-build", "../x", home=tmp_path) is None
+ _grok_session(tmp_path, _grok_rows()[:1])
+ assert agent_transcript.first_user_text("grok-build", "grok-1", home=tmp_path) == ""
+ events = agent_transcript.read_events("grok-build", "grok-1", home=tmp_path)
+ assert events == []
+
+
+# --------------------------------------------------------------------------- #
+# Antigravity
+# --------------------------------------------------------------------------- #
+
+
+def _agy_session(home: Path, rows: list[dict]) -> None:
+ _write(
+ home
+ / ".gemini"
+ / "antigravity-cli"
+ / "brain"
+ / "agy-1"
+ / ".system_generated"
+ / "logs"
+ / "transcript.jsonl",
+ rows,
+ )
+
+
+def _agy_step(index: int, kind: str, source: str, at: str, **fields: object) -> dict:
+ return {
+ "step_index": index,
+ "source": source,
+ "type": kind,
+ "status": "DONE",
+ "created_at": f"2026-08-25T17:57:{at}Z",
+ **fields,
+ }
+
+
+class TestAntigravity:
+ def test_reads_steps_in_order_and_pairs_outputs_with_calls(self, tmp_path: Path) -> None:
+ _agy_session(
+ tmp_path,
+ [
+ _agy_step(
+ 0,
+ "USER_INPUT",
+ "USER_EXPLICIT",
+ "30",
+ content=(
+ "<USER_REQUEST>\nSwap the hero screenshot\n</USER_REQUEST>\n"
+ "<ADDITIONAL_METADATA>\nThe current local time is: x\n"
+ "</ADDITIONAL_METADATA>"
+ ),
+ ),
+ _agy_step(1, "CHECKPOINT", "SYSTEM", "30", content="{{ CHECKPOINT 0 }}"),
+ _agy_step(
+ 2,
+ "PLANNER_RESPONSE",
+ "MODEL",
+ "32",
+ thinking="**Examine the Image**\n\nLooking at it.",
+ tool_calls=[
+ {
+ "name": "find_by_name",
+ "args": {
+ "MaxDepth": "4",
+ "Pattern": '"*.png"',
+ "SearchDirectory": '"C:/work/src"',
+ },
+ },
+ {"name": "view_file", "args": {"AbsolutePath": '"C:/work/a.png"'}},
+ ],
+ ),
+ _agy_step(3, "GENERIC", "MODEL", "35", content="Found 2 results\na.png\nb.png"),
+ _agy_step(4, "GENERIC", "MODEL", "36", content="The image shows a sidebar."),
+ _agy_step(
+ 5,
+ "ERROR_MESSAGE",
+ "SYSTEM",
+ "40",
+ content="Error: model output error, please try again",
+ ),
+ _agy_step(
+ 6,
+ "PLANNER_RESPONSE",
+ "MODEL",
+ "45",
+ content="The screenshot was swapped.",
+ ),
+ ],
+ )
+ events = agent_transcript.read_events("antigravity", "agy-1", home=tmp_path)
+ assert events is not None
+ assert _kinds(events) == [
+ "user_message",
+ "turn_started",
+ "reasoning",
+ "tool_call",
+ "tool_call",
+ "tool_result",
+ "tool_result",
+ "assistant_text",
+ "assistant_text",
+ "turn_finished",
+ ]
+ assert _by_kind(events, "user_message")[0]["text"] == "Swap the hero screenshot"
+ calls = _by_kind(events, "tool_call")
+ # JSON strings inside JSON come out as what they encode.
+ assert calls[0]["input"] == {
+ "MaxDepth": 4, # "4" in the file: JSON inside JSON, decoded once
+ "Pattern": "*.png",
+ "SearchDirectory": "C:/work/src",
+ }
+ assert calls[0]["summary"] == "*.png"
+ assert calls[1]["summary"] == "C:/work/a.png"
+ results = _by_kind(events, "tool_result")
+ assert [r["call_id"] for r in results] == [calls[0]["call_id"], calls[1]["call_id"]]
+ assert results[0]["output"].startswith("Found 2 results")
+ assert results[0]["duration_ms"] == 3_000
+ texts = _by_kind(events, "assistant_text")
+ assert texts[0]["text"].startswith("Error: model output error")
+ assert texts[1]["text"] == "The screenshot was swapped."
+ assert agent_transcript.first_user_text("antigravity", "agy-1", home=tmp_path) == (
+ "Swap the hero screenshot"
+ )
+
+ def test_an_unknown_conversation_is_none(self, tmp_path: Path) -> None:
+ assert agent_transcript.read_events("antigravity", "agy-9", home=tmp_path) is None
+ assert agent_transcript.read("antigravity", "", home=tmp_path) is None
+
+
+# --------------------------------------------------------------------------- #
+# OpenCode
+# --------------------------------------------------------------------------- #
+
+_OPENCODE_SCHEMA = """
+CREATE TABLE session (
+ id TEXT PRIMARY KEY, project_id TEXT NOT NULL DEFAULT '', parent_id TEXT,
+ slug TEXT NOT NULL DEFAULT '', directory TEXT NOT NULL, title TEXT NOT NULL DEFAULT '',
+ version TEXT NOT NULL DEFAULT '', time_created INTEGER NOT NULL,
+ time_updated INTEGER NOT NULL
+);
+CREATE TABLE message (
+ id TEXT PRIMARY KEY, session_id TEXT NOT NULL, time_created INTEGER NOT NULL,
+ time_updated INTEGER NOT NULL, data TEXT NOT NULL
+);
+CREATE TABLE part (
+ id TEXT PRIMARY KEY, message_id TEXT NOT NULL, session_id TEXT NOT NULL,
+ time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, data TEXT NOT NULL
+);
+"""
+
+
+def _opencode_db(home: Path) -> None:
+ home.mkdir(parents=True, exist_ok=True)
+ con = sqlite3.connect(home / "opencode.db")
+ con.executescript(_OPENCODE_SCHEMA)
+ con.execute(
+ "INSERT INTO session (id, directory, time_created, time_updated) VALUES (?, ?, ?, ?)",
+ ("ses_1", "C:/work", 1_000, 9_000),
+ )
+ con.execute(
+ "INSERT INTO session (id, directory, time_created, time_updated) VALUES (?, ?, ?, ?)",
+ ("ses_empty", "C:/work", 1_000, 1_000),
+ )
+
+ def _clocked(data: dict) -> dict:
+ """Every timestamp in a row's body moved onto the real clock."""
+ out: dict = {}
+ for key, value in data.items():
+ if key == "time" and isinstance(value, dict):
+ out[key] = {k: v + T0 for k, v in value.items()}
+ else:
+ out[key] = value
+ return out
+
+ def message(mid: str, at: int, data: dict) -> None:
+ con.execute(
+ "INSERT INTO message VALUES (?, ?, ?, ?, ?)",
+ (mid, "ses_1", T0 + at, T0 + at, json.dumps(_clocked(data))),
+ )
+
+ def part(pid: str, mid: str, at: int, updated: int, data: dict) -> None:
+ if isinstance(data.get("state"), dict):
+ data = {**data, "state": _clocked(data["state"])}
+ con.execute(
+ "INSERT INTO part VALUES (?, ?, ?, ?, ?, ?)",
+ (pid, mid, "ses_1", T0 + at, T0 + updated, json.dumps(_clocked(data))),
+ )
+
+ message(
+ "msg_u",
+ 1_000,
+ {
+ "role": "user",
+ "time": {"created": 1_000},
+ "model": {"providerID": "opencode", "modelID": "muse-spark-1.2", "variant": "xhigh"},
+ },
+ )
+ part("prt_u", "msg_u", 1_010, 1_010, {"type": "text", "text": "Link me to localhost"})
+ message(
+ "msg_a",
+ 2_000,
+ {
+ "parentID": "msg_u",
+ "role": "assistant",
+ "variant": "xhigh",
+ "modelID": "muse-spark-1.2",
+ "providerID": "opencode",
+ "tokens": {
+ "total": 300,
+ "input": 200,
+ "output": 60,
+ "reasoning": 40,
+ "cache": {"write": 0, "read": 150},
+ },
+ "time": {"created": 2_000, "completed": 6_000},
+ "finish": "stop",
+ },
+ )
+ part("prt_s", "msg_a", 2_100, 2_100, {"type": "step-start", "snapshot": "abc"})
+ part(
+ "prt_r",
+ "msg_a",
+ 2_200,
+ 2_200,
+ {
+ "type": "reasoning",
+ "text": "Localhost is local.",
+ "time": {"start": 2_200, "end": 3_000},
+ "metadata": {"openai": {"itemId": "rs_1"}},
+ },
+ )
+ part(
+ "prt_t",
+ "msg_a",
+ 3_100,
+ 3_400,
+ {
+ "type": "tool",
+ "tool": "read",
+ "callID": "call_1",
+ "state": {
+ "status": "completed",
+ "input": {"filePath": "C:/work/run.bat"},
+ "output": "@echo off",
+ "title": "C:/work/run.bat",
+ "time": {"start": 3_100, "end": 3_350},
+ },
+ },
+ )
+ part(
+ "prt_e",
+ "msg_a",
+ 3_500,
+ 3_800,
+ {
+ "type": "tool",
+ "tool": "bash",
+ "callID": "call_2",
+ "state": {
+ "status": "error",
+ "input": {"command": "curl 127.0.0.1"},
+ "error": "connection refused",
+ },
+ },
+ )
+ part("prt_x", "msg_a", 4_000, 4_000, {"type": "text", "text": "Open http://127.0.0.1:47821"})
+ part(
+ "prt_f",
+ "msg_a",
+ 4_100,
+ 4_100,
+ {"type": "step-finish", "reason": "stop", "tokens": {"input": 200, "output": 60}},
+ )
+ con.commit()
+ con.close()
+
+
+class TestOpenCode:
+ def test_messages_and_parts_become_the_chat_events(self, tmp_path: Path) -> None:
+ _opencode_db(tmp_path)
+ log = agent_transcript._opencode_events("ses_1", tmp_path, False)
+ assert log is not None and (log.model, log.effort) == ("muse-spark-1.2", "xhigh")
+ events = agent_transcript.read_events("opencode", "ses_1", home=tmp_path)
+ assert events is not None
+ assert _kinds(events) == [
+ "user_message",
+ "turn_started",
+ "reasoning",
+ "tool_call",
+ "tool_result",
+ "tool_call",
+ "tool_result",
+ "assistant_text",
+ "usage_delta",
+ "turn_finished",
+ ]
+ assert _by_kind(events, "user_message")[0]["text"] == "Link me to localhost"
+ thought = _by_kind(events, "reasoning")[0]
+ assert thought["text"] == "Localhost is local."
+ # Timed from its own start to the call that followed it.
+ assert thought["duration_ms"] == 900
+ calls = _by_kind(events, "tool_call")
+ assert [(c["name"], c["summary"]) for c in calls] == [
+ ("read", "C:/work/run.bat"),
+ ("bash", "curl 127.0.0.1"),
+ ]
+ results = _by_kind(events, "tool_result")
+ assert results[0]["output"] == "@echo off"
+ assert results[0]["duration_ms"] == 250
+ assert results[1]["is_error"] is True
+ assert results[1]["output"] == "connection refused"
+ # The error's end is the part's last write.
+ assert results[1]["duration_ms"] == 300
+ usage = _by_kind(events, "turn_finished")[0]["usage"]
+ assert usage == {
+ "input_tokens": 200,
+ "output_tokens": 60,
+ "thinking_tokens": 40,
+ "cache_read_input_tokens": 150,
+ "cache_creation_input_tokens": 0,
+ }
+ turns = agent_transcript.read("opencode", "ses_1", home=tmp_path)
+ assert turns is not None
+ assert [(t.role, len(t.steps)) for t in turns] == [("user", 0), ("assistant", 2)]
+
+ def test_a_session_with_nothing_said_is_available_and_empty(self, tmp_path: Path) -> None:
+ _opencode_db(tmp_path)
+ events = agent_transcript.read_events("opencode", "ses_empty", home=tmp_path)
+ assert events == []
+ assert agent_transcript.first_user_text("opencode", "ses_empty", home=tmp_path) == ""
+
+ def test_an_unknown_session_or_database_is_none(self, tmp_path: Path) -> None:
+ assert agent_transcript.read_events("opencode", "ses_1", home=tmp_path) is None
+ _opencode_db(tmp_path)
+ assert agent_transcript.read_events("opencode", "ses_nope", home=tmp_path) is None
+
+
+# --------------------------------------------------------------------------- #
+# Kimi
+# --------------------------------------------------------------------------- #
+
+
+def _wire(kind: str, payload: dict, at: float) -> dict:
+ return {"timestamp": at, "message": {"type": kind, "payload": payload}}
+
+
+class TestKimiLegacyWire:
+ def test_reads_the_wrapped_records_and_late_arguments(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path / "sessions" / "0123abcd" / "kimi-1" / "wire.jsonl",
+ [
+ {"type": "metadata", "protocol_version": "1.1"},
+ _wire(
+ "TurnBegin",
+ {"user_input": [{"type": "text", "text": "Where did we stop?"}]},
+ 100.0,
+ ),
+ _wire("StepBegin", {"n": 1}, 100.1),
+ _wire(
+ "ContentPart", {"type": "think", "think": "They ask about the webhook."}, 101.0
+ ),
+ _wire("ContentPart", {"type": "text", "text": "Let me check the notes."}, 102.0),
+ _wire(
+ "ToolCall",
+ {
+ "type": "function",
+ "id": "tool_a",
+ "function": {"name": "ReadFile", "arguments": '{"path": "NOTES.md"}'},
+ },
+ 103.0,
+ ),
+ # A second call whose arguments stream in AFTER the first call's
+ # result — measured on the legacy wire.
+ _wire(
+ "ToolCall",
+ {"type": "function", "id": "tool_b", "function": {"name": "ReadFile"}},
+ 103.1,
+ ),
+ _wire(
+ "ToolResult",
+ {
+ "tool_call_id": "tool_a",
+ "return_value": {"is_error": False, "output": "# Notes"},
+ },
+ 103.5,
+ ),
+ _wire("ToolCallPart", {"arguments_part": '{"path": "Code.gs"}'}, 103.6),
+ _wire(
+ "StatusUpdate",
+ {
+ "token_usage": {
+ "input_other": 1384,
+ "output": 184,
+ "input_cache_read": 4864,
+ "input_cache_creation": 0,
+ },
+ "message_id": "chatcmpl-1",
+ },
+ 103.7,
+ ),
+ _wire(
+ "ToolResult",
+ {
+ "tool_call_id": "tool_b",
+ "return_value": {"is_error": True, "output": "no such file"},
+ },
+ 104.0,
+ ),
+ _wire("ContentPart", {"type": "text", "text": "Here is the plan."}, 105.0),
+ ],
+ )
+ events = agent_transcript.read_events("kimi", "kimi-1", home=tmp_path)
+ assert events is not None
+ assert _kinds(events) == [
+ "user_message",
+ "turn_started",
+ "reasoning",
+ "assistant_text",
+ "tool_call",
+ "tool_result",
+ "tool_call",
+ "usage_delta",
+ "tool_result",
+ "assistant_text",
+ "turn_finished",
+ ]
+ calls = _by_kind(events, "tool_call")
+ assert [(c["call_id"], c["summary"]) for c in calls] == [
+ ("tool_a", "NOTES.md"),
+ ("tool_b", "Code.gs"),
+ ]
+ assert calls[0]["input"] == {"path": "NOTES.md"}
+ results = _by_kind(events, "tool_result")
+ assert results[0] == {
+ "turn_id": "turn-1",
+ "call_id": "tool_a",
+ "output": "# Notes",
+ "is_error": False,
+ "duration_ms": 500,
+ }
+ assert results[1]["is_error"] is True
+ assert _by_kind(events, "turn_finished")[0]["usage"] == {
+ "input_tokens": 1384,
+ "output_tokens": 184,
+ "cache_read_input_tokens": 4864,
+ "cache_creation_input_tokens": 0,
+ }
+ assert agent_transcript.first_user_text("kimi", "kimi-1", home=tmp_path) == (
+ "Where did we stop?"
+ )
+
+
+class TestKimiCurrentWire:
+ def test_reads_the_flat_records_without_doubling_the_prompt(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path
+ / "sessions"
+ / "wd_work_1fce0659c7a0"
+ / "session_k2"
+ / "agents"
+ / "main"
+ / "wire.jsonl",
+ [
+ {"type": "metadata", "protocol_version": "1.4", "created_at": 1_000},
+ {"type": "config.update", "profileName": "agent", "time": T0 + 1_000},
+ {"type": "tools.set_active_tools", "names": ["Read"], "time": T0 + 1_000},
+ # The prompt is logged twice: as the turn's input and as the
+ # message it becomes. Once is enough.
+ {
+ "type": "turn.prompt",
+ "input": [{"type": "text", "text": "Rename the helper"}],
+ "origin": {"kind": "user"},
+ "time": T0 + 2_000,
+ },
+ {
+ "type": "context.append_message",
+ "message": {
+ "role": "user",
+ "content": [{"type": "text", "text": "Rename the helper"}],
+ "toolCalls": [],
+ "origin": {"kind": "user"},
+ },
+ "time": T0 + 2_000,
+ },
+ # A reminder the harness appends in the user's name.
+ {
+ "type": "context.append_message",
+ "message": {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "<system-reminder>\nbe brief\n</system-reminder>",
+ }
+ ],
+ "toolCalls": [],
+ "origin": {"kind": "injection", "variant": "reminder"},
+ },
+ "time": T0 + 2_001,
+ },
+ {
+ "type": "context.append_loop_event",
+ "event": {"type": "step.begin", "uuid": "s1", "turnId": "1", "step": 1},
+ "time": T0 + 2_100,
+ },
+ {
+ "type": "context.append_loop_event",
+ "event": {
+ "type": "content.part",
+ "uuid": "p1",
+ "turnId": "1",
+ "step": 1,
+ "part": {"type": "think", "think": "Find its callers first."},
+ },
+ "time": T0 + 2_200,
+ },
+ {
+ "type": "context.append_loop_event",
+ "event": {
+ "type": "tool.call",
+ "uuid": "c1",
+ "toolCallId": "c1",
+ "name": "Grep",
+ "args": {"pattern": "helper("},
+ },
+ "time": T0 + 3_000,
+ },
+ {
+ "type": "context.append_loop_event",
+ "event": {
+ "type": "tool.result",
+ "parentUuid": "c1",
+ "toolCallId": "c1",
+ "result": {"output": "a.py:3", "isError": False},
+ },
+ "time": T0 + 3_200,
+ },
+ {
+ "type": "context.append_loop_event",
+ "event": {
+ "type": "step.end",
+ "uuid": "s1",
+ "usage": {"inputOther": 900, "output": 40, "inputCacheRead": 100},
+ "finishReason": "completed",
+ },
+ "time": T0 + 3_300,
+ },
+ {"type": "usage.record", "model": "kimi-k2.5", "usage": {}, "time": T0 + 3_300},
+ {
+ "type": "context.append_loop_event",
+ "event": {
+ "type": "content.part",
+ "uuid": "p2",
+ "part": {"type": "text", "text": "Two callers, both renamed."},
+ },
+ "time": T0 + 4_000,
+ },
+ ],
+ )
+ log = agent_transcript._kimi_events("session_k2", tmp_path, False)
+ assert log is not None and log.model == "kimi-k2.5"
+ events = agent_transcript.read_events("kimi", "session_k2", home=tmp_path)
+ assert events is not None
+ assert _kinds(events) == [
+ "user_message",
+ "turn_started",
+ "reasoning",
+ "tool_call",
+ "tool_result",
+ "usage_delta",
+ "assistant_text",
+ "turn_finished",
+ ]
+ assert _by_kind(events, "user_message")[0]["text"] == "Rename the helper"
+ assert _by_kind(events, "reasoning")[0]["duration_ms"] == 800
+ assert _by_kind(events, "tool_call")[0]["summary"] == "helper("
+ assert _by_kind(events, "tool_result")[0]["duration_ms"] == 200
+ assert _by_kind(events, "turn_finished")[0]["usage"] == {
+ "input_tokens": 900,
+ "output_tokens": 40,
+ "cache_read_input_tokens": 100,
+ }
+
+ def test_a_session_that_only_opened_is_silence_not_absence(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path / "sessions" / "wd_work_1" / "session_k3" / "agents" / "main" / "wire.jsonl",
+ [
+ {"type": "metadata", "protocol_version": "1.4", "created_at": 1_000},
+ {"type": "config.update", "profileName": "agent", "time": T0 + 1_000},
+ ],
+ )
+ assert agent_transcript.first_user_text("kimi", "session_k3", home=tmp_path) == ""
+ assert agent_transcript.first_user_text("kimi", "session_k4", home=tmp_path) is None
+
+
+# --------------------------------------------------------------------------- #
+# the registry
+# --------------------------------------------------------------------------- #
+
+
+class TestRegistry:
+ def test_every_cli_with_a_record_is_readable_and_the_rest_are_not(self) -> None:
+ for agent in ("claude", "codex", "grok-build", "antigravity", "opencode", "kimi"):
+ assert agent_transcript.can_read(agent) is True, agent
+ # DeepSeek Harness runs its chat in the browser — the pane holds no
+ # conversation — and a plain shell has none.
+ assert agent_transcript.can_read("deepseek-harness") is False
+ assert agent_transcript.can_read("plain") is False
+ assert agent_transcript.can_read("") is False
+
+ def test_a_launch_profile_reads_through_the_binary_it_runs(self, tmp_path: Path) -> None:
+ """GLM Coding Plan IS Claude Code pointed elsewhere — so is its record."""
+ assert agent_transcript._agent_key("GLM ") == "claude"
+ assert agent_transcript._agent_key("some-new-cli") == "some-new-cli"
+ assert agent_transcript.can_read("glm") is True
+ _write(
+ tmp_path / "projects" / "C--work" / "abc.jsonl",
+ [
+ {
+ "type": "user",
+ "timestamp": "2026-08-27T10:00:00.000Z",
+ "uuid": "u1",
+ "message": {"role": "user", "content": "Port the parser"},
+ },
+ {
+ "type": "assistant",
+ "timestamp": "2026-08-27T10:00:05.000Z",
+ "uuid": "a1",
+ "message": {
+ "id": "m1",
+ "model": "glm-5",
+ "role": "assistant",
+ "content": [{"type": "text", "text": "On it."}],
+ },
+ },
+ ],
+ )
+ events = agent_transcript.read_events("glm", "abc", home=tmp_path)
+ assert events is not None
+ assert _by_kind(events, "user_message")[0]["text"] == "Port the parser"
+ assert agent_transcript.first_user_text("glm", "abc", home=tmp_path) == "Port the parser"
+
+ def test_the_opening_is_unknown_once_the_window_is_full(self, tmp_path: Path) -> None:
+ """A window on the recent past cannot name a session's first message."""
+ rows: list[dict] = []
+ for index in range(agent_transcript.MAX_TURNS + 1):
+ rows.append(
+ _grok_update(
+ {
+ "sessionUpdate": "user_message_chunk",
+ "content": {"type": "text", "text": f"question {index}"},
+ "_meta": {"modelId": "grok-4.6", "promptIndex": index},
+ },
+ 1_000 + index * 10,
+ )
+ )
+ _grok_session(tmp_path, rows)
+ assert agent_transcript.first_user_text("grok-build", "grok-1", home=tmp_path) == ""