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
feat(society): Always allow writes the agent's own rule, and every tool call obeys those rules
rubenluetke10-beep1b7cc3b9a8b7
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.pyindex 36969dc25e..8ea05ae296 100644--- a/jarvis/agent_chat/service.py+++ b/jarvis/agent_chat/service.py@@ -553,7 +553,18 @@ class AgentChatService:)if decision == "allow_always":session = self.store.get_session(session_id)- if session is not None and session.surface == "jarvis":+ handled = False+ hook = kit_for(session.surface).session_always_allow if session is not None else None+ if hook is not None:+ # A surface with its own memory for "always allow" (a society+ # agent's approval rules) keeps the session's stance untouched.+ try:+ handled = bool(await hook(session, name, args))+ except Exception: # noqa: BLE001 — falls back to the session-wide default below+ log.warning("agent chat: always-allow hook failed for %s", name, exc_info=True)+ if handled:+ pass+ elif session is not None and session.surface == "jarvis":self._always_allowed.setdefault(session_id, set()).add(name)else:self.store.update_session(session_id, permission_mode="auto")diff --git a/jarvis/agent_chat/surface_kits.py b/jarvis/agent_chat/surface_kits.pyindex 63a928190f..1b5f148e2e 100644--- a/jarvis/agent_chat/surface_kits.py+++ b/jarvis/agent_chat/surface_kits.py@@ -41,6 +41,11 @@ ExtraBuilder = Callable[[Any, Any], Awaitable[str]]SessionToolsBuilder = Callable[[Any, Any, Any], dict[str, Tool]]SessionExtraBuilder = Callable[[Any, Any, Any], Awaitable[str]]SessionFilterBuilder = Callable[[Any], Callable[[dict[str, Tool]], dict[str, Tool]] | None]+#: ``(session, tool_name, args) -> handled``: what "Always allow" on the+#: approval card means on this surface. ``True`` = the surface remembered it+#: its own way (a society agent writes its own approval rule); ``False`` =+#: the service falls back to its default (the session flips to auto).+SessionAlwaysAllow = Callable[[Any, str, dict[str, Any]], Awaitable[bool]]@dataclass(frozen=True, slots=True)@@ -98,6 +103,8 @@ class SurfaceKit:session_tools: SessionToolsBuilder | None = Nonesession_system_extra: SessionExtraBuilder | None = Nonesession_tool_filter: SessionFilterBuilder | None = None+ #: How the card's "Always allow" is remembered here (see the alias above).+ session_always_allow: SessionAlwaysAllow | None = Nonedef _chat_workspace() -> Path:@@ -149,6 +156,13 @@ def _society_filter(session: Any) -> Callable[[dict[str, Tool]], dict[str, Tool]return society_tool_filter(session)+async def _society_always_allow(session: Any, tool_name: str, args: dict[str, Any]) -> bool:+ """ "Always allow" writes the agent's own approval rule (lazy)."""+ from jarvis.society.surface import remember_always_allow++ return await remember_always_allow(session, tool_name, args)++def _only_local_models(tools: dict[str, Tool]) -> dict[str, Tool]:"""Its own hands and nothing else.@@ -225,6 +239,7 @@ _KITS: Final[dict[str, SurfaceKit]] = {session_tools=_society_tools,session_system_extra=_society_extra,session_tool_filter=_society_filter,+ session_always_allow=_society_always_allow,workspace_dir=_chat_workspace,),}diff --git a/jarvis/society/approvals.py b/jarvis/society/approvals.pyindex 20f658ac5a..9a8e3ef79d 100644--- a/jarvis/society/approvals.py+++ b/jarvis/society/approvals.py@@ -10,7 +10,8 @@ person decides.Rule evaluation (``decide``), in order: global blacklist (not here — theToolExecutor raises before anything), the agent's ``require_approval``patterns (queue), its ``always_allow`` patterns (run when the tool's own-tier is at most ``monitor``), then the tool's risk tier against the ceiling.+tier is at most ``ask`` — the person's standing yes), then the tool's risk+tier against the ceiling.Patterns are capability ids (``plugin:gmail``), ``capability:verb``(``plugin:gmail:send``) or ``capability:*``."""@@ -67,7 +68,10 @@ def decide(agent: AgentRecord, capability_id: str, tool_tier: str, *, verb: strif any(matches(p, capability_id, verb) for p in rules.get("require_approval", [])):return Verdict.QUEUEif any(matches(p, capability_id, verb) for p in rules.get("always_allow", [])):- return Verdict.RUN if _TIER_RANK.get(tool_tier, 1) <= 1 else Verdict.QUEUE+ # An explicit always-allow rule is the person's standing "yes" for this+ # exact action (the card's "Always allow", agent-definition §3.4): it+ # runs up to the ask tier. Block stays block — it never had a card.+ return Verdict.RUN if _TIER_RANK.get(tool_tier, 1) <= 2 else Verdict.QUEUEceiling = _TIER_RANK[str(agent.permission_ceiling)]tier = _TIER_RANK.get(tool_tier, 1)if tier <= ceiling and tool_tier != str(PermissionCeiling.ASK):diff --git a/jarvis/society/surface.py b/jarvis/society/surface.pyindex 80a2ace188..9714c7145d 100644--- a/jarvis/society/surface.py+++ b/jarvis/society/surface.py@@ -34,7 +34,7 @@ from .agent_tools import (ShellTool,WikiNoteTool,)-from .capabilities import CapabilityKind, CapabilityRow, select_tools+from .capabilities import CapabilityKind, CapabilityRow, capability_id_for_tool, select_toolsfrom .learning import RunLearnedSkillToolfrom .memory import resolve_society_vaultfrom .roster import AgentRecord, canonical_session_id@@ -47,6 +47,7 @@ __all__ = ["agent_id_of","build_briefing","capability_epoch",+ "remember_always_allow","society_system_extra","society_tool_filter","society_tools",@@ -160,6 +161,114 @@ def society_tools(cfg: Any, brain: Any, session: Any) -> dict[str, Tool]:return tools+#: Argument keys that name WHAT a mixed-action tool does (``gmail: send``).+_VERB_KEYS: Final[tuple[str, ...]] = ("action", "operation", "method", "command", "mode")+++def _verb_of(args: dict[str, Any]) -> str:+ for key in _VERB_KEYS:+ raw = args.get(key)+ if isinstance(raw, str) and raw.strip():+ return raw.strip().lower()[:40]+ return ""+++class _GatedTool:+ """A granted tool wrapped with the agent's approval rules.++ The executor asks ``risk_tier_for_args`` before every call; this wrapper+ answers with ``approvals.decide`` over the roster row's rules and ceiling:+ a require-approval match or a call above the ceiling reads as ``ask`` (the+ chat card appears), an always-allow match lets an ask-tier call run, a+ blocked class stays ``block``. Everything else — schema, flags, execute —+ is the inner tool's own.+ """++ def __init__(self, inner: Any, agent: AgentRecord, capability_id: str) -> None:+ self._inner = inner+ self._agent = agent+ self._capability_id = capability_id+ self.name = inner.name+ self.description = inner.description+ self.schema = inner.schema+ self.risk_tier = inner.risk_tier++ def __getattr__(self, item: str) -> Any:+ return getattr(self._inner, item)++ def risk_tier_for_args(self, args: dict[str, Any]) -> str | None:+ from .approvals import Verdict, decide++ base = str(self.risk_tier or "monitor")+ hook = getattr(self._inner, "risk_tier_for_args", None)+ if callable(hook):+ try:+ own = hook(args)+ except Exception: # noqa: BLE001 — a broken inner hook falls back to the static tier+ log.warning("society gate: %s.risk_tier_for_args raised", self.name, exc_info=True)+ own = None+ if isinstance(own, str) and own:+ base = own+ try:+ verdict = decide(self._agent, self._capability_id, base, verb=_verb_of(args))+ except Exception: # noqa: BLE001 — the static tier still gates the call+ log.warning("society gate: decide failed for %s", self.name, exc_info=True)+ return base+ if verdict is Verdict.BLOCK:+ return "block"+ if verdict is Verdict.QUEUE:+ return "ask"+ # RUN: an always-allow rule lifts an ask-tier call to monitor — the+ # person's standing yes; anything lower keeps its own tier.+ return "monitor" if base == "ask" else base++ async def execute(self, args: dict[str, Any], ctx: Any) -> Any:+ return await self._inner.execute(args, ctx)+++async def remember_always_allow(session: Any, tool_name: str, args: dict[str, Any]) -> bool:+ """The card's "Always allow" on a society session writes the agent's OWN+ rule (``approval_rules.always_allow``: ``capability`` or ``capability:verb``)+ instead of flipping the session to auto. Returns False when this is not a+ society session or the tool has no capability id, so the caller falls back.+ """+ rt = current_runtime()+ agent_id = agent_id_of(getattr(session, "session_id", "") or "")+ if rt is None or agent_id is None:+ return False+ cap_id = capability_id_for_tool(tool_name)+ if cap_id is None:+ return False+ agent = await rt.roster.get(agent_id)+ if agent is None:+ return False+ verb = _verb_of(args)+ pattern = f"{cap_id}:{verb}" if verb else cap_id+ rules = {+ "require_approval": list(agent.approval_rules.get("require_approval", [])),+ "always_allow": list(agent.approval_rules.get("always_allow", [])),+ }+ if pattern not in rules["always_allow"]:+ rules["always_allow"].append(pattern)+ rules["always_allow"].sort()+ updated = await rt.roster.update(agent.agent_id, {"approval_rules": rules})+ rt.cache_agent(updated)+ try:+ await rt.post_chat_notice(+ agent,+ {+ "kind": "always_allow",+ "pattern": pattern,+ "agent_id": agent.agent_id,+ "agent_name": agent.name,+ "text": f"{agent.name} may now run {pattern} without asking.",+ },+ )+ except Exception: # noqa: BLE001 — the rule is saved; the notice is a projection+ log.warning("society: always-allow notice not posted for %s", agent_id, exc_info=True)+ return True++class _ContainedTool:"""A folder tool whose path arguments must stay inside the workspace."""@@ -236,6 +345,14 @@ def society_tool_filter(session: Any) -> Callable[[dict[str, Tool]], dict[str, Tfocus=agent.focus,denies=agent.denies,)+ # Every granted hand obeys the agent's own approval rules and ceiling+ # (agent-definition §3.4): the gate rides on the executor's per-call+ # tier hook, so the chat card and the queue stay the one approval path.+ picked = {+ name: cast(Tool, _GatedTool(tool, agent, cap_id))+ for name, tool in picked.items()+ if (cap_id := capability_id_for_tool(name)) is not None+ }ordered: dict[str, Tool] = {}ordered.update(own)ordered.update(picked)diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsxindex 09dce25259..bc1a3c3b62 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx@@ -44,7 +44,7 @@ import { ProviderLogo } from "@/components/providers/ProviderLogo";import { useT } from "@/i18n";import { cn } from "@/lib/utils";import { createAgentChatStore, useAgentChatStore } from "@/store/agentChat";-import type { AgentChatSurface } from "@/lib/agentChatApi";+import type { AgentChatSurface, ApprovalDecision } from "@/lib/agentChatApi";import { AgentSwatch } from "../AgentSwatch";import { useResolveProposal, type SocietyAgent } from "../data";@@ -496,7 +496,7 @@ function Transcript({items: TimelineItem[];agent: SocietyAgent;busy: boolean;- onDecide: (approvalId: string, decision: "allow" | "deny") => Promise<void>;+ onDecide: (approvalId: string, decision: ApprovalDecision) => Promise<void>;}) {const t = useT();const bottom = useRef<HTMLDivElement>(null);@@ -732,7 +732,7 @@ function TurnBubble({onDecide,}: {item: TurnItem;- onDecide: (approvalId: string, decision: "allow" | "deny") => Promise<void>;+ onDecide: (approvalId: string, decision: ApprovalDecision) => Promise<void>;}) {const t = useT();const running = item.status === "running";@@ -929,7 +929,7 @@ function ToolLine({onDecide,}: {block: ToolBlock;- onDecide: (approvalId: string, decision: "allow" | "deny") => Promise<void>;+ onDecide: (approvalId: string, decision: ApprovalDecision) => Promise<void>;}) {const t = useT();const pending = block.approval && block.approval.decision === null;@@ -953,6 +953,14 @@ function ToolLine({>{t("society.chat.approve")}</button>+ <button+ type="button"+ onClick={() => void onDecide(block.approval!.approvalId, "allow_always")}+ title={t("society.chat.allow_always")}+ className="rounded-full border border-border px-2 py-0.5 text-foreground hover:bg-secondary"+ >+ {t("society.chat.allow_always")}+ </button><buttontype="button"onClick={() => void onDecide(block.approval!.approvalId, "deny")}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex e2d07d2e06..cbce47eb18 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -5113,7 +5113,8 @@"proposal_kind_routine": "Routine","proposal_kind_approval_rule": "Freigaberegeln","proposal_kind_focus": "Werkzeuge, die zuerst genutzt werden",- "proposal_kind_team": "Teammitglieder"+ "proposal_kind_team": "Teammitglieder",+ "allow_always": "Immer erlauben"},"world": {"minimap_label": "Inselkarte",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 7ff1754b28..aacbe984a4 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -5146,7 +5146,8 @@"proposal_kind_routine": "Routine","proposal_kind_approval_rule": "Approval rules","proposal_kind_focus": "Tools to reach for first",- "proposal_kind_team": "Teammates"+ "proposal_kind_team": "Teammates",+ "allow_always": "Always allow"},"world": {"minimap_label": "Island map",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 6c8c2e6fcc..c234a6df4a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -5113,7 +5113,8 @@"proposal_kind_routine": "Rutina","proposal_kind_approval_rule": "Reglas de aprobación","proposal_kind_focus": "Herramientas a usar primero",- "proposal_kind_team": "Compañeros de equipo"+ "proposal_kind_team": "Compañeros de equipo",+ "allow_always": "Permitir siempre"},"world": {"minimap_label": "Mapa de la isla",diff --git a/tests/unit/agent_chat/test_agent_chat_service.py b/tests/unit/agent_chat/test_agent_chat_service.pyindex f86316d2ac..eda5beb9e8 100644--- a/tests/unit/agent_chat/test_agent_chat_service.py+++ b/tests/unit/agent_chat/test_agent_chat_service.py@@ -547,3 +547,45 @@ def test_an_uncreatable_workspace_falls_back_instead_of_failing_the_chat(svc = AgentChatService(AgentChatStore(tmp_path / "db.sqlite"), default_cwd=lambda: str(home))assert svc.default_cwd("jarvis") == str(home)+++def test_allow_always_on_a_kit_that_handles_it_does_not_flip_the_mode(+ tmp_path: Path, scripted, monkeypatch: pytest.MonkeyPatch+):+ """A surface with its own memory for "always allow" (a society agent's+ approval rules) keeps the session's stance; the default surfaces still+ flip to auto (the test above)."""+ from dataclasses import replace++ from jarvis.agent_chat import service as service_mod++ remembered: list[tuple[str, str, dict[str, Any]]] = []++ async def hook(session: Any, name: str, args: dict[str, Any]) -> bool:+ remembered.append((session.session_id, name, dict(args)))+ return True++ real_kit_for = service_mod.kit_for+ monkeypatch.setattr(+ service_mod,+ "kit_for",+ lambda surface: replace(real_kit_for(surface), session_always_allow=hook),+ )+ ScriptedBrain.script = [+ [BrainDelta(tool_call={"id": "c1", "name": "RunCommand", "input": {"command": "echo x"}})],+ [BrainDelta(content="ok")],+ ]++ async def scenario() -> None:+ svc = AgentChatService(AgentChatStore(":memory:"))+ session = svc.create_session(provider="fakeprov", cwd=str(tmp_path))+ q = svc.subscribe(session.session_id)+ await svc.send(session.session_id, "run things")+ ev = (await _drain(q, "approval_required"))[-1]["payload"]+ svc.resolve_approval(session.session_id, ev["approval_id"], "allow_always")+ events = await _drain(q, "turn_finished")+ assert "session_updated" not in [e["kind"] for e in events]+ assert svc.store.get_session(session.session_id).permission_mode != "auto" # type: ignore[union-attr]+ assert remembered == [(session.session_id, "RunCommand", {"command": "echo x"})]++ asyncio.run(scenario())diff --git a/tests/unit/society/test_approvals.py b/tests/unit/society/test_approvals.pyindex 69f3fb67c6..d2a16a1d6f 100644--- a/tests/unit/society/test_approvals.py+++ b/tests/unit/society/test_approvals.py@@ -43,7 +43,8 @@ async def test_verdict_order(world):assert decide(agent, "plugin:gmail", "monitor", verb="read") is Verdict.RUNassert decide(agent, "plugin:gmail", "monitor", verb="send") is Verdict.QUEUEassert decide(agent, "cli:gh", "monitor") is Verdict.RUN- assert decide(agent, "cli:gh", "ask") is Verdict.QUEUE # always_allow never lifts ask+ assert decide(agent, "cli:gh", "ask") is Verdict.RUN # always_allow = a standing yes up to ask+ assert decide(agent, "cli:gh", "block") is Verdict.BLOCKassert decide(agent, "core:search-web", "safe") is Verdict.RUNassert decide(agent, "core:run-shell", "ask") is Verdict.QUEUEassert decide(agent, "plugin:spotify", "block") is Verdict.BLOCK@@ -107,3 +108,18 @@ async def test_expiry_parks_and_resurfaces(world):revived = await approvals.resurface()assert [a.state for a in revived] == [ApprovalState.PENDING]assert revived[0].expires_ms > item.expires_ms+++async def test_an_always_allow_pattern_runs_an_ask_tier_call(world):+ """The card's "Always allow" is the person's standing yes: it lifts an+ ask-tier call; a blocked class stays blocked."""+ _, roster, _ = world+ agent, _ = await roster.create(+ name="Mailbox",+ permission_ceiling="ask",+ approval_rules={"require_approval": [], "always_allow": ["plugin:gmail:send"]},+ )+ assert decide(agent, "plugin:gmail", "ask", verb="send") is Verdict.RUN+ assert decide(agent, "plugin:gmail", "monitor", verb="send") is Verdict.RUN+ assert decide(agent, "plugin:gmail", "block", verb="send") is Verdict.BLOCK+ assert decide(agent, "plugin:gmail", "ask", verb="read") is Verdict.QUEUEdiff --git a/tests/unit/society/test_surface.py b/tests/unit/society/test_surface.pyindex 5b6054102f..8a05641342 100644--- a/tests/unit/society/test_surface.py+++ b/tests/unit/society/test_surface.py@@ -158,3 +158,52 @@ async def test_capability_epoch_changes_when_hands_change(rt: SocietyRuntime):before = capability_epoch(rt.catalog())rt._get_tools = lambda: {**TOOLS, "spotify": _tool("spotify")} # noqa: SLF001 — test seamassert capability_epoch(rt.catalog()) != before+++async def test_a_granted_tool_is_gated_by_the_agents_rules(rt: SocietyRuntime, tmp_path: Path):+ """Every granted hand obeys the roster row's approval rules and ceiling+ through the executor's per-call tier hook (agent-definition §3.4)."""+ await rt.roster.create(+ name="Mailbox",+ title="Gmail agent",+ description="Handle my mail.",+ focus=["plugin:gmail"],+ permission_ceiling="monitor",+ approval_rules={"require_approval": ["plugin:gmail:send"], "always_allow": []},+ )+ cfg = SimpleNamespace(wiki=SimpleNamespace(vault_root=str(tmp_path / "vault")))+ session = SimpleNamespace(session_id="society:mailbox")+ await society_system_extra(cfg, None, session)+ filt = society_tool_filter(session)+ assert filt is not None+ picked = filt({**TOOLS, **society_tools(cfg, None, session)})+ gmail = picked["gmail"]+ assert gmail.name == "gmail" and gmail.schema == TOOLS["gmail"].schema+ assert gmail.risk_tier_for_args({"action": "list"}) in (None, "monitor")+ assert gmail.risk_tier_for_args({"action": "send"}) == "ask" # require_approval+ # Own hands are never wrapped: the society tools gate themselves.+ assert not hasattr(picked[SHELL_TOOL_NAME], "_capability_id")+ # An always-allow rule is the person's standing yes: an ask-tier call runs.+ await rt.roster.update(+ "mailbox",+ {"approval_rules": {"require_approval": [], "always_allow": ["plugin:gmail:send"]}},+ )+ await society_system_extra(cfg, None, session)+ gmail = society_tool_filter(session)({**TOOLS})["gmail"] # type: ignore[misc]+ gmail.risk_tier = "ask"+ assert gmail.risk_tier_for_args({"action": "send"}) == "monitor"+++async def test_always_allow_writes_the_agents_own_rule(rt: SocietyRuntime):+ from jarvis.society.surface import remember_always_allow++ await rt.roster.create(name="Mailbox", title="Gmail agent", focus=["plugin:gmail"])+ session = SimpleNamespace(session_id="society:mailbox")+ assert await remember_always_allow(session, "gmail", {"action": "send"}) is True+ agent = await rt.roster.get("mailbox")+ assert agent is not None and agent.approval_rules["always_allow"] == ["plugin:gmail:send"]+ # Idempotent, and a tool without a capability id (an own hand) is not remembered.+ assert await remember_always_allow(session, "gmail", {"action": "send"}) is True+ assert (await rt.roster.get("mailbox")).approval_rules["always_allow"] == ["plugin:gmail:send"]+ assert await remember_always_allow(session, "spawn-worker", {}) is False+ assert await remember_always_allow(SimpleNamespace(session_id="agent:x"), "gmail", {}) is False