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(voice): ask a named agent and hear its answer in the same call (#676)

Ruben Lütkea16fdb530b56
diff --git a/jarvis/brain/tool_gateway.py b/jarvis/brain/tool_gateway.py
index 8413e80f62..1978eae202 100644
--- a/jarvis/brain/tool_gateway.py
+++ b/jarvis/brain/tool_gateway.py
@@ -170,6 +170,13 @@ class BrainSupervisorToolGateway:
from jarvis.plugins.tool.show_on_screen import ShowOnScreenTool
tools[ShowOnScreenTool.name] = ShowOnScreenTool()
+ if "message_agent" in tools:
+ # With a team on this install, a call can relay a conversation with
+ # one of its agents: ask, wait for the answer, say it.
+ from jarvis.plugins.tool.ask_agent import AskAgentTool
+ from jarvis.society.runtime import current_runtime
+
+ tools[AskAgentTool.name] = AskAgentTool(runtime_resolver=current_runtime)
if self._workspace_tool is not None:
# Live delegates coding to one addressed service. The old prompt
# tools silently choose an ambient pane and cannot safely coexist.
diff --git a/jarvis/live/config.py b/jarvis/live/config.py
index fff7a7c6a6..530c2cb3a7 100644
--- a/jarvis/live/config.py
+++ b/jarvis/live/config.py
@@ -8,7 +8,12 @@ from pydantic import BaseModel, ConfigDict, Field
from jarvis.core.agent_brief import AGENT_BRIEF_RULE
from jarvis.cu.direct import COMPUTER_CONTROL_RULES
-from jarvis.live.coordination import ON_SCREEN_RULE, WORK_STATUS_RULE, conversation_rules
+from jarvis.live.coordination import (
+ ON_SCREEN_RULE,
+ TEAM_TALK_RULE,
+ WORK_STATUS_RULE,
+ conversation_rules,
+)
from jarvis.live.product import PRODUCT_BRIEF
from jarvis.live.recovery import HISTORY_CONTEXT_RULE
@@ -123,6 +128,7 @@ class LiveConfig(BaseModel):
"count and the task as prompt; never an existing agent and never spawn_worker. "
+ WORK_STATUS_RULE
+ ON_SCREEN_RULE
+ + TEAM_TALK_RULE
+ AGENT_BRIEF_RULE
+ " "
+ (COMPUTER_CONTROL_RULES if computer else "")
diff --git a/jarvis/live/coordination.py b/jarvis/live/coordination.py
index 4c8dace8d5..e36c3d2da7 100644
--- a/jarvis/live/coordination.py
+++ b/jarvis/live/coordination.py
@@ -37,6 +37,14 @@ ON_SCREEN_RULE: Final[str] = (
)
+#: For the model that executes tools: talking with one of the user's agents.
+TEAM_TALK_RULE: Final[str] = (
+ "When the user wants to talk with or ask one of their named agents, use ask_agent: "
+ "it waits for the answer, which you then say as that agent's words. Keep relaying "
+ "while the user addresses that agent, and answer yourself again when they say so. "
+)
+
+
def conversation_rules(executor: str) -> str:
"""The speaking model's rules; ``executor`` is what carries out work for it."""
return (
@@ -69,4 +77,4 @@ def conversation_rules(executor: str) -> str:
)
-__all__ = ["ON_SCREEN_RULE", "WORK_STATUS_RULE", "conversation_rules"]
+__all__ = ["ON_SCREEN_RULE", "TEAM_TALK_RULE", "WORK_STATUS_RULE", "conversation_rules"]
diff --git a/jarvis/live/native.py b/jarvis/live/native.py
index 541c210439..fac50bcd45 100644
--- a/jarvis/live/native.py
+++ b/jarvis/live/native.py
@@ -18,7 +18,12 @@ from jarvis.core.paths import user_data_dir
from jarvis.core.runtime_refs import get_supervisor_tool_gateway
from jarvis.core.tool_budget import VOICE_TOOL_BUDGET_S
from jarvis.cu.direct import COMPUTER_CONTROL_RULES
-from jarvis.live.coordination import ON_SCREEN_RULE, WORK_STATUS_RULE, conversation_rules
+from jarvis.live.coordination import (
+ ON_SCREEN_RULE,
+ TEAM_TALK_RULE,
+ WORK_STATUS_RULE,
+ conversation_rules,
+)
from jarvis.live.product import PRODUCT_BRIEF
from jarvis.live.runtime import claim, register, unregister
from jarvis.live.session import LiveVoiceSession, _identity
@@ -179,6 +184,7 @@ class NativeLiveVoiceSession(LiveVoiceSession):
"retries and never replay uncertain delivery. "
+ WORK_STATUS_RULE
+ ON_SCREEN_RULE
+ + TEAM_TALK_RULE
+ AGENT_BRIEF_RULE
),
history=tuple(
diff --git a/jarvis/live/runtime.py b/jarvis/live/runtime.py
index 582ba20c10..c253b12146 100644
--- a/jarvis/live/runtime.py
+++ b/jarvis/live/runtime.py
@@ -125,7 +125,12 @@ async def show_content(session_id: str, *, title: str, markdown: str) -> bool:
return False
try:
await on_session_loop(session, show, title=title, markdown=markdown)
- except RuntimeError: # the call ended between the lookup and the delivery
+ except RuntimeError as exc:
+ # The call ended between the lookup and the delivery. The caller shows
+ # the content without a call record instead.
+ import logging
+
+ logging.getLogger(__name__).info("Live call %s could not show content: %s", session_id, exc)
return False
return True
diff --git a/jarvis/plugins/tool/ask_agent.py b/jarvis/plugins/tool/ask_agent.py
new file mode 100644
index 0000000000..7b17330b1a
--- /dev/null
+++ b/jarvis/plugins/tool/ask_agent.py
@@ -0,0 +1,166 @@
+"""ask_agent tool: put a question to a named agent and wait for its answer.
+
+``message_agent`` delivers a message and returns at once; the answer comes back
+later as a separate report. That is right for work, and wrong for a
+conversation: a user who says "ask Scout what it found" or "let me talk to the
+Gmail agent" wants the answer in the same breath. This tool sends the question
+through the same delivery path and then waits a bounded time for the reply, so
+a live call can relay a back-and-forth with one agent.
+
+When the reply does not arrive in time nothing is lost: the wait ends, and the
+answer is handed to the conversation when it comes, as any agent report is.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import time
+from typing import Any
+
+from jarvis.core.protocols import ToolResult
+from jarvis.plugins.tool.delegate_to_agent import RuntimeResolver
+
+log = logging.getLogger(__name__)
+
+DEFAULT_WAIT_S = 45
+MAX_WAIT_S = 120
+_POLL_S = 0.5
+
+
+def _now() -> float:
+ return time.monotonic()
+
+
+class AskAgentTool:
+ name = "ask_agent"
+ risk_tier = "safe"
+ is_action_tool = True
+ description = (
+ "Ask one of the user's named Dodaios agents a question and wait for its answer, so "
+ "the user can talk with that agent through you. Use it when the user wants to "
+ "speak with or ask an agent ('ask Scout what it found', 'let me talk to the Gmail "
+ "agent'). Say the answer as that agent's words and name the agent once. While the "
+ "user keeps addressing that agent, pass each of their turns on with ask_agent; "
+ "answer yourself again when they say so or change the subject. To assign work use "
+ "delegate_to_agent; for a note that needs no answer use message_agent. When "
+ "answered is false the agent is still thinking: say so, never invent its answer; "
+ "it is handed to this conversation when it arrives."
+ )
+ schema: dict[str, Any] = {
+ "type": "object",
+ "additionalProperties": False,
+ "properties": {
+ "agent": {"type": "string", "description": "The agent's name or id."},
+ "question": {
+ "type": "string",
+ "description": (
+ "What the user wants to ask or tell the agent, complete in itself: "
+ "the agent does not hear the call."
+ ),
+ },
+ "wait_seconds": {
+ "type": "integer",
+ "minimum": 5,
+ "maximum": MAX_WAIT_S,
+ "description": f"How long to wait for the answer (default {DEFAULT_WAIT_S}).",
+ },
+ },
+ "required": ["agent", "question"],
+ }
+
+ def __init__(self, *, runtime_resolver: RuntimeResolver) -> None:
+ self._resolve = runtime_resolver
+
+ def describe_args(self, args: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "level": "modify",
+ "agent": str(args.get("agent") or ""),
+ "task": str(args.get("question") or "")[:240],
+ }
+
+ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:
+ from jarvis.society.agent_tools import MessageAgentTool
+ from jarvis.society.delegation_wait import result_for
+
+ try:
+ wait_s = int(args.get("wait_seconds") or DEFAULT_WAIT_S)
+ except (TypeError, ValueError): # a malformed wait falls back to the default
+ wait_s = DEFAULT_WAIT_S
+ wait_s = max(5, min(MAX_WAIT_S, wait_s))
+ from jarvis.society.runtime import reply_awaited_inline
+
+ try:
+ runtime = self._resolve()
+ if runtime is None:
+ return ToolResult(success=False, output=None, error="society unavailable")
+ # Started first: tasks the runtime creates must not inherit the mark.
+ await runtime.ensure_started()
+ except Exception as exc: # noqa: BLE001 - an honest, inspectable tool failure
+ log.warning("ask_agent: the agent team is not available", exc_info=True)
+ return ToolResult(success=False, output=None, error=str(exc))
+ # The one question sent below is marked as awaited; ``marked`` receives
+ # its id, so every way out of this call can lift the mark again.
+ marked: list[str] = []
+ waiting = reply_awaited_inline.set(marked)
+ reply = None
+ try:
+ try:
+ sent = await MessageAgentTool(runtime, runtime.lead_id).execute(
+ {
+ "target": str(args.get("agent") or ""),
+ "text": str(args.get("question") or ""),
+ "kind": "query",
+ "reply_policy": "always",
+ },
+ ctx,
+ )
+ except Exception as exc: # noqa: BLE001 - an honest, inspectable tool failure
+ log.warning("ask_agent: delivery failed", exc_info=True)
+ return ToolResult(success=False, output=None, error=str(exc))
+ finally:
+ reply_awaited_inline.reset(waiting)
+ if not sent.success or not isinstance(sent.output, dict):
+ return sent
+ agent = str(sent.output.get("target") or args.get("agent") or "")
+ request = await runtime.store.get_event(str(sent.output.get("message_id") or ""))
+ if request is None:
+ return sent
+ deadline = _now() + wait_s
+ while reply is None and _now() < deadline:
+ await asyncio.sleep(_POLL_S)
+ reply = await result_for(runtime.store, request)
+ finally:
+ # Also after a failed or uncertain send: a reply that still comes
+ # is then announced like any other.
+ for request_id in marked:
+ runtime.stop_awaiting_inline(request_id)
+ if reply is None:
+ # An answer that landed while the wait ended was not announced:
+ # read once more before calling it pending.
+ reply = await result_for(runtime.store, request)
+ if reply is None:
+ return ToolResult(
+ success=True,
+ output={
+ "agent": agent,
+ "answered": False,
+ "status": "pending",
+ "message_id": request.event_id,
+ "note": (
+ f"{agent} has not answered within {wait_s} seconds. Tell the user "
+ "it is still thinking. The answer is handed to this conversation "
+ "when it arrives; do not ask again."
+ ),
+ },
+ )
+ return ToolResult(
+ success=True,
+ output={
+ "agent": agent,
+ "answered": True,
+ "status": reply.get("status") or "done",
+ "answer": str(reply.get("report") or ""),
+ "message_id": request.event_id,
+ },
+ )
diff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.py
index 6da931e0f2..ae0798c011 100644
--- a/jarvis/society/runtime.py
+++ b/jarvis/society/runtime.py
@@ -22,6 +22,7 @@ import inspect
import logging
from collections.abc import Callable, Iterable, Mapping
from contextlib import AsyncExitStack
+from contextvars import ContextVar
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Final
@@ -66,6 +67,15 @@ class _UsablePlugins:
read_at: float
+#: Set by a caller that waits for the reply to the message it is about to send
+#: and says that reply itself (``jarvis.plugins.tool.ask_agent``).
+#: The value is an empty list that receives the id of the ONE question it
+#: marks; a task that inherits the context finds the list already used.
+reply_awaited_inline: ContextVar[list[str] | None] = ContextVar(
+ "reply_awaited_inline", default=None
+)
+
+
class SocietyRuntimeClosed(RuntimeError):
"""This runtime owner has entered terminal shutdown."""
@@ -184,6 +194,9 @@ class SocietyRuntime:
self._data_dir / "society-conversations.db", defer_open=True
)
self._review_lock = asyncio.Lock()
+ #: Requests whose reply a caller is waiting for and will speak itself;
+ #: their answer is not announced a second time (``reply_awaited_inline``).
+ self._awaited_inline: set[str] = set()
#: The Quest Board: the person's jobs, routed to one taker, read back off the board.
self.quests = Quests(self)
from .team_lead import TeamLeads
@@ -422,6 +435,10 @@ class SocietyRuntime:
})
except Exception: # A chat failure must not suppress the voice result.
log.warning("society: result notice delivery failed", exc_info=True)
+ if request.event_id in self._awaited_inline:
+ # The asker is waiting on this very answer and says it itself; the
+ # chat notice above keeps the durable copy.
+ return
surface = request.payload.get("reply_surface")
if surface == "voice" or (surface is None and request.trace_id.startswith("voice:")):
if self._publish_event is not None:
@@ -432,6 +449,10 @@ class SocietyRuntime:
except Exception: # The durable board and chat still retain the report.
log.warning("society: result announcement failed", exc_info=True)
+ def stop_awaiting_inline(self, request_id: str) -> None:
+ """The caller stopped waiting: a later reply is announced as usual."""
+ self._awaited_inline.discard(request_id)
+
async def _deliver_pending(self) -> None:
"""Recover committed messages and retry busy chats without opening sockets."""
while True:
@@ -1285,16 +1306,30 @@ class SocietyRuntime:
turn = current_chat_turn.get()
if turn is not None and turn.direct_user:
body["reply_session_id"] = turn.session_id
- envelope = await self.store.append_and_publish(
- SocietyEnvelope(
- msg_type=msg_type,
- from_agent=from_agent,
- to_agent=to_agent,
- trace_id=trace_id or f"chat:{uuid4().hex}",
- payload=body,
- parent_event_id=parent_event_id,
- )
+ outgoing = SocietyEnvelope(
+ msg_type=msg_type,
+ from_agent=from_agent,
+ to_agent=to_agent,
+ trace_id=trace_id or f"chat:{uuid4().hex}",
+ payload=body,
+ parent_event_id=parent_event_id,
)
+ marked = reply_awaited_inline.get()
+ if (
+ marked is not None
+ and not marked
+ and from_agent == self.lead_id
+ and msg_type is MsgType.QUERY
+ ):
+ # Marked before it is stored: no reply can arrive ahead of the mark.
+ marked.append(outgoing.event_id)
+ self._awaited_inline.add(outgoing.event_id)
+ try:
+ envelope = await self.store.append_and_publish(outgoing)
+ except BaseException:
+ # Never sent: nothing may stay marked for a reply that cannot come.
+ self._awaited_inline.discard(outgoing.event_id)
+ raise
from .delegation_wait import track_request
await track_request(self, envelope)
diff --git a/tests/unit/plugins/tool/test_ask_agent.py b/tests/unit/plugins/tool/test_ask_agent.py
new file mode 100644
index 0000000000..4d11889748
--- /dev/null
+++ b/tests/unit/plugins/tool/test_ask_agent.py
@@ -0,0 +1,194 @@
+"""Asking a named agent waits for its answer, so a call can relay a conversation."""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from types import SimpleNamespace
+from uuid import uuid4
+
+import pytest
+
+from jarvis.core.events import AnnouncementRequested
+from jarvis.plugins.tool import ask_agent
+from jarvis.plugins.tool.ask_agent import AskAgentTool
+from jarvis.society.events import MsgType, SocietyEnvelope
+from jarvis.society.runtime import SocietyRuntime
+from tests.unit.plugins.tool.test_delegate_to_agent import FakeChat
+
+
+def _ctx() -> SimpleNamespace:
+ return SimpleNamespace(
+ trace_id=uuid4(), user_utterance="ask scout", config={"output_language": "en"},
+ memory_read=None,
+ )
+
+
+async def team(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(ask_agent, "_POLL_S", 0.01)
+ spoken: list[object] = []
+ chat = FakeChat(tmp_path / "agent_chat.db")
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ rt = SocietyRuntime(
+ tmp_path, chat_service=lambda: chat, cfg=lambda: cfg, event_publish=spoken.append
+ )
+ await rt.ensure_started()
+ await rt.roster.create(name="Scout", provider="openai", model="gpt-5.2")
+ try:
+ yield rt, spoken
+ finally:
+ await rt.close()
+
+
+async def _question(rt: SocietyRuntime) -> SocietyEnvelope:
+ """The newest question the lead put to an agent."""
+ for _ in range(200):
+ scout = await rt.roster.resolve("Scout")
+ events = await rt.store.events_for_agent(scout.agent_id, limit=10)
+ asked = [e for e in events if e.msg_type is MsgType.QUERY and e.from_agent == rt.lead_id]
+ if asked:
+ return asked[-1]
+ await asyncio.sleep(0.01)
+ raise AssertionError("the question never reached the agent")
+
+
+async def _answer(rt: SocietyRuntime, text: str, *, status: str = "done") -> None:
+ request = await _question(rt)
+ await rt.say(
+ from_agent=request.to_agent, to_agent=rt.lead_id, text=text,
+ trace_id=request.trace_id, msg_type=MsgType.ANSWER,
+ payload={"reply_status": status}, parent_event_id=request.event_id,
+ )
+
+
+async def test_the_answer_comes_back_in_the_same_call_and_is_not_announced_twice(team):
+ rt, spoken = team
+ tool = AskAgentTool(runtime_resolver=lambda: rt)
+ asking = asyncio.create_task(
+ tool.execute({"agent": "scout", "question": "Which VPS did you pick?"}, _ctx())
+ )
+ await _answer(rt, "Hetzner, because of the price.")
+ result = await asyncio.wait_for(asking, 10)
+ assert result.success and result.output["answered"] is True
+ assert result.output["agent"] == "Scout"
+ assert result.output["answer"] == "Hetzner, because of the price."
+ request = await _question(rt)
+ assert request.text == "Which VPS did you pick?" and request.payload["reply_policy"] == "always"
+ await asyncio.sleep(0.05)
+ assert not [e for e in spoken if isinstance(e, AnnouncementRequested)]
+
+
+async def test_a_late_answer_is_handed_to_the_conversation_instead(team, monkeypatch):
+ rt, spoken = team
+ # The wait runs out at once: only this tool's clock jumps, not the loop's.
+ clock = iter([0.0, 0.0])
+ monkeypatch.setattr(ask_agent, "_now", lambda: next(clock, 1000.0))
+ tool = AskAgentTool(runtime_resolver=lambda: rt)
+ result = await tool.execute({"agent": "Scout", "question": "Summarise the inbox."}, _ctx())
+ assert result.success and result.output["answered"] is False
+ assert result.output["status"] == "pending" and "still thinking" in result.output["note"]
+ await _answer(rt, "Three mails need you.")
+ for _ in range(200):
+ if any(isinstance(e, AnnouncementRequested) for e in spoken):
+ break
+ await asyncio.sleep(0.01)
+ announced = [e for e in spoken if isinstance(e, AnnouncementRequested)]
+ assert len(announced) == 1 and "Three mails need you." in (announced[0].report or "")
+
+
+async def test_a_blocked_answer_keeps_its_status(team):
+ rt, _spoken = team
+ tool = AskAgentTool(runtime_resolver=lambda: rt)
+ asking = asyncio.create_task(tool.execute({"agent": "Scout", "question": "Send it."}, _ctx()))
+ await _answer(rt, "I have no mail access.", status="blocked")
+ result = await asyncio.wait_for(asking, 10)
+ assert result.output["answered"] is True and result.output["status"] == "blocked"
+
+
+async def test_an_unknown_agent_or_a_missing_team_is_refused_without_waiting(team):
+ rt, _spoken = team
+ unknown = await AskAgentTool(runtime_resolver=lambda: rt).execute(
+ {"agent": "Ghost", "question": "Anyone there?"}, _ctx()
+ )
+ assert unknown.success is False and "Scout" in unknown.output["available"]
+ absent = await AskAgentTool(runtime_resolver=lambda: None).execute(
+ {"agent": "Scout", "question": "Anyone there?"}, _ctx()
+ )
+ assert absent.success is False and absent.error == "society unavailable"
+
+
+def test_the_wait_is_bounded_and_the_tool_is_offered_only_with_a_team():
+ from jarvis.brain.tool_gateway import BrainSupervisorToolGateway
+
+ wait = AskAgentTool.schema["properties"]["wait_seconds"]
+ assert (wait["minimum"], wait["maximum"]) == (5, ask_agent.MAX_WAIT_S)
+
+ def names(tools: dict) -> set[str]:
+ manager = SimpleNamespace(_tools=tools, _config=SimpleNamespace(computer_use=None))
+ return {d.name for d in BrainSupervisorToolGateway(manager).voice_catalog()}
+
+ stub = SimpleNamespace(
+ description="", schema={"type": "object"}, risk_tier="safe", execute=lambda *a: None
+ )
+ assert "ask_agent" in names({"message_agent": stub})
+ assert "ask_agent" not in names({})
+
+
+async def test_a_send_that_reports_failure_leaves_nothing_marked(team, monkeypatch):
+ rt, spoken = team
+
+ async def failed(_event_id):
+ return "failed"
+
+ monkeypatch.setattr(rt.store, "delivery_status", failed)
+ result = await AskAgentTool(runtime_resolver=lambda: rt).execute(
+ {"agent": "Scout", "question": "Are you there?"}, _ctx()
+ )
+ assert result.success is False
+ assert rt._awaited_inline == set()
+ # The message may have gone out all the same: its answer is announced as usual.
+ await _answer(rt, "Yes.")
+ for _ in range(200):
+ if any(isinstance(e, AnnouncementRequested) for e in spoken):
+ break
+ await asyncio.sleep(0.01)
+ assert [e for e in spoken if isinstance(e, AnnouncementRequested)]
+
+
+async def test_only_the_one_question_is_marked_never_later_traffic(team):
+ from jarvis.society.runtime import reply_awaited_inline
+
+ rt, _spoken = team
+ scout = await rt.roster.resolve("Scout")
+ used: list[str] = []
+ token = reply_awaited_inline.set(used)
+ try:
+ first = await rt.say(
+ from_agent=rt.lead_id, to_agent=scout.agent_id, text="one", msg_type=MsgType.QUERY
+ )
+ # A task that inherited the context sends more: none of it is marked.
+ second = await asyncio.create_task(
+ rt.say(from_agent=rt.lead_id, to_agent=scout.agent_id, text="two",
+ msg_type=MsgType.QUERY)
+ )
+ note = await rt.say(
+ from_agent=scout.agent_id, to_agent=rt.lead_id, text="fyi", msg_type=MsgType.SAY
+ )
+ finally:
+ reply_awaited_inline.reset(token)
+ assert used == [first.event_id]
+ assert rt._awaited_inline == {first.event_id}
+ assert second.event_id not in rt._awaited_inline and note.event_id not in rt._awaited_inline
+ rt.stop_awaiting_inline(first.event_id)
+ assert rt._awaited_inline == set()
+
+
+async def test_after_every_way_out_nothing_stays_marked(team):
+ rt, _spoken = team
+ tool = AskAgentTool(runtime_resolver=lambda: rt)
+ asking = asyncio.create_task(tool.execute({"agent": "Scout", "question": "Status?"}, _ctx()))
+ await _question(rt)
+ asking.cancel()
+ await asyncio.gather(asking, return_exceptions=True)
+ assert rt._awaited_inline == set()