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
fix(missions): make Gemini/Google-CLI/API workers honor the orchestrator timeout_s budget
Ruben Lütke25891c030b02
diff --git a/jarvis/missions/workers/api_agent_worker.py b/jarvis/missions/workers/api_agent_worker.pyindex cf22c6f897..ffaa8410c6 100644--- a/jarvis/missions/workers/api_agent_worker.py+++ b/jarvis/missions/workers/api_agent_worker.py@@ -242,6 +242,7 @@ class ApiAgentWorker:log_dir: Path,model: str = "",max_turns: int = _MAX_TURNS,+ timeout_s: float = _WORKER_TIMEOUT_S,_broker_binding: Any | None = None,**_unused: Any,) -> AsyncIterator[Any]:@@ -249,7 +250,7 @@ class ApiAgentWorker:issued_here = broker_binding is Noneif issued_here:broker_binding = self.capability_inventory.bind_broker(- ttl_s=_WORKER_TIMEOUT_S + 60.0,+ ttl_s=timeout_s + 60.0,mission_id=_unused.get("mission_id"),worker_id=worker_id,)@@ -263,6 +264,7 @@ class ApiAgentWorker:log_dir=log_dir,model=model,max_turns=max_turns,+ timeout_s=timeout_s,broker_binding=broker_binding,**_unused,):@@ -285,6 +287,7 @@ class ApiAgentWorker:log_dir: Path,model: str = "",max_turns: int = _MAX_TURNS,+ timeout_s: float = _WORKER_TIMEOUT_S,broker_binding: Any | None,**_unused: Any,) -> AsyncIterator[Any]:@@ -384,14 +387,14 @@ class ApiAgentWorker:try:for turn in range(max_turns):- if time.perf_counter() - t0 > _WORKER_TIMEOUT_S:+ if time.perf_counter() - t0 > timeout_s:res = ClaudeResult(subtype="error_during_execution",is_error=True,session_id=session_id,timed_out=True,duration_ms=int((time.perf_counter() - t0) * 1000),- result=f"{final_text}\n[timeout after {_WORKER_TIMEOUT_S:.0f}s]".strip(),+ result=f"{final_text}\n[timeout after {timeout_s:.0f}s]".strip(),)_emit_line(res)yield resdiff --git a/jarvis/missions/workers/gemini_worker.py b/jarvis/missions/workers/gemini_worker.pyindex b11ff31ded..c7b5c535c0 100644--- a/jarvis/missions/workers/gemini_worker.py+++ b/jarvis/missions/workers/gemini_worker.py@@ -67,6 +67,10 @@ _QUOTA_BLOCKED_MARKERS: tuple[str, ...] = ()_FALLBACK_MODEL: str = "gemini-3-flash-preview"+# 20 min default hard cap — used only when the orchestrator does not pass its+# own degressive budget (720 s iteration-0 / 360 s correction) via ``timeout_s``.+_WORKER_TIMEOUT_S: float = 1200.0+def _build_isolated_gemini_env(env: dict[str, str],@@ -297,6 +301,7 @@ class GeminiWorker:max_turns: int = 20,resume_session_id: str | None = None,extra_args: tuple[str, ...] = (),+ timeout_s: float = _WORKER_TIMEOUT_S,_broker_binding: Any | None = None,**_unused: Any,) -> AsyncIterator[Any]:@@ -305,7 +310,7 @@ class GeminiWorker:issued_here = broker_binding is Noneif issued_here:broker_binding = self.capability_inventory.bind_broker(- ttl_s=1260.0,+ ttl_s=timeout_s + 60.0,mission_id=_unused.get("mission_id"),worker_id=worker_id,)@@ -323,6 +328,7 @@ class GeminiWorker:max_turns=max_turns,resume_session_id=resume_session_id,extra_args=extra_args,+ timeout_s=timeout_s,broker_binding=broker_binding,**_unused,):@@ -349,6 +355,7 @@ class GeminiWorker:max_turns: int = 20,resume_session_id: str | None = None,extra_args: tuple[str, ...] = (),+ timeout_s: float = _WORKER_TIMEOUT_S,broker_binding: Any | None,**_unused: Any,) -> AsyncIterator[Any]:@@ -424,6 +431,12 @@ class GeminiWorker:permission_mode == "yolo",)+ t0 = time.perf_counter()+ # One deadline for the WHOLE spawn, shared with the quota-fallback+ # re-spawn below — otherwise one iteration could burn 2 × timeout_s+ # and blow the orchestrator's degressive task budget.+ deadline = t0 + timeout_s+async def _spawn_once(spawn_cmd: list[str]) -> tuple[bytes, bytes, int]:"""Spawn the Gemini CLI once and return (stdout, stderr, exit).@@ -453,12 +466,14 @@ class GeminiWorker:proc_local.pid,exc_info=True,)- # 1200 s (20 min) hard cap — raised from 600 s so complex tasks can- # finish (user mandate 2026-06-09). The "timeout" substring in the- # stderr below still flags is_timeout to the orchestrator, which then- # grades the on-disk diff instead of discarding it.+ # The orchestrator's degressive budget (``timeout_s``) is the hard+ # cap; a fallback re-spawn only gets whatever remains of it. The+ # "timeout" substring in the stderr below flags is_timeout to the+ # orchestrator, which then grades the on-disk diff instead of+ # discarding it.+ remaining = max(1.0, deadline - time.perf_counter())try:- out, err = await asyncio.wait_for(proc_local.communicate(), timeout=1200.0)+ out, err = await asyncio.wait_for(proc_local.communicate(), timeout=remaining)except TimeoutError:with suppress(ProcessLookupError):proc_local.kill()@@ -466,11 +481,13 @@ class GeminiWorker:# asyncio transport tears down and the Win32 handle drops.with suppress(Exception):await asyncio.wait_for(proc_local.wait(), timeout=5.0)- out, err = b"", b"GeminiWorker: subprocess wait_for timeout (1200s)"+ out, err = b"", (+ f"GeminiWorker: subprocess wait_for timeout "+ f"({remaining:.0f}s of {timeout_s:.0f}s budget)"+ ).encode()exit_local = proc_local.returncode if proc_local.returncode is not None else -1return out, err, exit_local- t0 = time.perf_counter()stdout_bytes, stderr_bytes, exit_code = await _spawn_once(cmd)# Pro→Flash fallback. Google AI Studio enforces a rolling 6hdiff --git a/jarvis/missions/workers/google_cli_worker.py b/jarvis/missions/workers/google_cli_worker.pyindex 5ca6f337c9..001a16bf71 100644--- a/jarvis/missions/workers/google_cli_worker.py+++ b/jarvis/missions/workers/google_cli_worker.py@@ -70,7 +70,9 @@ class BrokerMcpConfigurationError(RuntimeError):"""Raised when the isolated Google CLI cannot receive the broker config."""-def _build_agy_worker_argv(exe: str, prompt: str, worktree: Path) -> list[str]:+def _build_agy_worker_argv(+ exe: str, prompt: str, worktree: Path, *, timeout_s: float = _WORKER_TIMEOUT_S+) -> list[str]:"""agy worker argv: one non-interactive prompt with auto-approved tools so itcan write files in the worktree.@@ -86,9 +88,10 @@ def _build_agy_worker_argv(exe: str, prompt: str, worktree: Path) -> list[str]:diff; agy itself reported "kein aktives Workspace-Verzeichnis geöffnet" # i18n-allow (quotes agy's own literal CLI message)— English: "no active workspace directory open").- ``--print-timeout`` is widened from agy's 5-minute default to the worker's own- time budget so a long "production-quality" task is not cut short by agy before- our :data:`_WORKER_TIMEOUT_S` cap.+ ``--print-timeout`` is derived from the caller's ``timeout_s`` budget, set+ 30 s BELOW it (floored at 30 s) so agy terminates itself and flushes its+ final output before the external PTY kill fires; the PTY ``timeout_s``+ stays the hard enforcement.Newlines are collapsed to spaces — agy takes the whole prompt as a single``--print`` argument.@@ -101,7 +104,7 @@ def _build_agy_worker_argv(exe: str, prompt: str, worktree: Path) -> list[str]:"--add-dir",str(worktree),"--print-timeout",- f"{int(_WORKER_TIMEOUT_S)}s",+ f"{max(30, int(timeout_s) - 30)}s","--dangerously-skip-permissions",]@@ -175,6 +178,7 @@ class GoogleCliWorker:max_turns: int = 20,resume_session_id: str | None = None,extra_args: tuple[str, ...] = (),+ timeout_s: float = _WORKER_TIMEOUT_S,_broker_binding: Any | None = None,**_unused: Any,) -> AsyncIterator[Any]:@@ -183,7 +187,7 @@ class GoogleCliWorker:issued_here = broker_binding is Noneif issued_here:broker_binding = self.capability_inventory.bind_broker(- ttl_s=_WORKER_TIMEOUT_S + 60.0,+ ttl_s=timeout_s + 60.0,mission_id=_unused.get("mission_id"),worker_id=worker_id,)@@ -201,6 +205,7 @@ class GoogleCliWorker:max_turns=max_turns,resume_session_id=resume_session_id,extra_args=extra_args,+ timeout_s=timeout_s,broker_binding=broker_binding,**_unused,):@@ -227,6 +232,7 @@ class GoogleCliWorker:max_turns: int = 20,resume_session_id: str | None = None,extra_args: tuple[str, ...] = (),+ timeout_s: float = _WORKER_TIMEOUT_S,broker_binding: Any | None,**_unused: Any,) -> AsyncIterator[Any]:@@ -285,6 +291,7 @@ class GoogleCliWorker:model=model,max_turns=max_turns,resume_session_id=resume_session_id,+ timeout_s=timeout_s,_broker_binding=broker_binding,**_unused,):@@ -312,6 +319,7 @@ class GoogleCliWorker:max_turns=max_turns,resume_session_id=resume_session_id,extra_args=extra_args,+ timeout_s=timeout_s,_broker_binding=broker_binding,**_unused,):@@ -323,7 +331,7 @@ class GoogleCliWorker:# agy path: PTY + write-mode + isolated hook/mcp-free home.exe = cli.argv_prefix[0]log_dir.mkdir(parents=True, exist_ok=True) # noqa: ASYNC240 — trivial sync mkdir (mirrors GeminiWorker)- argv = _build_agy_worker_argv(exe, prompt, worktree)+ argv = _build_agy_worker_argv(exe, prompt, worktree, timeout_s=timeout_s)broker_servers = (broker_binding.mcp_server_config() if broker_binding is not None else {})@@ -390,7 +398,7 @@ class GoogleCliWorker:None,lambda: run_cli_over_pty(tuple(argv),- timeout_s=_WORKER_TIMEOUT_S,+ timeout_s=timeout_s,cwd=str(worktree),env=agy_env,on_spawn=_assign,@@ -406,7 +414,7 @@ class GoogleCliWorker:is_error = bool(result.error) or result.timed_out or result.exit_status not in (0, None)text = result.text or (result.error or "")if result.timed_out:- text = f"{text}\n[timeout after {_WORKER_TIMEOUT_S:.0f}s]".strip()+ text = f"{text}\n[timeout after {timeout_s:.0f}s]".strip()logger.info("GoogleCliWorker[%s] agy done: error=%s %dms text=%d chars",worker_id,diff --git a/tests/missions/workers/test_worker_timeout_parity.py b/tests/missions/workers/test_worker_timeout_parity.pynew file mode 100644index 0000000000..c8d52533d4--- /dev/null+++ b/tests/missions/workers/test_worker_timeout_parity.py@@ -0,0 +1,286 @@+"""Every mission worker honors the orchestrator's ``timeout_s`` budget.++The Kontrollierer allocates a degressive per-iteration time budget (720 s for+iteration 0, 360 s for corrections) and passes it to ``worker.spawn`` as+``timeout_s``. A worker that silently swallows the kwarg into ``**_unused``+runs on its own 1200 s module constant instead, overshooting the 1380 s task+budget — a correction iteration then burns 20 minutes before the orchestrator+can grade the diff (live case: antigravity corrections ran 1200 s instead of+360 s while ``[brain.worker]`` pointed at the Google CLI worker).++These tests pin the contract for ALL worker backends: the parameter must be+declared (never ``**_unused``-swallowed) and must reach the actual enforcement+point (``asyncio.wait_for`` deadline, PTY timeout, agent-loop deadline).+"""++from __future__ import annotations++import asyncio+import inspect+import time+from typing import Any++import pytest++import jarvis.core.config as config_module+import jarvis.missions.workers.api_agent_worker as api_module+import jarvis.missions.workers.gemini_worker as gemini_module+import jarvis.missions.workers.google_cli_worker as google_module+from jarvis.google_cli.pty_runner import PtyRunResult+from jarvis.google_cli.resolver import GoogleCli+from jarvis.missions.workers.api_agent_worker import ApiAgentWorker+from jarvis.missions.workers.claude_direct_worker import ClaudeDirectWorker+from jarvis.missions.workers.codex_direct_worker import CodexDirectWorker+from jarvis.missions.workers.gemini_worker import GeminiWorker+from jarvis.missions.workers.google_cli_worker import (+ GoogleCliWorker,+ _build_agy_worker_argv,+)+++class _StubBinding:+ tool_specs: tuple[dict[str, object], ...] = ()++ def close(self) -> None:+ return None++ def mcp_server_config(self) -> dict[str, dict[str, object]]:+ return {}++ def apply_environment(self, env: dict[str, str]) -> dict[str, str]:+ return dict(env)+++class _RecordingInventory:+ """Records the broker TTL a worker requests for its self-issued grant."""++ def __init__(self) -> None:+ self.ttl_s: float | None = None++ def bind_broker(self, *, ttl_s: float, **_kwargs: Any) -> _StubBinding:+ self.ttl_s = ttl_s+ return _StubBinding()++ def report_for(self, backend: str, *, binding: Any = None) -> dict[str, object]:+ return {"backend": backend}+++class _Job:+ def assign(self, _pid: int) -> None:+ return None+++_WORKER_CLASSES = (+ ApiAgentWorker,+ ClaudeDirectWorker,+ CodexDirectWorker,+ GeminiWorker,+ GoogleCliWorker,+)++[email protected]("worker_cls", _WORKER_CLASSES, ids=lambda c: c.__name__)+def test_spawn_declares_timeout_s(worker_cls: type) -> None:+ """``timeout_s`` must be a declared parameter on every backend — a+ ``**_unused`` catch-all silently discards the orchestrator's budget."""+ for method_name in ("spawn", "_spawn_bound"):+ params = inspect.signature(getattr(worker_cls, method_name)).parameters+ assert "timeout_s" in params, (+ f"{worker_cls.__name__}.{method_name} swallows timeout_s into **kwargs"+ )+++async def test_gemini_worker_enforces_timeout_s(monkeypatch, tmp_path) -> None:+ """A hanging Gemini CLI is killed after ``timeout_s``, not after the+ 1200 s module constant, and the synthetic stderr keeps the load-bearing+ "timeout" substring the orchestrator classifies ``is_timeout`` from."""++ class _HangingProcess:+ pid = 4242++ def __init__(self) -> None:+ self.returncode: int | None = None++ async def communicate(self) -> tuple[bytes, bytes]:+ await asyncio.sleep(30.0)+ return b"", b""++ def kill(self) -> None:+ self.returncode = -9++ async def wait(self) -> int:+ return self.returncode if self.returncode is not None else -9++ async def _hanging(*_args: Any, **_kwargs: Any) -> _HangingProcess:+ return _HangingProcess()++ monkeypatch.setattr(gemini_module, "create_worker_subprocess", _hanging)+ inventory = _RecordingInventory()+ worker = GeminiWorker(capability_inventory=inventory) # type: ignore[arg-type]+ t0 = time.perf_counter()+ events = [+ e+ async for e in worker.spawn(+ "build it",+ worktree=tmp_path,+ env={},+ job=_Job(),+ worker_id="w",+ log_dir=tmp_path / "logs",+ timeout_s=0.2,+ )+ ]+ elapsed = time.perf_counter() - t0+ assert elapsed < 10.0, "worker ignored timeout_s and ran on its module constant"+ result = events[-1]+ assert result.is_error is True+ assert "timeout" in result.result+ assert inventory.ttl_s == pytest.approx(0.2 + 60.0)+++async def test_gemini_quota_fallback_shares_one_deadline(monkeypatch, tmp_path) -> None:+ """The Pro→Flash quota retry runs on the REMAINING budget — one iteration+ must never burn 2 × timeout_s across the two attempts."""+ spawn_times: list[float] = []++ class _QuotaProcess:+ pid = 1++ def __init__(self) -> None:+ self.returncode: int | None = None++ async def communicate(self) -> tuple[bytes, bytes]:+ self.returncode = 1+ return b"", b"code: 429 QUOTA_EXHAUSTED"++ def kill(self) -> None:+ self.returncode = -9++ async def wait(self) -> int:+ return -9++ class _HangingProcess:+ pid = 2++ def __init__(self) -> None:+ self.returncode: int | None = None++ async def communicate(self) -> tuple[bytes, bytes]:+ await asyncio.sleep(30.0)+ return b"", b""++ def kill(self) -> None:+ self.returncode = -9++ async def wait(self) -> int:+ return -9++ procs: list[Any] = [_QuotaProcess(), _HangingProcess()]++ async def _next_proc(*_args: Any, **_kwargs: Any) -> Any:+ spawn_times.append(time.perf_counter())+ return procs.pop(0)++ monkeypatch.setattr(gemini_module, "create_worker_subprocess", _next_proc)+ worker = GeminiWorker(capability_inventory=_RecordingInventory()) # type: ignore[arg-type]+ t0 = time.perf_counter()+ events = [+ e+ async for e in worker.spawn(+ "build it",+ worktree=tmp_path,+ env={},+ job=_Job(),+ worker_id="w",+ log_dir=tmp_path / "logs",+ model="gemini-3-pro-preview",+ timeout_s=1.0,+ )+ ]+ elapsed = time.perf_counter() - t0+ assert len(spawn_times) == 2, "quota fallback was not attempted"+ assert elapsed < 10.0, "fallback attempt got a fresh budget instead of the remainder"+ assert events[-1].is_error is True+++async def test_google_cli_worker_passes_timeout_to_pty_and_agy(monkeypatch, tmp_path) -> None:+ """agy path: the PTY hard cap IS the orchestrator budget, and agy's own+ ``--print-timeout`` is derived slightly below it so agy flushes its final+ output before the external kill."""+ monkeypatch.setattr(+ google_module, "resolve_google_cli", lambda: GoogleCli(kind="agy", argv_prefix=["agy.exe"])+ )+ monkeypatch.setattr(google_module, "ensure_isolated_home", lambda **_k: str(tmp_path / "iso"))+ monkeypatch.setattr(google_module, "_oauth_login_present", lambda *_a: True)+ captured: dict[str, Any] = {}++ def _fake_run(argv, *, timeout_s, cwd=None, env=None, on_spawn=None, **_kw):+ captured["argv"] = list(argv)+ captured["timeout_s"] = timeout_s+ return PtyRunResult(text="ok", raw="raw", exit_status=0, timed_out=False, error=None)++ monkeypatch.setattr(google_module, "run_cli_over_pty", _fake_run)+ inventory = _RecordingInventory()+ worker = GoogleCliWorker(capability_inventory=inventory) # type: ignore[arg-type]+ _ = [+ e+ async for e in worker.spawn(+ "build it",+ worktree=tmp_path,+ env={"PATH": "/p"},+ job=_Job(),+ worker_id="w",+ log_dir=tmp_path / "logs",+ timeout_s=360.0,+ )+ ]+ assert captured["timeout_s"] == 360.0+ argv = captured["argv"]+ assert argv[argv.index("--print-timeout") + 1] == "330s"+ assert inventory.ttl_s == pytest.approx(360.0 + 60.0)+++def test_agy_print_timeout_never_drops_below_floor(tmp_path) -> None:+ """Tiny budgets clamp agy's self-timeout to a workable 30 s floor instead+ of a nonsensical zero/negative value; the PTY cap stays the enforcement."""+ argv = _build_agy_worker_argv("agy.exe", "p", tmp_path, timeout_s=45.0)+ assert argv[argv.index("--print-timeout") + 1] == "30s"+++async def test_api_agent_worker_enforces_timeout_s(monkeypatch, tmp_path) -> None:+ """The in-process agent loop checks the PASSED budget, not the module+ constant — an exhausted budget yields a timed-out result before the+ next brain turn starts."""++ class _NeverCalledBrain:+ def can_call_tools(self) -> bool:+ return True++ async def complete(self, _req: Any):+ raise AssertionError("brain must not run once the budget is exhausted")+ yield # pragma: no cover — makes this an async generator++ monkeypatch.setattr(api_module, "_build_brain", lambda *_a, **_k: _NeverCalledBrain())+ monkeypatch.setattr(config_module, "get_jarvis_agent_secret", lambda *_a, **_k: "key")+ inventory = _RecordingInventory()+ worker = ApiAgentWorker("openai", capability_inventory=inventory) # type: ignore[arg-type]+ events = [+ e+ async for e in worker.spawn(+ "build it",+ worktree=tmp_path,+ env={},+ job=_Job(),+ worker_id="w",+ log_dir=tmp_path / "logs",+ timeout_s=0.0,+ )+ ]+ result = events[-1]+ assert result.timed_out is True+ assert "timeout" in result.result+ assert inventory.ttl_s == pytest.approx(60.0)