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(missions): record gemini worker runs as structured streams

rubenluetke10-beep50bed900b5f6
diff --git a/jarvis/missions/stream_evidence.py b/jarvis/missions/stream_evidence.py
index b8c2f9448b..25de8fa76c 100644
--- a/jarvis/missions/stream_evidence.py
+++ b/jarvis/missions/stream_evidence.py
@@ -73,6 +73,37 @@ _CLAUDE_FRAME_TYPES: frozenset[str] = frozenset(
# (the extractors truncate again to ``max_result_chars`` downstream).
_CODEX_OUTPUT_CAP: int = 4000
+# Gemini CLI `--output-format stream-json` frame types (flat NDJSON events):
+# {type:"init", timestamp, session_id, model}
+# {type:"message", timestamp, role:"user"|"assistant", content, delta?}
+# {type:"tool_use", timestamp, tool_name, tool_id, parameters}
+# {type:"tool_result", timestamp, tool_id, status:"success"|"error", output?, error?}
+# {type:"error", timestamp, severity, message}
+# {type:"result", timestamp, status, stats} <- stats only, NO answer text
+# Schema verified against the installed bundle (gemini-cli 0.47.0,
+# packages/cli nonInteractiveCli emit sites, read 2026-08-12). The answer text
+# exists only as assistant `delta:true` chunks; they split words mid-token, so
+# they are concatenated RAW — inserting any separator would corrupt words.
+_GEMINI_FRAME_TYPES: frozenset[str] = frozenset(
+ {"init", "message", "tool_use", "tool_result", "error"}
+)
+
+
+def _is_gemini_result(obj: dict) -> bool: # noqa: ANN001 — tolerant of arbitrary dicts
+ """A gemini terminal frame — collides with claude's ``result`` type.
+
+ Claude's result frame carries the answer under ``result`` and no ISO
+ ``timestamp``; gemini's carries ``timestamp`` + ``status``/``stats`` and
+ never ``result``. All three checks together keep a claude frame from ever
+ being misread.
+ """
+ return (
+ obj.get("type") == "result"
+ and "result" not in obj
+ and "timestamp" in obj
+ and ("status" in obj or "stats" in obj)
+ )
+
def _codex_item_to_claude_lines(
item: dict, counter: int
@@ -170,9 +201,11 @@ def _normalize_worker_stream(stream_text: str) -> str:
"""Rewrite codex / gemini worker streams into the canonical claude shape.
See the module note above. A pure-claude stream returns unchanged; codex
- ``item.completed`` frames become assistant/user pairs; a gemini plain-text
- transcript (no JSON frames at all) becomes a single ``result`` frame so the
- spoken answer is recoverable.
+ ``item.completed`` frames become assistant/user pairs; gemini
+ ``--output-format stream-json`` events (tool_use/tool_result/message
+ deltas) become the equivalent claude frames; a legacy gemini plain-text
+ transcript (no JSON frames at all) becomes a single ``result`` frame so
+ the spoken answer is recoverable.
"""
if not stream_text:
return stream_text
@@ -181,6 +214,31 @@ def _normalize_worker_stream(stream_text: str) -> str:
saw_json = False
counter = 0
+ # Gemini state: assistant delta chunks since the last flush, concatenated
+ # RAW (deltas split words mid-token), and the last flushed segment — the
+ # candidate final answer, since gemini's result frame carries only stats.
+ gem_text: list[str] = []
+ gem_last_segment = ""
+
+ def _flush_gemini_text() -> None:
+ nonlocal gem_last_segment
+ text = "".join(gem_text).strip()
+ gem_text.clear()
+ if not text:
+ return
+ gem_last_segment = text
+ out.append(
+ json.dumps(
+ {
+ "type": "assistant",
+ "message": {
+ "role": "assistant",
+ "content": [{"type": "text", "text": text}],
+ },
+ }
+ )
+ )
+
for raw in stream_text.splitlines():
line = raw.strip()
if not line:
@@ -195,6 +253,68 @@ def _normalize_worker_stream(stream_text: str) -> str:
continue
saw_json = True
otype = obj.get("type")
+ # Gemini before the claude passthrough: its ``result`` frame shares
+ # claude's type name and must not slip through unrewritten.
+ if otype in _GEMINI_FRAME_TYPES or _is_gemini_result(obj):
+ if otype == "message":
+ if obj.get("role") == "assistant":
+ chunk = obj.get("content")
+ if isinstance(chunk, str) and chunk:
+ gem_text.append(chunk)
+ # The echoed user prompt is not worker evidence — dropped.
+ elif otype == "tool_use":
+ _flush_gemini_text()
+ counter += 1
+ tid = str(obj.get("tool_id") or f"gemini_tool_{counter}")
+ name = str(obj.get("tool_name") or "tool").strip() or "tool"
+ params = obj.get("parameters")
+ out.append(
+ json.dumps(
+ {
+ "type": "assistant",
+ "message": {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": tid,
+ "name": name,
+ "input": params if isinstance(params, dict) else {},
+ }
+ ],
+ },
+ }
+ )
+ )
+ elif otype == "tool_result":
+ tid = str(obj.get("tool_id") or "")
+ is_error = str(obj.get("status") or "").strip().lower() == "error"
+ content = str(obj.get("output") or "")
+ if is_error and not content:
+ err = obj.get("error")
+ msg = str(err.get("message") or "") if isinstance(err, dict) else ""
+ content = msg or "tool call failed"
+ blk: dict = {
+ "type": "tool_result",
+ "tool_use_id": tid,
+ "content": content[:_CODEX_OUTPUT_CAP],
+ }
+ if is_error:
+ blk["is_error"] = True
+ out.append(
+ json.dumps(
+ {"type": "user", "message": {"role": "user", "content": [blk]}}
+ )
+ )
+ elif otype == "result":
+ # Terminal frame: the answer is whatever the assistant last
+ # said — flush and restate it as a claude result frame so
+ # every extractor sees the same spoken answer.
+ _flush_gemini_text()
+ if gem_last_segment:
+ out.append(json.dumps({"type": "result", "result": gem_last_segment}))
+ # init / error frames carry no deliverable evidence — dropped.
+ continue
if otype in _CLAUDE_FRAME_TYPES:
out.append(line) # claude frame — passed through unchanged
continue
@@ -207,6 +327,11 @@ def _normalize_worker_stream(stream_text: str) -> str:
# Any other codex frame (thread.started / turn.* / error / item.created
# / item.delta) carries no deliverable evidence — drop it.
+ # A killed gemini worker can end mid-stream with buffered deltas and no
+ # result frame — the words it DID say are still evidence, so they flush;
+ # only the synthetic result frame stays absent (anti-hearsay).
+ _flush_gemini_text()
+
# Gemini `--output-format text`: the whole transcript is plain text with no
# JSON frames. Treat it as the worker's final answer so the spoken answer is
# recoverable. Gated on NOTHING having parsed as JSON, so a stray non-JSON
@@ -300,6 +425,9 @@ def extract_stream_evidence(
_WRITE_TOOL_NAMES: frozenset[str] = frozenset({
"Write", "Edit", "MultiEdit", "NotebookEdit",
"file_write", "write_file", "create_file",
+ # gemini-cli's edit tool is literally named "replace" (params carry
+ # file_path); no other backend uses that name.
+ "replace",
})
# Keys under `tool_use.input` that carry the target path, in priority order.
diff --git a/jarvis/missions/workers/gemini_worker.py b/jarvis/missions/workers/gemini_worker.py
index c7b5c535c0..567d828667 100644
--- a/jarvis/missions/workers/gemini_worker.py
+++ b/jarvis/missions/workers/gemini_worker.py
@@ -10,15 +10,21 @@ Cmd-Layout:
gemini --prompt <prompt>
--model <gemini-3.1-pro-preview | gemini-3-flash-preview | ...>
--yolo
- --output-format text
-
-We deliberately use plain `text` output instead of `stream-json`: the
-Gemini CLI's stream-json schema isn't a 1:1 match for the Claude
-schema we already parse, and the Kontrollierer doesn't need
-intermediate stream events — only WorkerSpawned + a terminal result so
-the diff-collector + Critic can take over. Yielding two synthetic
-`Claude*`-shaped events keeps the orchestrator code path unchanged
-(field shape mirrors `ClaudeSystemInit` + `ClaudeResult`).
+ --output-format stream-json
+
+`stream-json` (not `text`): the archived ``stream.jsonl`` is the ONLY
+record of what a worker actually did — the Critic's evidence and the
+Visualization's node graph are both reconstructed from it. Text mode
+recorded nothing but the final prose, so gemini runs drew as bare
+Request → Result cards forever. The gemini event schema isn't the
+claude shape, but :func:`jarvis.missions.stream_evidence.
+normalize_worker_stream` rewrites it (verified against the installed
+CLI 0.47.0 bundle), so every downstream reader stays unchanged. The
+worker still yields only the two synthetic `Claude*`-shaped events
+(`ClaudeSystemInit` + `ClaudeResult`) — the orchestrator path is
+untouched; the final answer is assembled from the stream's assistant
+deltas, falling back to raw stdout for an older CLI that ignores the
+format flag.
Spawn discipline:
- Routed through `create_worker_subprocess` (NO shell=True, NO PTY); that
@@ -46,6 +52,8 @@ from contextlib import suppress
from pathlib import Path
from typing import Any, Literal
+from jarvis.missions.stream_evidence import extract_stream_evidence
+
from .capabilities import WorkerCapabilityInventory
from .process_utils import create_worker_subprocess
from .stream_consumer import ClaudeResult, ClaudeSystemInit
@@ -253,7 +261,7 @@ def _build_gemini_cmd(
"--model",
model,
"--output-format",
- "text",
+ "stream-json",
]
if yolo:
cmd.append("--yolo")
@@ -530,12 +538,17 @@ class GeminiWorker:
wall_ms = int((time.perf_counter() - t0) * 1000)
is_error = exit_code != 0
- # Cost + tokens aren't reported by Gemini CLI in text mode. Leave
- # them at None; the orchestrator falls back to 0 via the
+ # Cost + tokens aren't consumed from the stream's stats frame yet.
+ # Leave them at None; the orchestrator falls back to 0 via the
# `tokens_used → total_tokens → num_turns` chain (also None here).
- # Stamp the assistant's textual reply into `result` so the Critic
- # can read it as part of the log summary if needed.
- result_text = stdout_bytes.decode("utf-8", errors="replace")
+ # The spoken answer is assembled from the stream-json assistant
+ # deltas via the shared canonicalizer; raw stdout is the fallback
+ # for an older CLI that emitted plain text despite the flag.
+ stdout_text = stdout_bytes.decode("utf-8", errors="replace")
+ result_text = (
+ extract_stream_evidence(stdout_text, max_result_chars=400).final_answer
+ or stdout_text
+ )
if is_error and stderr_bytes:
tail = stderr_bytes.decode("utf-8", errors="replace")[-300:]
result_text = (result_text or "") + f"\n[stderr-tail]\n{tail}"
diff --git a/jarvis/ui/web/frontend/src/lib/nodeSpec.ts b/jarvis/ui/web/frontend/src/lib/nodeSpec.ts
index 8585a5ee55..a2a30f2b3f 100644
--- a/jarvis/ui/web/frontend/src/lib/nodeSpec.ts
+++ b/jarvis/ui/web/frontend/src/lib/nodeSpec.ts
@@ -137,8 +137,21 @@ const FILE_TOOLS = new Set([
"file_write",
"write_file",
"create_file",
+ "replace", // gemini-cli's edit tool
+]);
+const SEARCH_TOOLS = new Set([
+ "read",
+ "glob",
+ "grep",
+ "search",
+ "ls",
+ "list_files",
+ // gemini-cli's read/search family
+ "read_file",
+ "read_many_files",
+ "search_file_content",
+ "list_directory",
]);
-const SEARCH_TOOLS = new Set(["read", "glob", "grep", "search", "ls", "list_files"]);
/** Which category a tool call belongs to — the n8n-style family sort. */
export function toolCategory(toolName: string | null | undefined): NodeCategory {
diff --git a/jarvis/ui/web/run_plan.py b/jarvis/ui/web/run_plan.py
index 6f597084ef..20e09a3874 100644
--- a/jarvis/ui/web/run_plan.py
+++ b/jarvis/ui/web/run_plan.py
@@ -82,7 +82,17 @@ _DETAIL_KEYS: Final[tuple[str, ...]] = (
# step (``writes``) so the frontend can connect an artifact node to the exact
# step that produced it. Mirrors ``stream_evidence._WRITE_TOOL_NAMES``.
_WRITE_TOOL_NAMES: Final[frozenset[str]] = frozenset(
- {"Write", "Edit", "MultiEdit", "NotebookEdit", "file_write", "write_file", "create_file"}
+ {
+ "Write",
+ "Edit",
+ "MultiEdit",
+ "NotebookEdit",
+ "file_write",
+ "write_file",
+ "create_file",
+ # gemini-cli's edit tool ("replace") — params carry file_path.
+ "replace",
+ }
)
# Tool names (lowercased) that launch a sub-agent rather than acting directly.
diff --git a/tests/missions/test_stream_evidence_multiprovider.py b/tests/missions/test_stream_evidence_multiprovider.py
index de61861bb9..c1e1f44acb 100644
--- a/tests/missions/test_stream_evidence_multiprovider.py
+++ b/tests/missions/test_stream_evidence_multiprovider.py
@@ -25,6 +25,7 @@ from jarvis.missions.stream_evidence import (
extract_verified_commands,
extract_verified_desktop_actions,
extract_write_targets,
+ normalize_worker_stream,
readonly_answer,
)
@@ -126,6 +127,126 @@ def test_gemini_plain_text_informational_is_spoken_back() -> None:
assert "Sydney" in answer
+# --- gemini: `--output-format stream-json` (CLI 0.47.0 shapes) ---------------
+# Frame shapes verified against the installed bundle's emit sites (2026-08-12).
+_GEM_TS = "2026-08-12T17:00:00.000Z"
+
+
+def _gem_msg(content: str, *, role: str = "assistant") -> str:
+ return json.dumps(
+ {
+ "type": "message",
+ "timestamp": _GEM_TS,
+ "role": role,
+ "content": content,
+ **({"delta": True} if role == "assistant" else {}),
+ }
+ )
+
+
+def _gem_tool_use(name: str, params: dict, tid: str) -> str:
+ return json.dumps(
+ {
+ "type": "tool_use",
+ "timestamp": _GEM_TS,
+ "tool_name": name,
+ "tool_id": tid,
+ "parameters": params,
+ }
+ )
+
+
+def _gem_tool_result(tid: str, *, status: str = "success", output: str = "") -> str:
+ return json.dumps(
+ {
+ "type": "tool_result",
+ "timestamp": _GEM_TS,
+ "tool_id": tid,
+ "status": status,
+ "output": output,
+ }
+ )
+
+
+def _gem_result() -> str:
+ return json.dumps(
+ {
+ "type": "result",
+ "timestamp": _GEM_TS,
+ "status": "success",
+ "stats": {"total_tokens": 1},
+ }
+ )
+
+
+def test_gemini_stream_json_write_is_credited() -> None:
+ stream = "\n".join(
+ [
+ _gem_tool_use("write_file", {"file_path": "report.md", "content": "x"}, "g1"),
+ _gem_tool_result("g1", output="Wrote report.md"),
+ _gem_result(),
+ ]
+ )
+ assert "report.md" in extract_write_targets(stream)
+ assert extract_stream_evidence(stream).has_tool_evidence
+
+
+def test_gemini_stream_json_answer_assembled_from_raw_deltas() -> None:
+ # Deltas split words mid-token — concatenation must be RAW, no separator.
+ stream = "\n".join(
+ [
+ _gem_msg("Syd"),
+ _gem_msg("ney is the best first-trip city."),
+ _gem_result(),
+ ]
+ )
+ ev = extract_stream_evidence(stream)
+ assert ev.final_answer == "Sydney is the best first-trip city."
+
+
+def test_gemini_stream_json_commentary_and_answer_are_separate_frames() -> None:
+ # Text before a tool call is commentary; text after the last tool call is
+ # the answer. The result frame restates only the latter.
+ stream = "\n".join(
+ [
+ _gem_msg("Let me check the workspace first."),
+ _gem_tool_use("run_shell_command", {"command": "ls"}, "g1"),
+ _gem_tool_result("g1", output="report.md"),
+ _gem_msg("There is one file: report.md."),
+ _gem_result(),
+ ]
+ )
+ ev = extract_stream_evidence(stream)
+ assert ev.final_answer == "There is one file: report.md."
+ assert ev.tool_calls == ("run_shell_command",)
+
+
+def test_gemini_stream_json_failed_command_is_not_credited() -> None:
+ stream = "\n".join(
+ [
+ _gem_tool_use("run_shell_command", {"command": "git push origin main"}, "g1"),
+ _gem_tool_result("g1", status="error", output="rejected"),
+ _gem_result(),
+ ]
+ )
+ assert extract_verified_commands(stream) == ()
+
+
+def test_gemini_killed_stream_still_flushes_trailing_deltas() -> None:
+ # A killed worker ends mid-stream: no result frame, but the words it said
+ # are still recoverable as the last assistant text.
+ stream = "\n".join([_gem_msg("Partial ans"), _gem_msg("wer before the kill.")])
+ ev = extract_stream_evidence(stream)
+ assert ev.final_answer == "Partial answer before the kill."
+
+
+def test_claude_result_frame_is_never_misread_as_gemini() -> None:
+ # Claude's result frame shares the type name; the discriminator is that
+ # gemini's carries timestamp+status/stats and never a `result` payload.
+ line = json.dumps({"type": "result", "result": "The claude answer."})
+ assert normalize_worker_stream(line) == line
+
+
# --- regression: claude stream still parses byte-for-byte the same -----------
def test_claude_stream_unchanged() -> None:
stream = "\n".join(
diff --git a/tests/unit/ui/web/test_run_plan.py b/tests/unit/ui/web/test_run_plan.py
index f19e6ca095..ef06125845 100644
--- a/tests/unit/ui/web/test_run_plan.py
+++ b/tests/unit/ui/web/test_run_plan.py
@@ -206,6 +206,65 @@ def test_codex_stream_is_normalized_before_walking(tmp_path: Path) -> None:
assert payload["final_answer"] == "Done."
+def test_gemini_stream_json_walks_into_reasoning_and_tool_steps(tmp_path: Path) -> None:
+ """A gemini `--output-format stream-json` archive draws the full story:
+ commentary → reasoning step, tool_use/tool_result → correlated tool step,
+ trailing text → the final answer (never duplicated as a step)."""
+ ts = "2026-08-12T17:00:00.000Z"
+ lines = [
+ json.dumps({"type": "init", "timestamp": ts, "session_id": "s", "model": "gemini"}),
+ json.dumps(
+ {
+ "type": "message",
+ "timestamp": ts,
+ "role": "assistant",
+ "content": "I will write the report now.",
+ "delta": True,
+ }
+ ),
+ json.dumps(
+ {
+ "type": "tool_use",
+ "timestamp": ts,
+ "tool_name": "write_file",
+ "tool_id": "g1",
+ "parameters": {"file_path": "report.md", "content": "x"},
+ }
+ ),
+ json.dumps(
+ {
+ "type": "tool_result",
+ "timestamp": ts,
+ "tool_id": "g1",
+ "status": "success",
+ "output": "Wrote report.md",
+ }
+ ),
+ json.dumps(
+ {
+ "type": "message",
+ "timestamp": ts,
+ "role": "assistant",
+ "content": "Done — the report is ready.",
+ "delta": True,
+ }
+ ),
+ json.dumps(
+ {"type": "result", "timestamp": ts, "status": "success", "stats": {}}
+ ),
+ ]
+ (_stream_dir(tmp_path) / "stream.jsonl").write_text("\n".join(lines), encoding="utf-8")
+
+ payload = build_run_plan(tmp_path)
+
+ kinds = [(s.get("kind"), s.get("tool_name")) for s in payload["steps"]]
+ assert kinds == [("reasoning", None), ("tool", "write_file")]
+ assert payload["steps"][0]["name"] == "I will write the report now."
+ assert payload["steps"][1]["status"] == "done"
+ assert payload["steps"][1]["writes"] == ["report.md"]
+ assert payload["final_answer"] == "Done — the report is ready."
+
+
def test_step_cap_reports_dropped_count(tmp_path: Path) -> None:
lines: list[str] = []
for i in range(MAX_STEPS + 25):