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(society): a routine's result arrives in the agent's own chat

rubenluetke10-beepdb40ba915935
diff --git a/jarvis/society/routines.py b/jarvis/society/routines.py
index 945ccb1b77..fd21d9cd52 100644
--- a/jarvis/society/routines.py
+++ b/jarvis/society/routines.py
@@ -13,6 +13,7 @@ runner already understands.
from __future__ import annotations
import json
+from collections.abc import Sequence
from typing import Any, Final
from jarvis.tasks.schema import (
@@ -102,6 +103,16 @@ def build_task_spec(
)
+def agent_id_from_tags(tags: Sequence[str]) -> str | None:
+ """The owning agent behind a task's tags (``agent:<id>``), else ``None``."""
+ prefix = agent_tag("")
+ for tag in tags:
+ text = str(tag)
+ if text.startswith(prefix) and len(text) > len(prefix):
+ return text[len(prefix) :]
+ return None
+
+
def _tags_of(row: dict[str, Any]) -> tuple[str, ...]:
raw = row.get("spec_json")
if not raw:
diff --git a/jarvis/tasks/runner.py b/jarvis/tasks/runner.py
index a435f32875..a65ef1390b 100644
--- a/jarvis/tasks/runner.py
+++ b/jarvis/tasks/runner.py
@@ -33,7 +33,7 @@ import contextlib
import logging
import re
import time
-from collections.abc import Iterable
+from collections.abc import Awaitable, Callable, Iterable
from typing import TYPE_CHECKING, Any, Protocol
from uuid import UUID, uuid4
@@ -122,6 +122,7 @@ class TaskRunner:
tool_registry: _ToolRegistryLike | Any = None,
agent_brain: _AgentBrainLike | None = None,
auto_approver: _AutoApproverLike | None = None,
+ result_sink: Callable[[tuple[str, ...], str, str], Awaitable[None]] | None = None,
) -> None:
self._store = store
self._bus = bus
@@ -131,6 +132,10 @@ class TaskRunner:
self._tools = tool_registry
self._brain = agent_brain
self._approver = auto_approver
+ #: ``(tags, text, status)`` after an agent action — where a tagged
+ #: task's result also goes (a society agent's routine reports into its
+ #: own chat). Optional: tasks never import the society.
+ self._result_sink = result_sink
# ------------------------------------------------------------------
@@ -260,7 +265,8 @@ class TaskRunner:
elif action.kind == "tool_call":
await self._run_tool_call(task_id, action, cancel_token)
elif action.kind == "agent":
- await self._run_agent(task_id, action, cancel_token, ctx)
+ tags = tuple(str(t) for t in (getattr(spec, "tags", None) or ()))
+ await self._run_agent(task_id, action, cancel_token, ctx, tags=tags)
else: # pragma: no cover — the schema does not allow anything else
raise RuntimeError(f"Unknown action kind: {action.kind}")
@@ -470,10 +476,14 @@ class TaskRunner:
action: Any,
cancel_token: CancelToken | None,
ctx: dict[str, Any],
+ *,
+ tags: tuple[str, ...] = (),
) -> None:
"""Run an agentic brain turn: the prompt is executed with the toggled
plugins as the tool allowlist. Each grant's scope is forwarded so the
- brain can pre-authorize unattended ask-tier actions.
+ brain can pre-authorize unattended ask-tier actions. ``tags`` are the
+ task's tags, handed to the result sink so a tagged owner (a society
+ agent) gets the result in its own chat.
"""
if self._brain is None:
raise RuntimeError(
@@ -528,6 +538,13 @@ class TaskRunner:
TaskStepRecorded(task_id=task_id, seq=seq, kind="log",
source_layer="tasks.runner")
)
+ if self._result_sink is not None and tags:
+ try:
+ await self._result_sink(tags, text, "done")
+ except Exception: # noqa: BLE001 — the task succeeded; a failed delivery is logged
+ log.warning(
+ "task %s: result sink failed for tags %s", task_id, tags, exc_info=True
+ )
# Delivery: speak the result at the next VAD turn-boundary. The TTS
# pipeline scrubs it; on a muted/headless runtime this is a logged
# no-op (cloud-first). The result also stays visible as the step above
diff --git a/tests/unit/society/test_routines.py b/tests/unit/society/test_routines.py
index 139cc6cae6..5278bd0ab5 100644
--- a/tests/unit/society/test_routines.py
+++ b/tests/unit/society/test_routines.py
@@ -134,3 +134,13 @@ async def test_scheduler_is_preferred(agent):
spec = build_task_spec(agent, title="brief", prompt="p", schedule={"kind": "every"})
task_id = await create_routine(store, scheduler, spec)
assert scheduler.scheduled == [task_id]
+
+
+def test_the_agent_id_is_read_off_the_tags():
+ from jarvis.society.routines import agent_id_from_tags
+
+ assert agent_id_from_tags(("society", "agent:mailbox")) == "mailbox"
+ assert agent_id_from_tags(["agent:scout"]) == "scout"
+ assert agent_id_from_tags(("society", "agent:")) is None
+ assert agent_id_from_tags(()) is None
+ assert agent_id_from_tags(("automation",)) is None
diff --git a/tests/unit/tasks/test_runner_agent_result.py b/tests/unit/tasks/test_runner_agent_result.py
new file mode 100644
index 0000000000..0c797f3b19
--- /dev/null
+++ b/tests/unit/tasks/test_runner_agent_result.py
@@ -0,0 +1,100 @@
+"""An agent action's result reaches the runner's result sink with the task's
+tags, so a tagged owner (a society agent's routine) can hear about it in its
+own chat. The sink is optional and a failing sink never fails the task."""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.control.cancel import CancelToken
+from jarvis.core.bus import EventBus
+from jarvis.tasks.runner import TaskRunner
+from jarvis.tasks.schema import AgentAction, TaskSpec, TriggerAfterDelay
+from jarvis.tasks.store import TaskStore
+
+
+class FakeAgentBrain:
+ def __init__(self) -> None:
+ self.prompts: list[str] = []
+
+ async def run_task(self, *, prompt: str, allowed_tools: Any, model_tier: Any, trace_id: Any):
+ self.prompts.append(prompt)
+ return "Inbox sorted: 3 replies drafted."
+
+
+async def store(tmp_path: Path):
+ s = TaskStore(tmp_path / "runner.db")
+ await s.init()
+ try:
+ yield s
+ finally:
+ await s.close()
+
+
+async def _run(store: TaskStore, runner: TaskRunner, spec: TaskSpec) -> None:
+ task_id = await store.insert(spec)
+ await asyncio.wait_for(runner.run(task_id, CancelToken()), timeout=2.0)
+
+
+async def test_an_agent_routine_result_reaches_its_sink(store: TaskStore) -> None:
+ delivered: list[tuple[tuple[str, ...], str, str]] = []
+
+ async def sink(tags: tuple[str, ...], text: str, status: str) -> None:
+ delivered.append((tags, text, status))
+
+ runner = TaskRunner(store, EventBus(), agent_brain=FakeAgentBrain(), 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"),
+ )
+ await _run(store, runner, spec)
+ assert delivered == [(("society", "agent:mailbox"), "Inbox sorted: 3 replies drafted.", "done")]
+
+
+async def test_an_untagged_task_and_a_missing_sink_change_nothing(store: TaskStore) -> None:
+ calls: list[Any] = []
+
+ async def sink(tags: tuple[str, ...], text: str, status: str) -> None:
+ calls.append(tags)
+
+ runner = TaskRunner(store, EventBus(), agent_brain=FakeAgentBrain(), result_sink=sink)
+ untagged = TaskSpec(
+ title="plain",
+ trigger=TriggerAfterDelay(delay_seconds=0.01),
+ action=AgentAction(prompt="Say hi."),
+ )
+ await _run(store, runner, untagged)
+ assert calls == []
+ plain = TaskRunner(store, EventBus(), agent_brain=FakeAgentBrain())
+ tagged = TaskSpec(
+ title="[agent:Mailbox] no sink",
+ trigger=TriggerAfterDelay(delay_seconds=0.01),
+ action=AgentAction(prompt="Say hi."),
+ tags=("society", "agent:mailbox"),
+ )
+ await _run(store, plain, tagged)
+
+
+async def test_a_failing_sink_never_fails_the_task(store: TaskStore, caplog) -> None:
+ async def sink(tags: tuple[str, ...], text: str, status: str) -> None:
+ raise RuntimeError("chat is down")
+
+ runner = TaskRunner(store, EventBus(), agent_brain=FakeAgentBrain(), 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"] == "completed"
+ assert any("result sink failed" in r.getMessage() for r in caplog.records)