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(agent-chat): a clickable approval card answers ToolExecutor's ticket

rubenluetke10-beepfb1e4989aca2
diff --git a/jarvis/agent_chat/approval_bridge.py b/jarvis/agent_chat/approval_bridge.py
new file mode 100644
index 0000000000..0a602cc79d
--- /dev/null
+++ b/jarvis/agent_chat/approval_bridge.py
@@ -0,0 +1,227 @@
+"""The chat's approval card answers ``ToolExecutor``'s ticket.
+
+On the Jarvis surface a typed turn runs on Jarvis' own harness, and its tools
+run through ``ToolExecutor`` (jarvis/safety/tool_executor.py). When the
+executor decides a call needs a person — an ``ask``-tier tool, or a
+plausibility doubt — it arms an approval ticket, publishes
+``ActionApprovalRequired`` and waits for an ``ActionApproved`` /
+``ActionDenied`` on the bus. On the voice path that decision is a spoken
+"yes" on the next turn; here it is a CLICK on the chat's approval card. This
+bridge is what turns the click into the bus event the ticket is waiting for,
+and what makes the chat's permission stance mean something:
+
+============ ================== ============ ==================
+stance folder Write/Edit RunCommand Jarvis ask-tier
+============ ================== ============ ==================
+``ask`` card card card
+``accept-edits`` approved card card
+``bypass`` approved approved approved
+``plan`` (not offered) (not offered) (not offered)
+============ ================== ============ ==================
+
+A tool the person once answered with "always allow" is approved without a
+card for the rest of the session, in every stance below ``bypass``. The
+blacklist is never reached from here: ``RiskTierEvaluator.evaluate`` raises
+for a blacklisted call before the executor ever asks anyone, in every stance
+— "bypass" bypasses the ASKING, not the blocking.
+
+Shape, and the one rule it obeys: like ``TaskAutoApprover`` this is ONE
+persistent subscriber with a map of grants keyed by ``approval_ref`` (the
+chat stamps ``"agent-chat:<session_id>"`` through its tool context, the
+executor echoes it on the event), so several chats can run at once without
+a subscribe/unsubscribe race. And it NEVER awaits the person inside the
+handler: ``EventBus.publish`` awaits every subscriber, so a handler that
+blocked on a click would stall the executor's own publish. A synchronous
+decision (a stance or an "always") is published inline; a card is asked in
+a task of its own and the decision published when it lands.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from collections import OrderedDict
+from collections.abc import Awaitable, Callable
+from dataclasses import dataclass, field
+from typing import Any, Final
+from uuid import UUID
+
+from jarvis.core.events import ActionApprovalRequired, ActionApproved, ActionDenied, ActionProposed
+
+log = logging.getLogger(__name__)
+
+#: ``ExecutionContext.config["approval_ref"]`` for one chat session.
+REF_PREFIX: Final[str] = "agent-chat:"
+
+#: The folder tools an ``accept-edits`` stance waves through.
+EDIT_TOOLS: Final[frozenset[str]] = frozenset({"Write", "Edit"})
+
+#: How many ``ActionProposed`` argument sets are remembered for the cards'
+#: "what exactly" — one per in-flight call would do; a few more cost nothing.
+_ARGS_CACHE_SIZE: Final[int] = 64
+
+#: What the card's ``ask`` callback answers with.
+AskFn = Callable[[str, str, dict[str, Any], str], Awaitable[str]]
+
+
+def approval_ref(session_id: str) -> str:
+ return f"{REF_PREFIX}{session_id}"
+
+
+@dataclass(slots=True)
+class ChatGrant:
+ """What one chat turn allows without asking, and how it asks otherwise."""
+
+ session_id: str
+ turn_id: str
+ #: ``ask`` | ``accept-edits`` | ``bypass`` | ``plan`` (permissions.py).
+ stance: str
+ #: The tools the person waved through with "always allow" this session —
+ #: shared with the service, which owns the set.
+ always_allowed: set[str]
+ #: ``ask(call_id, tool_name, args, summary) -> "allow" | "allow_always" |
+ #: "deny" | "cancel"`` — the service's card.
+ ask: AskFn
+ #: The timeline row the card belongs to (the step mirror's open call for
+ #: this tool), else a fresh id.
+ call_id_for: Callable[[str], str] = field(default=lambda name: "")
+ edit_tools: frozenset[str] = EDIT_TOOLS
+ #: Tools the vendor CLI already asked about on its own control channel
+ #: this turn (Claude Code's ``can_use_tool``): the executor's gate for the
+ #: same tool is answered without a second card.
+ pre_approved: set[str] = field(default_factory=set)
+
+
+class ChatApprovalBridge:
+ """One subscriber, many chats: turns approval tickets into cards and back."""
+
+ def __init__(self, bus: Any) -> None:
+ self._bus = bus
+ self._grants: dict[str, ChatGrant] = {}
+ self._args: OrderedDict[UUID, dict[str, Any]] = OrderedDict()
+ self._tasks: set[asyncio.Task[None]] = set()
+ bus.subscribe(ActionProposed, self._on_proposed)
+ bus.subscribe(ActionApprovalRequired, self._on_required)
+
+ # ------------------------------------------------------------ grants
+
+ def arm(self, ref: str, grant: ChatGrant) -> None:
+ self._grants[ref] = grant
+
+ def disarm(self, ref: str) -> None:
+ self._grants.pop(ref, None)
+
+ def is_armed(self, ref: str) -> bool:
+ return ref in self._grants
+
+ def note_cli_approval(self, ref: str, tool_name: str) -> None:
+ """A vendor CLI's own prompt for ``tool_name`` was answered "allow"."""
+ grant = self._grants.get(ref)
+ if grant is not None:
+ grant.pre_approved.add(_bare(tool_name))
+
+ # ------------------------------------------------------------ events
+
+ async def _on_proposed(self, event: ActionProposed) -> None:
+ # The card wants the real arguments; the approval event only carries
+ # a redacted preview. Keep the last few proposals by trace.
+ try:
+ self._args[event.trace_id] = dict(event.args or {})
+ while len(self._args) > _ARGS_CACHE_SIZE:
+ self._args.popitem(last=False)
+ except Exception: # noqa: BLE001 — AP-18: a subscriber never raises into the bus
+ log.debug("chat approval bridge: could not cache proposed args", exc_info=True)
+
+ async def _on_required(self, event: ActionApprovalRequired) -> None:
+ try:
+ ref = getattr(event, "approval_ref", None)
+ grant = self._grants.get(ref) if ref else None
+ if grant is None:
+ return
+ decision = self._decide_inline(grant, event.tool_name)
+ if decision is not None:
+ await self._bus.publish(
+ ActionApproved(
+ trace_id=event.trace_id,
+ tool_name=event.tool_name,
+ approved_by=decision,
+ )
+ )
+ return
+ task = asyncio.create_task(
+ self._ask_and_answer(grant, event),
+ name=f"agent-chat-approval-{grant.session_id[:8]}",
+ )
+ self._tasks.add(task)
+ task.add_done_callback(self._tasks.discard)
+ except Exception: # noqa: BLE001 — AP-18: a subscriber never raises into the bus
+ log.warning("chat approval bridge: could not handle an approval request", exc_info=True)
+
+ # ------------------------------------------------------------ policy
+
+ @staticmethod
+ def _decide_inline(grant: ChatGrant, tool_name: str) -> str | None:
+ """The ``approved_by`` label when the stance decides without a card, else None."""
+ name = _bare(tool_name)
+ if grant.stance == "bypass":
+ return "chat-bypass"
+ if name in grant.always_allowed:
+ return "user"
+ if name in grant.pre_approved:
+ return "user"
+ if grant.stance == "accept-edits" and name in grant.edit_tools:
+ return "chat-accept-edits"
+ return None
+
+ async def _ask_and_answer(self, grant: ChatGrant, event: ActionApprovalRequired) -> None:
+ args = self._args.pop(event.trace_id, None) or {}
+ summary = _summary(args, event.args_preview)
+ call_id = ""
+ try:
+ call_id = grant.call_id_for(event.tool_name) or ""
+ except Exception: # noqa: BLE001 — a missing row is cosmetic, the card still asks
+ log.debug("chat approval bridge: no timeline row for %s", event.tool_name)
+ try:
+ decision = await grant.ask(call_id, event.tool_name, args, summary)
+ except Exception: # noqa: BLE001 — the ticket must be answered either way
+ log.warning("chat approval bridge: the card failed; denying", exc_info=True)
+ decision = "deny"
+ if decision in ("allow", "allow_always"):
+ if decision == "allow_always":
+ grant.always_allowed.add(_bare(event.tool_name))
+ await self._bus.publish(
+ ActionApproved(
+ trace_id=event.trace_id, tool_name=event.tool_name, approved_by="user"
+ )
+ )
+ return
+ reason = "cancelled" if decision == "cancel" else "declined by the person"
+ await self._bus.publish(
+ ActionDenied(trace_id=event.trace_id, tool_name=event.tool_name, reason=reason)
+ )
+
+
+def _bare(tool_name: str) -> str:
+ """A tool's own name without an MCP prefix (``mcp__jarvis__open-app`` -> ``open-app``)."""
+ name = tool_name or ""
+ if name.startswith("mcp__"):
+ return name.split("__", 2)[-1]
+ return name
+
+
+def _summary(args: dict[str, Any], preview: str) -> str:
+ for key in ("command", "file_path", "pattern", "path", "query", "title", "to"):
+ value = args.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip().splitlines()[0][:200]
+ return (preview or "")[:200]
+
+
+__all__ = [
+ "EDIT_TOOLS",
+ "REF_PREFIX",
+ "AskFn",
+ "ChatApprovalBridge",
+ "ChatGrant",
+ "approval_ref",
+]
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index f3a2bb0e56..1c9d2f717c 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -487,6 +487,11 @@ class ActionApprovalRequired(Event):
expires_at_ns: int = 0
mission_id: str | None = None
worker_id: str | None = None
+ #: Correlation for a surface that answers its own approval cards — the
+ #: typed chat stamps ``"agent-chat:<session_id>"`` through its tool
+ #: context so its bridge recognises the calls of ITS turn and no other.
+ #: ``None`` on every other surface.
+ approval_ref: str | None = None
@dataclass(frozen=True, slots=True)
diff --git a/jarvis/safety/tool_executor.py b/jarvis/safety/tool_executor.py
index e9a333f667..53cd4417df 100644
--- a/jarvis/safety/tool_executor.py
+++ b/jarvis/safety/tool_executor.py
@@ -116,6 +116,22 @@ class ToolExecutor:
# args live here OUT-OF-BAND — never in the serialized ToolResult.output.
self._pending_voice: dict[UUID, tuple[Tool, dict[str, Any]]] = {}
+ #: The longest a surface may keep an approval open, whatever it asks for.
+ MAX_APPROVAL_TIMEOUT_S = 900.0
+
+ def _approval_timeout(self, config_snapshot: dict[str, Any] | None) -> float:
+ """The wait for this call: the surface's ``approval_timeout_s`` when it
+ declares one (never below the default, never above the cap), else the
+ default the executor was built with."""
+ raw = (config_snapshot or {}).get("approval_timeout_s")
+ if raw is None:
+ return self._default_timeout_s
+ try:
+ asked = float(raw)
+ except (TypeError, ValueError):
+ return self._default_timeout_s
+ return max(self._default_timeout_s, min(asked, self.MAX_APPROVAL_TIMEOUT_S))
+
def set_plausibility_context_fn(
self, fn: PlausibilityContextFn | None,
) -> None:
@@ -318,6 +334,11 @@ class ToolExecutor:
# above is the untouched tier decision.
surface = resolve_approval_surface(config_snapshot)
voice_confirm = surface == CONVERSATIONAL
+ # How long a card may stay open — declared by the calling layer like
+ # the surface itself (a person reading a chat card must not lose the
+ # tool to a clock built for a spoken "ja"), clamped so no surface can
+ # park the executor forever.
+ approval_timeout_s = self._approval_timeout(config_snapshot)
approval_ticket = None
if needs_confirm and not voice_confirm:
# An unattended call arms too: the pre-authorization bridges answer
@@ -352,7 +373,7 @@ class ToolExecutor:
window_ns = (
0
if surface == UNATTENDED
- else int(self._default_timeout_s * 1_000_000_000)
+ else int(approval_timeout_s * 1_000_000_000)
)
await self._bus.publish(
ActionApprovalRequired(
@@ -368,6 +389,9 @@ class ToolExecutor:
worker_id=_optional_string(
(config_snapshot or {}).get("worker_id")
),
+ approval_ref=_optional_string(
+ (config_snapshot or {}).get("approval_ref")
+ ),
)
)
@@ -432,7 +456,7 @@ class ToolExecutor:
else:
try:
approved, who_or_reason = await self._approval.wait(
- tid, self._default_timeout_s
+ tid, approval_timeout_s
)
finally:
if approval_ticket is not None:
@@ -449,7 +473,7 @@ class ToolExecutor:
if who_or_reason == TIMEOUT_REASON:
error = (
f"{APPROVAL_TIMEOUT_PREFIX} (nobody decided within "
- f"{self._default_timeout_s:.0f}s)"
+ f"{approval_timeout_s:.0f}s)"
)
else:
error = f"{APPROVAL_DENIED_PREFIX} ({who_or_reason})"
diff --git a/tests/unit/agent_chat/test_approval_bridge.py b/tests/unit/agent_chat/test_approval_bridge.py
new file mode 100644
index 0000000000..ff1ab45fc3
--- /dev/null
+++ b/tests/unit/agent_chat/test_approval_bridge.py
@@ -0,0 +1,265 @@
+"""The chat's approval card answers the executor's ticket — with the REAL executor.
+
+No mocks: a real ``EventBus``, ``ToolExecutor``, ``ApprovalWorkflow`` and
+``RiskTierEvaluator``, the chat's folder tools, and the bridge in between.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+from typing import Any
+
+from jarvis.agent_chat import folder_tools as ft
+from jarvis.agent_chat.approval_bridge import ChatApprovalBridge, ChatGrant, approval_ref
+from jarvis.core.bus import EventBus
+from jarvis.core.config import SafetyConfig
+from jarvis.core.events import ActionApprovalRequired, ActionDenied
+from jarvis.safety.approval import ApprovalWorkflow
+from jarvis.safety.risk_tier import RiskTierEvaluator
+from jarvis.safety.tool_executor import APPROVAL_DENIED_PREFIX, ToolExecutor
+
+SESSION = "sess-1"
+REF = approval_ref(SESSION)
+
+
+class _Card:
+ """The chat's card, scripted: records what it was asked, answers what it is told."""
+
+ def __init__(self, answer: str = "allow") -> None:
+ self.answer = answer
+ self.asked: list[tuple[str, str, dict[str, Any], str]] = []
+ self.release = asyncio.Event()
+ self.release.set()
+
+ async def __call__(self, call_id: str, name: str, args: dict[str, Any], summary: str) -> str:
+ self.asked.append((call_id, name, dict(args), summary))
+ await self.release.wait()
+ return self.answer
+
+
+def _stack(
+ *, timeout_s: float = 5.0, safety: SafetyConfig | None = None
+) -> tuple[ToolExecutor, ChatApprovalBridge, EventBus]:
+ bus = EventBus()
+ executor = ToolExecutor(
+ bus,
+ RiskTierEvaluator(safety or SafetyConfig()),
+ ApprovalWorkflow(bus, timeout_s=timeout_s),
+ default_timeout_s=timeout_s,
+ )
+ return executor, ChatApprovalBridge(bus), bus
+
+
+def _snapshot(timeout_s: float = 600.0) -> dict[str, Any]:
+ return {
+ "approval_surface": "interactive",
+ "approval_ref": REF,
+ "approval_timeout_s": timeout_s,
+ }
+
+
+def _grant(card: _Card, stance: str, always: set[str] | None = None) -> ChatGrant:
+ return ChatGrant(
+ session_id=SESSION,
+ turn_id="turn-1",
+ stance=stance,
+ always_allowed=always if always is not None else set(),
+ ask=card,
+ call_id_for=lambda name: f"row-{name}",
+ )
+
+
+def _denials(bus: EventBus) -> list[ActionDenied]:
+ seen: list[ActionDenied] = []
+
+ async def _capture(event: ActionDenied) -> None:
+ seen.append(event)
+
+ bus.subscribe(ActionDenied, _capture)
+ return seen
+
+
+# ------------------------------------------------------------------ ask
+
+
+async def test_ask_stance_runs_the_tool_only_after_the_card_allows(tmp_path: Path):
+ executor, bridge, _ = _stack()
+ card = _Card("allow")
+ bridge.arm(REF, _grant(card, "ask"))
+ write = ft.folder_tools(tmp_path)["Write"]
+
+ result = await executor.execute(
+ write, {"file_path": "a.txt", "content": "hi"}, config_snapshot=_snapshot()
+ )
+
+ assert result.success, result.error
+ assert (tmp_path / "a.txt").read_text(encoding="utf-8") == "hi"
+ assert card.asked == [("row-Write", "Write", {"file_path": "a.txt", "content": "hi"}, "a.txt")]
+
+
+async def test_deny_on_the_card_yields_approval_denied(tmp_path: Path):
+ executor, bridge, bus = _stack()
+ denials = _denials(bus)
+ card = _Card("deny")
+ bridge.arm(REF, _grant(card, "ask"))
+ write = ft.folder_tools(tmp_path)["Write"]
+
+ result = await executor.execute(
+ write, {"file_path": "a.txt", "content": "hi"}, config_snapshot=_snapshot()
+ )
+
+ assert not result.success
+ assert result.error and result.error.startswith(APPROVAL_DENIED_PREFIX)
+ assert not (tmp_path / "a.txt").exists()
+ assert denials and denials[-1].reason == "declined by the person"
+
+
+async def test_reads_never_ask(tmp_path: Path):
+ (tmp_path / "r.txt").write_text("x", encoding="utf-8")
+ executor, bridge, _ = _stack()
+ card = _Card("deny")
+ bridge.arm(REF, _grant(card, "ask"))
+ read = ft.folder_tools(tmp_path)["Read"]
+ result = await executor.execute(read, {"file_path": "r.txt"}, config_snapshot=_snapshot())
+ assert result.success and card.asked == []
+
+
+async def test_the_bridge_never_blocks_the_executors_publish(tmp_path: Path):
+ """The card may take minutes; the executor's publish must return at once."""
+ executor, bridge, _ = _stack()
+ card = _Card("allow")
+ card.release.clear() # the person has not clicked yet
+ bridge.arm(REF, _grant(card, "ask"))
+ write = ft.folder_tools(tmp_path)["Write"]
+
+ running = asyncio.create_task(
+ executor.execute(write, {"file_path": "b.txt", "content": "x"}, config_snapshot=_snapshot())
+ )
+ for _ in range(20):
+ await asyncio.sleep(0)
+ assert card.asked, "the card is open while the executor waits on its ticket"
+ assert not running.done()
+ card.release.set()
+ result = await asyncio.wait_for(running, timeout=5.0)
+ assert result.success
+
+
+# --------------------------------------------------------------- stances
+
+
+async def test_accept_edits_waves_writes_through_but_cards_commands(tmp_path: Path):
+ executor, bridge, _ = _stack()
+ card = _Card("deny")
+ bridge.arm(REF, _grant(card, "accept-edits"))
+ tools = ft.folder_tools(tmp_path)
+
+ written = await executor.execute(
+ tools["Write"], {"file_path": "c.txt", "content": "x"}, config_snapshot=_snapshot()
+ )
+ assert written.success and card.asked == []
+
+ ran = await executor.execute(
+ tools["RunCommand"], {"command": "echo hi"}, config_snapshot=_snapshot()
+ )
+ assert not ran.success and ran.error and ran.error.startswith(APPROVAL_DENIED_PREFIX)
+ assert [a[1] for a in card.asked] == ["RunCommand"]
+
+
+async def test_bypass_asks_nothing(tmp_path: Path):
+ executor, bridge, _ = _stack()
+ card = _Card("deny")
+ bridge.arm(REF, _grant(card, "bypass"))
+ tools = ft.folder_tools(tmp_path)
+ ran = await executor.execute(
+ tools["RunCommand"], {"command": "echo hi"}, config_snapshot=_snapshot()
+ )
+ assert ran.success, ran.error
+ assert card.asked == []
+
+
+async def test_blacklist_wins_in_every_stance(tmp_path: Path):
+ safety = SafetyConfig()
+ safety.blacklist.commands = ["*forbidden-thing*"] # fnmatch, as in jarvis.toml
+ for stance in ("ask", "accept-edits", "bypass"):
+ executor, bridge, _ = _stack(safety=safety)
+ card = _Card("allow")
+ bridge.arm(REF, _grant(card, stance))
+ run = ft.folder_tools(tmp_path)["RunCommand"]
+ result = await executor.execute(
+ run, {"command": "echo forbidden-thing"}, config_snapshot=_snapshot()
+ )
+ assert not result.success, stance
+ assert card.asked == [], f"{stance}: a blacklisted call must never reach a card"
+
+
+async def test_always_allow_remembers_the_tool_for_the_session(tmp_path: Path):
+ executor, bridge, _ = _stack()
+ always: set[str] = set()
+ card = _Card("allow_always")
+ bridge.arm(REF, _grant(card, "ask", always))
+ write = ft.folder_tools(tmp_path)["Write"]
+
+ first = await executor.execute(
+ write, {"file_path": "d.txt", "content": "1"}, config_snapshot=_snapshot()
+ )
+ second = await executor.execute(
+ write, {"file_path": "e.txt", "content": "2"}, config_snapshot=_snapshot()
+ )
+ assert first.success and second.success
+ assert always == {"Write"}
+ assert len(card.asked) == 1, "the second write was waved through"
+
+
+async def test_a_cli_approval_pre_answers_the_executor_gate(tmp_path: Path):
+ executor, bridge, _ = _stack()
+ card = _Card("deny")
+ bridge.arm(REF, _grant(card, "ask"))
+ bridge.note_cli_approval(REF, "mcp__jarvis__Write")
+ write = ft.folder_tools(tmp_path)["Write"]
+ result = await executor.execute(
+ write, {"file_path": "f.txt", "content": "x"}, config_snapshot=_snapshot()
+ )
+ assert result.success and card.asked == []
+
+
+async def test_another_sessions_calls_are_not_answered(tmp_path: Path):
+ """A grant answers ITS session's calls only; an unarmed ref is left to the executor."""
+ executor, bridge, _ = _stack(timeout_s=0.2)
+ card = _Card("allow")
+ bridge.arm(approval_ref("other"), _grant(card, "bypass"))
+ write = ft.folder_tools(tmp_path)["Write"]
+ result = await executor.execute(
+ write, {"file_path": "g.txt", "content": "x"}, config_snapshot=_snapshot(timeout_s=0.2)
+ )
+ assert not result.success and card.asked == []
+
+
+# --------------------------------------------------------------- executor
+
+
+async def test_the_surface_declares_the_timeout_within_the_cap():
+ executor, _, _ = _stack(timeout_s=5.0)
+ assert executor._approval_timeout(None) == 5.0
+ assert executor._approval_timeout({}) == 5.0
+ assert executor._approval_timeout({"approval_timeout_s": 600}) == 600.0
+ assert executor._approval_timeout({"approval_timeout_s": 2}) == 5.0, "never below the default"
+ assert executor._approval_timeout({"approval_timeout_s": 5000}) == 900.0, "never above the cap"
+ assert executor._approval_timeout({"approval_timeout_s": "nonsense"}) == 5.0
+
+
+async def test_the_approval_event_carries_the_chat_ref(tmp_path: Path):
+ executor, bridge, bus = _stack()
+ seen: list[ActionApprovalRequired] = []
+
+ async def _capture(event: ActionApprovalRequired) -> None:
+ seen.append(event)
+
+ bus.subscribe(ActionApprovalRequired, _capture)
+ bridge.arm(REF, _grant(_Card("allow"), "ask"))
+ write = ft.folder_tools(tmp_path)["Write"]
+ await executor.execute(
+ write, {"file_path": "h.txt", "content": "x"}, config_snapshot=_snapshot()
+ )
+ assert seen and seen[0].approval_ref == REF
+ assert seen[0].expires_at_ns > 0