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
chore: auto-save WIP via Claude stop-hook safety net (2026-07-14 09:55)
Ruben Lütke4c6e11443c4f
diff --git a/jarvis/brain/dispatcher.py b/jarvis/brain/dispatcher.pyindex 9be8cd2112..a2cc8331a5 100644--- a/jarvis/brain/dispatcher.py+++ b/jarvis/brain/dispatcher.py@@ -36,6 +36,7 @@ class BrainDispatcher:max_turns: int = 15,max_tokens_total: int = 50_000,max_tokens: int = 8192,+ deadline_s: float | None = None,) -> None:self._brain = brainself._tools = tools or {}@@ -48,6 +49,9 @@ class BrainDispatcher:# tool-use turns; this is the cap on a single provider response so a# long reply is never read aloud truncated mid-sentence.self._max_tokens = max_tokens+ # Optional wall-clock bound for the tool-use loop (voice turns).+ # See ToolUseLoop.deadline_s; ``None`` = unbounded (default).+ self._deadline_s = deadline_s@propertydef brain(self) -> Brain:@@ -63,6 +67,7 @@ class BrainDispatcher:max_turns=self._max_turns,max_tokens_total=self._max_tokens_total,max_tokens=self._max_tokens,+ deadline_s=self._deadline_s,)def set_tools(self, tools: dict[str, Tool]) -> None:@@ -128,6 +133,7 @@ class BrainDispatcher:max_tokens_total=self._max_tokens_total,),max_tokens=self._max_tokens,+ deadline_s=self._deadline_s,)return await loop.run(messages,diff --git a/jarvis/brain/tool_use_loop.py b/jarvis/brain/tool_use_loop.pyindex dd20fad07c..133a29b086 100644--- a/jarvis/brain/tool_use_loop.py+++ b/jarvis/brain/tool_use_loop.py@@ -15,6 +15,7 @@ from __future__ import annotationsimport jsonimport loggingimport re+import timefrom collections.abc import Awaitable, Callablefrom typing import Anyfrom uuid import UUID, uuid4@@ -35,6 +36,15 @@ from .streaming import StreamingAggregate, aggregate, aggregate_with_consumer# (``safe_preview``) is a separate path and never touched what the model saw._MAX_TOOL_RESULT_CHARS = 8000+# Directive appended for the deadline-forced final round (see ``deadline_s``).+# English on purpose: it is model-facing prompt text, never spoken to the user.+_DEADLINE_FINAL_DIRECTIVE = (+ "[time budget exhausted] Answer the user NOW in one or two spoken "+ "sentences using ONLY the tool evidence gathered above. If the evidence "+ "is incomplete, say honestly what you could and could not verify. Do "+ "not call any more tools."+)+def _cap_tool_result_json(serialized: str) -> str:"""Truncate an over-long serialized tool result, leaving an honest marker so@@ -359,6 +369,7 @@ class ToolUseLoop:system_prompt: str | None = None,budget: IterationBudget | None = None,max_tokens: int = 8192,+ deadline_s: float | None = None,) -> None:self._brain = brainself._tools = tools@@ -378,6 +389,14 @@ class ToolUseLoop:# Per-response output ceiling forwarded onto every BrainRequest this# loop issues. Safety ceiling, not a target (see BrainConfig.max_tokens).self._max_tokens = max_tokens+ # Wall-clock bound for the WHOLE loop (voice turns; live incident+ # 2026-07-14: 14 rounds / 66 s). The iteration budget counts rounds,+ # not seconds — one slow provider round can eat a minute on its own.+ # When exceeded after a tool round, the loop runs exactly ONE final+ # round WITHOUT tools plus an answer-now directive, so the user+ # always hears a grounded answer instead of more tool churn.+ # ``None`` (default) = unbounded, previous behavior.+ self._deadline_s = deadline_sdef _resolve_tool(self, requested: str) -> tuple[Tool | None, str]:"""Look up a model-requested tool name, tolerating separator/case drift.@@ -486,6 +505,8 @@ class ToolUseLoop:tools_payload = self._tool_schemas()final_agg = StreamingAggregate()ack_attempted = False+ loop_started = time.monotonic()+ deadline_forced = Falsedef _progress() -> None:# Stall-timeout heartbeat (see ``on_progress`` in the docstring).@@ -538,6 +559,17 @@ class ToolUseLoop:if not agg.tool_calls:break+ # The deadline-forced round is the LAST round, period. With+ # ``tools_payload = []`` a well-behaved provider cannot emit tool+ # calls anymore; if one hallucinates a call anyway, stop here+ # rather than looping on a dead deadline.+ if deadline_forced:+ log.warning(+ "tool_use_loop: provider emitted a tool call in the "+ "deadline-forced tool-less round — ending the turn"+ )+ break+# Budget exhausted → abortif self._budget.exceeded():log.warning("IterationBudget exhausted: %s", self._budget.snapshot())@@ -927,6 +959,25 @@ class ToolUseLoop:final_agg.finish_reason = "budget_exceeded"break+ # Wall-clock deadline check after execution: force ONE final+ # tool-less answer round from the evidence gathered so far.+ if (+ self._deadline_s is not None+ and time.monotonic() - loop_started >= self._deadline_s+ ):+ deadline_forced = True+ elapsed = time.monotonic() - loop_started+ log.warning(+ "tool_use_loop: %.1fs deadline reached after %.1fs / "+ "%d round(s) — forcing a final tool-less answer round",+ self._deadline_s, elapsed, self._budget.turns_used,+ )+ tools_payload = []+ current_messages.append(BrainMessage(+ role="user",+ content=_DEADLINE_FINAL_DIRECTIVE,+ ))+# Fire-and-forget: if any tool has suppress_response=True,# skip the second brain iteration and return immediately.if suppress_output is not None:diff --git a/tests/unit/brain/test_tool_use_loop_deadline.py b/tests/unit/brain/test_tool_use_loop_deadline.pynew file mode 100644index 0000000000..01fb73020a--- /dev/null+++ b/tests/unit/brain/test_tool_use_loop_deadline.py@@ -0,0 +1,139 @@+"""Wall-clock deadline for the tool-use loop (delegated realtime turns).++Forensic origin (voice session 2026-07-14 09:29): a delegated "what is+in my wiki" turn ran ~14 sequential LLM rounds over 66 s — the iteration+budget (15 turns) was the only bound, and it carries no notion of time.+A voice user is gone long before round 14.++Contract under test:+ 1. When the deadline is exceeded after a tool round, the loop runs+ exactly ONE final round WITHOUT tools, carrying a directive to+ answer from the gathered evidence — the user always hears a+ grounded answer, never silence and never more tool churn.+ 2. Without a deadline (default) behavior is unchanged.+ 3. A generous deadline never fires on a fast turn.+"""+from __future__ import annotations++from collections.abc import AsyncIterator+from typing import Any++import pytest++from jarvis.brain.iteration_budget import IterationBudget+from jarvis.brain.tool_use_loop import ToolUseLoop+from jarvis.core.protocols import BrainDelta, BrainRequest, ToolResult+++class _ListTool:+ name = "wiki-list"+ schema: dict[str, Any] = {}+++class _ExecOK:+ def __init__(self) -> None:+ self.calls: list[dict[str, Any]] = []++ async def execute(self, tool: Any, args: dict[str, Any], **_: Any) -> ToolResult:+ self.calls.append(args)+ return ToolResult(success=True, output="- log.md\n- entities/ruben.md")+++class _GreedyBrain:+ """Calls a tool on EVERY round that offers tools; answers otherwise.++ Models the runaway agentic loop: it never stops on its own while the+ request still advertises tools.+ """++ def __init__(self) -> None:+ self.requests: list[BrainRequest] = []++ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:+ self.requests.append(req)+ if req.tools:+ yield BrainDelta(+ tool_call={"id": f"c{len(self.requests)}", "name": "wiki-list", "input": {}}+ )+ yield BrainDelta(finish_reason="tool_use")+ return+ yield BrainDelta(content="Your wiki holds log.md and entities/ruben.md.")+ yield BrainDelta(finish_reason="stop")+++class _OneShotBrain:+ """One tool round, then a normal answer — the healthy fast turn."""++ def __init__(self) -> None:+ self.requests: list[BrainRequest] = []++ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:+ self.requests.append(req)+ if len(self.requests) == 1:+ yield BrainDelta(tool_call={"id": "c1", "name": "wiki-list", "input": {}})+ yield BrainDelta(finish_reason="tool_use")+ return+ yield BrainDelta(content="Done quickly.")+ yield BrainDelta(finish_reason="stop")+++async def test_deadline_forces_one_final_toolless_round() -> None:+ brain = _GreedyBrain()+ executor = _ExecOK()+ loop = ToolUseLoop(+ brain,+ {"wiki-list": _ListTool()},+ executor, # type: ignore[arg-type]+ deadline_s=0.0, # already expired after the first tool round+ )++ result = await loop.run([], user_utterance="what is in my wiki")++ # Round 1 (tool call) + exactly ONE forced final round — no third round.+ assert len(brain.requests) == 2+ assert executor.calls, "the first tool round must still execute"+ # The forced round must offer NO tools …+ assert not brain.requests[1].tools+ # … and carry the answer-now directive.+ joined = " ".join(+ str(getattr(m, "content", "")) for m in brain.requests[1].messages+ )+ assert "answer" in joined.lower()+ # The user hears a real, grounded answer.+ assert "wiki" in result.text.lower()+++async def test_no_deadline_keeps_budget_behavior() -> None:+ brain = _GreedyBrain()+ loop = ToolUseLoop(+ brain,+ {"wiki-list": _ListTool()},+ _ExecOK(), # type: ignore[arg-type]+ budget=IterationBudget(max_turns=3),+ )++ result = await loop.run([], user_utterance="what is in my wiki")++ assert result.finish_reason == "budget_exceeded"+ # Every round still offered tools — no forced tool-less round happened.+ assert all(req.tools for req in brain.requests)+++async def test_generous_deadline_never_fires_on_fast_turn() -> None:+ brain = _OneShotBrain()+ loop = ToolUseLoop(+ brain,+ {"wiki-list": _ListTool()},+ _ExecOK(), # type: ignore[arg-type]+ deadline_s=300.0,+ )++ result = await loop.run([], user_utterance="what is in my wiki")++ assert result.text == "Done quickly."+ assert len(brain.requests) == 2+ # The second (answer) round kept its tools — no forced round.+ assert brain.requests[1].tools