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(tasks): finish a routine through task tools when the owner seat fails
rubenluetke10-beep4128fee4ae1c
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 7b7943269b..e97f1dde60 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -13346,6 +13346,7 @@ class BrainManager:allowed_tools: tuple[str, ...] = (),model_tier: str = "auto",trace_id: UUID | None = None,+ prefer_api: bool = False,) -> str:"""Run one isolated agentic turn for a scheduled task.@@ -13365,8 +13366,13 @@ class BrainManager:other error propagates so the runner records it in ``last_error``.The persistent active provider is never switched.+ ``prefer_api`` is accepted so a routine whose owner seat already+ failed (a CLI without Jarvis tools) can retry here without a+ TypeError. This path is already the API provider chain.+Returns the final assistant text."""+ del prefer_apiintent = "deep" if model_tier == "deep" else "fast"tools = self._select_task_tools(allowed_tools)# The per-turn context (date/time, awareness, wiki) rides on the userdiff --git a/jarvis/tasks/runner.py b/jarvis/tasks/runner.pyindex 32c4c27d86..3d5992e689 100644--- a/jarvis/tasks/runner.py+++ b/jarvis/tasks/runner.py@@ -94,6 +94,7 @@ class _AgentBrainLike(Protocol):allowed_tools: tuple[str, ...],model_tier: str,trace_id: UUID | None = None,+ prefer_api: bool = False,) -> Any: ...@@ -231,7 +232,20 @@ class TaskRunner:))log.exception("Task %s failed after %dms", task_id, duration_ms)- await self._announce(getattr(spec, "announce_on_failure", None), ctx)+ tags = tuple(str(tag) for tag in spec.tags)+ if self._result_sink is not None and tags:+ try:+ await self._result_sink(tags, error_msg, "failed")+ except Exception: # noqa: BLE001 — the run already failed; delivery is best effort+ log.warning(+ "task %s: failure sink failed for tags %s", task_id, tags, exc_info=True+ )+ fail_ctx = {**ctx, "error": error_msg}+ template = getattr(spec, "announce_on_failure", None)+ if template:+ await self._announce(template, fail_ctx)+ elif "society" in tags:+ await self._announce(error_msg, fail_ctx)returnduration_ms = int((time.perf_counter() - start) * 1000)@@ -555,9 +569,42 @@ class TaskRunner:"only perform the task above):\n" + redact_secrets(str(ctx["hook_payload"])))owned_result = None+ owned_failed: BaseException | None = Noneif self._owned_agent_runner is not None and tags:- owned_result = await self._owned_agent_runner(task_id, tags, prompt, cancel_token)+ try:+ owned_result = await self._owned_agent_runner(task_id, tags, prompt, cancel_token)+ except (RoutineDeferred, _Cancelled):+ raise+ except asyncio.CancelledError:+ raise _Cancelled(+ cancel_token.reason if cancel_token is not None else "cancelled"+ ) from None+ except Exception as exc:+ if _owner_blocks_fallback(exc):+ raise+ owned_failed = exc+ log.warning(+ "task %s: owner seat failed (%s); continuing via task tools",+ task_id,+ readable_error(exc),+ )+ seq = await self._store.append_step(+ task_id,+ "log",+ {+ "event": "owner_seat_failed",+ "message": readable_error(exc),+ "fallback": "task_tools",+ },+ )+ await self._bus.publish(+ TaskStepRecorded(+ task_id=task_id, seq=seq, kind="log", source_layer="tasks.runner"+ )+ )if self._brain is None and owned_result is None:+ if owned_failed is not None:+ raise RuntimeError(_seat_then_no_path(owned_failed)) from owned_failedraise RuntimeError("Agent brain not configured — agent action cannot run")allowed_tools = tuple(g.plugin_id for g in action.plugin_grants)# Plugins the user granted write/full are pre-authorized for this@@ -592,12 +639,21 @@ class TaskRunner:result = owned_resultelse:assert self._brain is not None- result = await self._brain.run_task(- prompt=prompt,- allowed_tools=allowed_tools,- model_tier=action.model_tier,- trace_id=trace_id,- )+ try:+ result = await self._brain.run_task(+ prompt=prompt,+ allowed_tools=allowed_tools,+ model_tier=action.model_tier,+ trace_id=trace_id,+ prefer_api=owned_failed is not None,+ )+ except Exception as exc:+ if owned_failed is not None:+ raise RuntimeError(+ f"{readable_error(exc)} "+ f"(agent seat had already failed: {readable_error(owned_failed)})"+ ) from exc+ raisefinally:if self._approver is not None:self._approver.disarm(trace_id)@@ -702,6 +758,30 @@ def _targets_computer_use(harness_name: str) -> bool:return harness_name == HARNESS_NAME+def _owner_blocks_fallback(exc: BaseException) -> bool:+ """True when the owner's state, not the seat, is why the routine cannot run.++ A paused/halted/missing owner is a user-visible condition: retrying the+ same work through another brain would impersonate a teammate that was+ told to stop. Seat failures (missing tools, a cancelled CLI turn) do+ not block the fallback — the routine still has to reach its goal.+ """+ text = str(exc).lower()+ return any(+ needle in text+ for needle in (+ "the society is halted",+ "the routine owner is unavailable",+ "the routine owner is paused",+ "canonical chat service is unavailable",+ )+ )+++def _seat_then_no_path(owned_failed: BaseException) -> str:+ return f"{readable_error(owned_failed)}. No other path was available to finish this routine."++_ERROR_MESSAGE_RE = re.compile(r"""['"]message['"]\s*:\s*['"]([^'"]{1,300})['"]""")_ERROR_CODE_RE = re.compile(r"""\b(?:Error code|status(?: code)?)[:=]?\s*(\d{3})\b|['"]code['"]\s*:\s*(\d{3})\b""",diff --git a/tests/unit/tasks/test_runner_agent_result.py b/tests/unit/tasks/test_runner_agent_result.pyindex 3427a2e045..a87ff149e0 100644--- a/tests/unit/tasks/test_runner_agent_result.py+++ b/tests/unit/tasks/test_runner_agent_result.py@@ -14,16 +14,20 @@ from jarvis.control.cancel import CancelTokenfrom jarvis.core.bus import EventBusfrom jarvis.core.events import AnnouncementRequested, TaskCompletedfrom jarvis.tasks.runner import TaskRunner-from jarvis.tasks.schema import AgentAction, TaskSpec, TriggerAfterDelay+from jarvis.tasks.schema import AgentAction, PluginGrant, TaskSpec, TriggerAfterDelayfrom jarvis.tasks.store import TaskStoreclass FakeAgentBrain:def __init__(self) -> None:self.prompts: list[str] = []+ self.kwargs: list[dict[str, Any]] = []- async def run_task(self, *, prompt: str, allowed_tools: Any, model_tier: Any, trace_id: Any):+ async def run_task(+ self, *, prompt: str, allowed_tools: Any, model_tier: Any, trace_id: Any, **kwargs: Any+ ):self.prompts.append(prompt)+ self.kwargs.append({"allowed_tools": allowed_tools, "model_tier": model_tier, **kwargs})return "Inbox sorted: 3 replies drafted."@@ -205,3 +209,98 @@ async def test_rub95_explicit_announce_on_success_still_speaks_once(assert len(announcements) == 1assert announcements[0].text == "Inbox sweep done."assert announcements[0].kind == "subagent"+++async def test_a_failed_owner_seat_finishes_through_task_tools(store: TaskStore) -> None:+ """A cancelled / tool-less owner seat is not the end of the routine."""++ async def owned_runner(task_id: str, tags: tuple[str, ...], prompt: str, cancel: Any):+ raise RuntimeError("cancelled")++ delivered: list[tuple[tuple[str, ...], str, str]] = []++ async def sink(tags: tuple[str, ...], text: str, status: str) -> None:+ delivered.append((tags, text, status))++ brain = FakeAgentBrain()+ bus = EventBus()+ announcements = _collect(bus, AnnouncementRequested)+ runner = TaskRunner(+ store, bus, agent_brain=brain, owned_agent_runner=owned_runner, result_sink=sink+ )+ spec = TaskSpec(+ title="[agent:Mailbox] Inbox sweep",+ trigger=TriggerAfterDelay(delay_seconds=0.01),+ action=AgentAction(+ prompt="Sort the inbox.",+ plugin_grants=(PluginGrant(plugin_id="gmail", scope="read"),),+ ),+ tags=("society", "agent:mailbox"),+ )+ task_id = await store.insert(spec)+ await asyncio.wait_for(runner.run(task_id, CancelToken()), timeout=2.0)+ row = await store.get(task_id)+ assert row is not None and row["state"] == "completed"+ assert brain.prompts and "Sort the inbox." in brain.prompts[0]+ assert brain.kwargs[0].get("prefer_api") is True+ assert brain.kwargs[0]["allowed_tools"] == ("gmail",)+ assert delivered == [(("society", "agent:mailbox"), "Inbox sorted: 3 replies drafted.", "done")]+ assert announcements == []+ assert any(+ s["kind"] == "log" and s["payload"].get("event") == "owner_seat_failed"+ for s in row["steps"]+ )+++async def test_a_paused_owner_is_explained_not_impersonated(store: TaskStore) -> None:+ """The user paused the teammate — another brain must not finish the job."""++ async def owned_runner(task_id: str, tags: tuple[str, ...], prompt: str, cancel: Any):+ raise RuntimeError("The routine owner is unavailable or paused")++ brain = FakeAgentBrain()+ delivered: list[tuple[tuple[str, ...], str, str]] = []++ async def sink(tags: tuple[str, ...], text: str, status: str) -> None:+ delivered.append((tags, text, status))++ bus = EventBus()+ announcements = _collect(bus, AnnouncementRequested)+ runner = TaskRunner(+ store, bus, agent_brain=brain, owned_agent_runner=owned_runner, result_sink=sink+ )+ spec = TaskSpec(+ title="[agent:Mailbox] Inbox sweep",+ trigger=TriggerAfterDelay(delay_seconds=0.01),+ action=AgentAction(prompt="Sort the inbox."),+ tags=("society", "agent:mailbox"),+ )+ task_id = await store.insert(spec)+ await asyncio.wait_for(runner.run(task_id, CancelToken()), timeout=2.0)+ row = await store.get(task_id)+ assert row is not None and row["state"] == "failed"+ assert brain.prompts == []+ assert row["last_error"] is not None and "paused" in row["last_error"]+ assert delivered and delivered[0][2] == "failed"+ assert announcements and "paused" in announcements[0].text+++async def test_no_brain_after_seat_failure_says_there_was_no_other_path(+ store: TaskStore,+) -> None:+ async def owned_runner(task_id: str, tags: tuple[str, ...], prompt: str, cancel: Any):+ raise RuntimeError("cancelled")++ runner = TaskRunner(store, EventBus(), owned_agent_runner=owned_runner)+ spec = TaskSpec(+ title="[agent:Mailbox] Inbox sweep",+ trigger=TriggerAfterDelay(delay_seconds=0.01),+ action=AgentAction(prompt="Sort the inbox."),+ tags=("society", "agent:mailbox"),+ )+ task_id = await store.insert(spec)+ await asyncio.wait_for(runner.run(task_id, CancelToken()), timeout=2.0)+ row = await store.get(task_id)+ assert row is not None and row["state"] == "failed"+ assert row["last_error"] is not None+ assert "No other path was available" in row["last_error"]