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): per-agent approval modes and persistent group chats
rubenluetke10-beep62077fbe7eb0
diff --git a/docs/commands-reference.md b/docs/commands-reference.mdindex 560c4e0da7..4b839c7a2d 100644--- a/docs/commands-reference.md+++ b/docs/commands-reference.md@@ -13,10 +13,10 @@ Commands marked **requires confirmation** never run on a bare voice request —## `society-create-agent` — Create a persistent team agent-Create an agent in the user's existing Agents team, only when requested. This creates a roster profile and starts no work. Responsibilities derive capabilities through the same service as the Agents UI. When a team agent creates a teammate, the new agent inherits that creator's model seat (provider, model, effort, subscription account) and permission setup (ceiling, grant mode, grants, denies) and cannot exceed them. Read the returned agent and created flag: an existing name is adopted, never duplicated. Use society-switch-agent-model only if a different provider is requested. Design the agent before calling: turn the user's words into a complete brief — mission, 3-6 responsibilities, working rules naming the data sources, output format and boundaries — inferring sensible defaults instead of copying the request verbatim. Read readback.not_connected and tell the user which services to connect. A requested schedule is a separate society-create-routine call.+Create an agent in the user's existing Agents team, only when requested. This creates a roster profile and starts no work. Responsibilities derive capabilities through the same service as the Agents UI. When a team agent creates a teammate, the new agent inherits that creator's model seat (provider, model, effort, subscription account) and permission setup (approval mode, ceiling, grant mode, grants, denies) and cannot exceed them. Read the returned agent and created flag: an existing name is adopted, never duplicated. Use society-switch-agent-model only if a different provider is requested. Design the agent before calling: turn the user's words into a complete brief — mission, 3-6 responsibilities, working rules naming the data sources, output format and boundaries — inferring sensible defaults instead of copying the request verbatim. Read readback.not_connected and tell the user which services to connect. A requested schedule is a separate society-create-routine call.- **Endpoint:** `POST /api/society/agents`-- **Arguments:** `name` (string; required); `title` (string; optional); `description` (string; optional); `mission` (string; optional); `responsibilities` (array; optional); `working_rules` (array; optional); `output_format` (string; optional); `boundaries` (array; optional); `success_criteria` (string; optional); `tier` (one of: specialist, orchestrator; optional); `focus` (array; optional); `skills` (array; optional); `daily_budget_usd` (number; optional); `max_concurrent_runs` (integer; optional); `permission_ceiling` (one of: safe, monitor, ask; optional); `grant_mode` (one of: all, allowlist; optional); `grants` (array; optional); `denies` (array; optional)+- **Arguments:** `name` (string; required); `title` (string; optional); `description` (string; optional); `mission` (string; optional); `responsibilities` (array; optional); `working_rules` (array; optional); `output_format` (string; optional); `boundaries` (array; optional); `success_criteria` (string; optional); `tier` (one of: specialist, orchestrator; optional); `focus` (array; optional); `skills` (array; optional); `approval_mode` (one of: bypass, ask, always_ask; optional); `daily_budget_usd` (number; optional); `max_concurrent_runs` (integer; optional); `permission_ceiling` (one of: safe, monitor, ask; optional); `grant_mode` (one of: all, allowlist; optional); `grants` (array; optional); `denies` (array; optional)- **Requires confirmation:** no- **Desktop UI section:** `agents`- **Voice example (EN):** "create an agent for researching suppliers"@@ -26,7 +26,7 @@ Create an agent in the user's existing Agents team, only when requested. This crChange an existing agent's responsibilities, skills, focus, budget or paused/active state as requested by the user. Resolve its real id with society_status first. Only send requested fields. Existing learned focus and approval rules survive prose edits. Report the returned stored agent.- **Endpoint:** `PATCH /api/society/agents/{agent_id}`-- **Arguments:** `agent_id` (string; required); `title` (string; optional); `description` (string; optional); `mission` (string; optional); `responsibilities` (array; optional); `working_rules` (array; optional); `output_format` (string; optional); `boundaries` (array; optional); `success_criteria` (string; optional); `tier` (one of: specialist, orchestrator; optional); `focus` (array; optional); `skills` (array; optional); `daily_budget_usd` (number; optional); `max_concurrent_runs` (integer; optional); `permission_ceiling` (one of: safe, monitor, ask; optional); `grant_mode` (one of: all, allowlist; optional); `grants` (array; optional); `denies` (array; optional); `state` (one of: active, paused; optional)+- **Arguments:** `agent_id` (string; required); `title` (string; optional); `description` (string; optional); `mission` (string; optional); `responsibilities` (array; optional); `working_rules` (array; optional); `output_format` (string; optional); `boundaries` (array; optional); `success_criteria` (string; optional); `tier` (one of: specialist, orchestrator; optional); `focus` (array; optional); `skills` (array; optional); `approval_mode` (one of: bypass, ask, always_ask; optional); `daily_budget_usd` (number; optional); `max_concurrent_runs` (integer; optional); `permission_ceiling` (one of: safe, monitor, ask; optional); `grant_mode` (one of: all, allowlist; optional); `grants` (array; optional); `denies` (array; optional); `state` (one of: active, paused; optional)- **Requires confirmation:** no- **Desktop UI section:** `agents`- **Voice example (EN):** "update Scout's responsibilities"diff --git a/jarvis/agent_chat/approval_bridge.py b/jarvis/agent_chat/approval_bridge.pyindex 0a602cc79d..a4376f778d 100644--- a/jarvis/agent_chat/approval_bridge.py+++ b/jarvis/agent_chat/approval_bridge.py@@ -90,6 +90,8 @@ class ChatGrant:#: 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)+ #: Society's explicit require-approval rules override Bypass.+ force_ask: Callable[[str, dict[str, Any]], bool] = field(default=lambda _name, _args: False)class ChatApprovalBridge:@@ -138,8 +140,10 @@ class ChatApprovalBridge:grant = self._grants.get(ref) if ref else Noneif grant is None:return- decision = self._decide_inline(grant, event.tool_name)+ args = self._args.get(event.trace_id) or {}+ decision = self._decide_inline(grant, event.tool_name, args)if decision is not None:+ self._args.pop(event.trace_id, None)await self._bus.publish(ActionApproved(trace_id=event.trace_id,@@ -160,10 +164,16 @@ class ChatApprovalBridge:# ------------------------------------------------------------ policy@staticmethod- def _decide_inline(grant: ChatGrant, tool_name: str) -> str | None:+ def _decide_inline(+ grant: ChatGrant, tool_name: str, args: dict[str, Any] | None = None+ ) -> str | None:"""The ``approved_by`` label when the stance decides without a card, else None."""name = _bare(tool_name)+ if grant.stance == "always_ask":+ return Noneif grant.stance == "bypass":+ if grant.force_ask(name, args or {}):+ return Nonereturn "chat-bypass"if name in grant.always_allowed:return "user"diff --git a/jarvis/agent_chat/control.py b/jarvis/agent_chat/control.pyindex 1b11fe5219..fb5b7282ff 100644--- a/jarvis/agent_chat/control.py+++ b/jarvis/agent_chat/control.py@@ -345,7 +345,13 @@ class ChatControls:ladder = ladder_key(session.surface, resolve_runner(session.provider, surface=session.surface))- permission = normalize_permission(ladder, permission)+ # /plan is a chat control, not a ladder choice: the Society ladder+ # (bypass / ask / always ask) has no read-only rung, and folding+ # "plan" onto it would silently leave the turn able to write.+ folded = normalize_permission(ladder, permission)+ if permission in ("plan", "read-only") and folded not in ("plan", "read-only"):+ folded = "plan"+ permission = foldedself.service.store.update_session(sid, permission_mode=permission)state.mode = "plan" if permission in ("plan", "read-only") else "build"set_chat_read_only(sid, state.mode == "plan")diff --git a/jarvis/agent_chat/jarvis_harness.py b/jarvis/agent_chat/jarvis_harness.pyindex 730df35231..ffe328e1fc 100644--- a/jarvis/agent_chat/jarvis_harness.py+++ b/jarvis/agent_chat/jarvis_harness.py@@ -199,16 +199,14 @@ def codex_config_args(session_id: str | None = None) -> list[str]:f'mcp_servers.{_SERVER_NAME}.tools.society_browser.approval_mode="approve"',]if session_id.startswith("society:"):- # A society seat cannot carry out its role without its owned- # tools. Surface startup failures instead of a tools-free chat- # that can only promise to configure the running app.- # This local configuration tool already verifies the current- # user request and routes permission changes to Jarvis' own- # approval card. A second Codex write prompt cannot be answered- # by `exec` and would reject even explicit routine requests.+ # Codex exec has no interactive approval channel. Every tool on+ # this server delegates to Jarvis' session catalog and+ # ToolExecutor, which owns the actual policy and chat card.+ # Leaving even one tool at Codex's prompt default causes an+ # unanswerable "approval policy is never" failure.args += ["-c",- f'mcp_servers.{_SERVER_NAME}.tools.society_propose_change.approval_mode="approve"',+ f'mcp_servers.{_SERVER_NAME}.default_tools_approval_mode="approve"',]return argsexcept Exception: # noqa: BLE001 — see mcp_config_json@@ -529,9 +527,7 @@ def society_memory_refresh(text: str, *, compact: bool = False) -> str:return ("<current_agent_memory>\n""Current standing instructions, memory and learned skill index replace their previous "- "snapshots when complete. "- + note- + "Learned guidance never grants "+ "snapshots when complete. " + note + "Learned guidance never grants ""permissions or overrides the standing instructions or the current user request.\n\n"+ body+ "\n</current_agent_memory>\n\n"diff --git a/jarvis/agent_chat/permissions.py b/jarvis/agent_chat/permissions.pyindex ca7d0a58bc..dd6a432a46 100644--- a/jarvis/agent_chat/permissions.py+++ b/jarvis/agent_chat/permissions.py@@ -283,6 +283,25 @@ _JARVIS: Final[tuple[PermissionMode, ...]] = (),)+_SOCIETY: Final[tuple[PermissionMode, ...]] = (+ PermissionMode(+ "bypass",+ "Bypass permissions",+ "Run Jarvis tools without prompts. Jarvis blocks, denied capabilities and "+ "credential boundaries still apply; vendor-native CLI tools use that runner's controls.",+ ),+ PermissionMode(+ "ask",+ "Ask",+ "Read freely; show a decision in this chat before an action or write.",+ ),+ PermissionMode(+ "always_ask",+ "Always ask",+ "Show a decision in this chat before every Jarvis tool call, including reads.",+ ),+)+#: The ladder key of the Jarvis surface — not a runner, but the one word the#: front page's composer shows whichever runner answers.JARVIS_LADDER: Final[str] = "jarvis"@@ -302,6 +321,7 @@ _LADDERS: Final[dict[str, tuple[tuple[PermissionMode, ...], str]]] = {"cursor-cli": (_CURSOR, "auto"),"api": (_API, "ask"),JARVIS_LADDER: (_JARVIS, "ask"),+ "society": (_SOCIETY, "bypass"),}# The universal stance ordering: every ladder is a sub-sequence of this once@@ -323,6 +343,7 @@ _STANCE: Final[dict[str, int]] = {"bypassPermissions": 3,"skip-permissions": 3,"bypass": 3,+ "always_ask": 1,}@@ -367,6 +388,17 @@ def is_permission_mode(runner: str, mode: str) -> bool:return mode in permission_ids(runner)+def society_mode_supported(runner: str, mode: str) -> bool:+ """Whether this transport can honor a Society mode without hidden prompts."""+ if mode == "bypass":+ return True+ if mode == "ask":+ return runner in {"brain", "codex-cli", "claude-cli", "glm-cli"}+ if mode == "always_ask":+ return runner in {"brain", "codex-cli"}+ return False++def normalize_permission(runner: str, mode: str | None) -> str:"""Fold ``mode`` onto the closest mode ``runner`` accepts.@@ -407,5 +439,6 @@ __all__ = ["normalize_permission","permission_ids","permission_modes",+ "society_mode_supported","stance_of",]diff --git a/jarvis/agent_chat/runner_brain.py b/jarvis/agent_chat/runner_brain.pyindex dc82490546..d5b9712fae 100644--- a/jarvis/agent_chat/runner_brain.py+++ b/jarvis/agent_chat/runner_brain.py@@ -475,6 +475,8 @@ async def run_brain_turn(_note_skill_trigger(brain, text)if bridge is not None:+ from jarvis.society.surface import requires_explicit_approval+bridge.arm(ref,ChatGrant(@@ -484,6 +486,11 @@ async def run_brain_turn(always_allowed=always_allowed,ask=handle.request_approval,call_id_for=mirror.open_call_id,+ force_ask=(+ lambda name, args: requires_explicit_approval(session.session_id, name, args)+ )+ if session.surface == "society"+ else lambda _name, _args: False,),)diff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.pyindex ae8493af52..2e9cf3a284 100644--- a/jarvis/agent_chat/runner_cli.py+++ b/jarvis/agent_chat/runner_cli.py@@ -964,7 +964,24 @@ def plan_codex(# stdin; the sandbox decides what may happen. Plan is the read-only# sandbox plus an instruction to plan instead of act. The sandbox goes# through ``-c sandbox_mode`` because ``exec resume`` has no ``-s``.- if mode == "full-access":+ society_seat = identity is not None and identity.session_id.startswith("society:")+ if society_seat:+ # The headless CLI cannot relay native approval prompts into Jarvis.+ # Give it only the app-owned MCP hands; all actions then pass through+ # the session grant, ToolExecutor and the visible chat approval card.+ argv += ["-c", 'sandbox_mode="read-only"', "-c", 'approval_policy="never"']+ for feature in (+ "shell_tool",+ "apps",+ "hooks",+ "multi_agent",+ "browser_use",+ "computer_use",+ "plugins",+ "web_search_request",+ ):+ argv += ["--disable", feature]+ elif mode == "full-access":argv += ["--dangerously-bypass-approvals-and-sandbox"]elif mode == "approve-for-me":argv += [@@ -1642,6 +1659,7 @@ class _CodexState:started_at: dict[str, float] = field(default_factory=dict)#: The last top-level ``error`` notification (retryable until turn.failed).last_error: str | None = None+ failed_tools: set[str] = field(default_factory=set)def translate_codex_line(obj: dict[str, Any], st: _CodexState) -> list[dict[str, Any]]:@@ -1773,10 +1791,18 @@ def translate_codex_line(obj: dict[str, Any], st: _CodexState) -> list[dict[str,)is_error = str(item.get("status") or "") == "failed"elif itype == "mcp_tool_call":- output = json.dumps(- item.get("result") or item.get("error") or {}, ensure_ascii=False+ result = item.get("result")+ output = json.dumps(result or item.get("error") or {}, ensure_ascii=False)+ is_error = (+ bool(item.get("error"))+ or str(item.get("status") or "") == "failed"+ or (isinstance(result, dict) and bool(result.get("isError"))))- is_error = bool(item.get("error"))+ if is_error:+ st.failed_tools.add(name)+ st.last_error = f"{name} failed: {output[:300]}"+ else:+ st.failed_tools.discard(name)else:output = "done"is_error = False@@ -2648,6 +2674,7 @@ async def run_cli_turn()if bridge is not None:from jarvis.agent_chat.approval_bridge import ChatGrant+ from jarvis.society.surface import requires_explicit_approvalbridge.arm(ref,@@ -2657,6 +2684,13 @@ async def run_cli_turn(stance=handle.stance or "ask",always_allowed=always_allowed if always_allowed is not None else set(),ask=handle.request_approval,+ force_ask=(+ lambda name, args: requires_explicit_approval(+ session.session_id, name, args+ )+ )+ if session.surface == "society"+ else lambda _name, _args: False,),)tool_context = register_turn(session.session_id) if identity else None@@ -3099,6 +3133,9 @@ async def _run_cli_once(or "\n".join(stderr_tail[-8:]).strip()or f"{runner} exited with code {proc.returncode}.")+ elif plan.shape == "codex" and state.failed_tools:+ status = "error"+ error_text = "Unresolved tool failure: " + ", ".join(sorted(state.failed_tools))usage = dict(state.usage)cost_usd = getattr(state, "cost_usd", None)diff --git a/jarvis/agent_chat/surface_kits.py b/jarvis/agent_chat/surface_kits.pyindex b6fb1b8dd2..5fcacc6edf 100644--- a/jarvis/agent_chat/surface_kits.py+++ b/jarvis/agent_chat/surface_kits.py@@ -32,6 +32,7 @@ __all__ = [#: The ladder key of the Jarvis ladder (``permissions.JARVIS_LADDER``) —#: spelled here so the kit table does not import the permissions module._JARVIS_LADDER: Final[str] = "jarvis"+_SOCIETY_LADDER: Final[str] = "society"ToolsBuilder = Callable[[Any, Any], dict[str, Tool]]ExtraBuilder = Callable[[Any, Any], Awaitable[str]]@@ -264,7 +265,7 @@ _KITS: Final[dict[str, SurfaceKit]] = {# with Jarvis' tools over MCP and its own hands; on an API row Jarvis'# brain runner drives the agent's own tool set.cli_seats=True,- ladder=_JARVIS_LADDER,+ ladder=_SOCIETY_LADDER,uses_stance=True,tool_origin="society",session_tools=_society_tools,diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.pyindex 2756b0ec63..4e5acc7c77 100644--- a/jarvis/commands/registry.py+++ b/jarvis/commands/registry.py@@ -176,6 +176,10 @@ def _society_profile_properties() -> dict[str, Any]:"type": "array", "items": {"type": "string"},"description": "Skill ids explicitly requested by the user.",},+ "approval_mode": _str_param(+ "Agent approval mode. Omit to inherit the creator or use Bypass permissions.",+ enum=["bypass", "ask", "always_ask"],+ ),"daily_budget_usd": {"type": "number", "minimum": 0,"description": "Daily spending limit requested by the user.",@@ -269,7 +273,8 @@ def _build_registry() -> tuple[AppCommand, ...]:"capabilities through the same service as the Agents UI. When a team agent ""creates a teammate, the new agent inherits that creator's model seat ""(provider, model, effort, subscription account) and permission setup "- "(ceiling, grant mode, grants, denies) and cannot exceed them. Read the "+ "(approval mode, ceiling, grant mode, grants, denies) and cannot exceed "+ "them. Read the ""returned agent and created flag: an existing name is adopted, never ""duplicated. Use society-switch-agent-model only if a different provider ""is requested. " + _AGENT_DESIGN_GUIDEdiff --git a/jarvis/mcp/jarvis_tools_server.py b/jarvis/mcp/jarvis_tools_server.pyindex 75dfce2cb1..bbfef8fb32 100644--- a/jarvis/mcp/jarvis_tools_server.py+++ b/jarvis/mcp/jarvis_tools_server.py@@ -223,27 +223,24 @@ def build_server() -> Any:async def _call_tool(name: str, arguments: dict[str, Any] | None) -> Any:from jarvis.core.protocols import SupervisorToolRequest, current_chat_turn+ def failed(message: str) -> Any:+ return types.CallToolResult(+ content=[types.TextContent(type="text", text=message)], isError=True+ )+gateway = _gateway()if gateway is None:- return [types.TextContent(type="text", text="Jarvis is still starting up.")]+ return failed("Jarvis is still starting up.")if name in _WITHHELD:- return [- types.TextContent(- type="text",- text=(- f"{name} is not available from the chat — you ARE the worker. "- "Do the work yourself."- ),- )- ]+ return failed(+ f"{name} is not available from the chat — you ARE the worker. Do the work yourself."+ )try:from jarvis.agent_chat.tool_context import restore_turnentry = (await _session_wire_catalog()).get(name)if entry is None:- return [- types.TextContent(type="text", text="Tool is no longer available in this chat.")- ]+ return failed("Tool is no longer available in this chat.")name = str(entry.name)with restore_turn(CHAT_SESSION_REF.get()):turn = current_chat_turn.get()@@ -251,9 +248,9 @@ def build_server() -> Any:task_scope = scope_for(CHAT_SESSION_REF.get())if (CHAT_SESSION_REF.get() or "").startswith("task-") and task_scope is None:- return [types.TextContent(type="text", text="The task grant has expired.")]+ return failed("The task grant has expired.")if task_scope is not None and name not in task_scope.names:- return [types.TextContent(type="text", text="Tool outside the task grant.")]+ return failed("Tool outside the task grant.")trace_id = task_scope.trace_id if task_scope else uuid4()if name == "society_browser" and turn is not None and task_scope is None:try:@@ -271,9 +268,7 @@ def build_server() -> Any:result = await gateway.execute(name, dict(arguments or {}), request)except Exception as exc: # noqa: BLE001 — a tool failure is data for the model, not a crashlog.warning("jarvis MCP: %s raised", name, exc_info=True)- return [- types.TextContent(type="text", text=f"Tool failed: {type(exc).__name__}: {exc}")- ]+ return failed(f"Tool failed: {type(exc).__name__}: {exc}")if name == "society_browser":success = bool(getattr(result, "success", False))text = _render(result)@@ -294,7 +289,10 @@ def build_server() -> Any:return types.CallToolResult(content=[types.TextContent(type="text", text=text)], isError=not success)- return [types.TextContent(type="text", text=_render(result))]+ return types.CallToolResult(+ content=[types.TextContent(type="text", text=_render(result))],+ isError=not bool(getattr(result, "success", False)),+ )return serverdiff --git a/jarvis/society/approvals.py b/jarvis/society/approvals.pyindex 3455bbfd12..2a7d4a62e9 100644--- a/jarvis/society/approvals.py+++ b/jarvis/society/approvals.py@@ -9,9 +9,9 @@ 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 ``ask`` — the person's standing yes), then the tool's risk-tier against the ceiling.+patterns (queue), its explicit approval mode, then the legacy+``always_allow`` patterns and risk ceiling. Bypass still blocks actions above+an inherited ceiling; Always ask queues even safe reads.Patterns are capability ids (``plugin:gmail``), ``capability:verb``(``plugin:gmail:send``) or ``capability:*``."""@@ -67,11 +67,21 @@ def decide(agent: AgentRecord, capability_id: str, tool_tier: str, *, verb: strrules = agent.approval_rulesif any(matches(p, capability_id, verb) for p in rules.get("require_approval", [])):return Verdict.QUEUE+ mode = str(agent.approval_mode) if agent.approval_mode is not None else ""+ if mode == "always_ask":+ return Verdict.QUEUEif any(matches(p, capability_id, verb) for p in rules.get("always_allow", [])):- # 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.+ # The person's explicit standing yes can authorize this action up to+ # the ask tier. Always ask above intentionally ignores standing yes.return Verdict.RUN if _TIER_RANK.get(tool_tier, 1) <= 2 else Verdict.QUEUE+ if mode == "bypass":+ # Bypass removes prompts, not an inherited risk ceiling. An action+ # above that ceiling is denied instead of being silently escalated.+ if _TIER_RANK.get(tool_tier, 1) > _TIER_RANK[str(agent.permission_ceiling)]:+ return Verdict.BLOCK+ return Verdict.RUN+ if mode == "ask":+ return Verdict.RUN if tool_tier == "safe" 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/chat_binding.py b/jarvis/society/chat_binding.pyindex 15cfaa7089..a883f157e4 100644--- a/jarvis/society/chat_binding.py+++ b/jarvis/society/chat_binding.py@@ -41,9 +41,8 @@ __all__ = [SURFACE: Final[str] = "society"-#: Permission ceiling → the Jarvis-ladder stance the session runs in-#: (``jarvis/agent_chat/permissions.py``): safe reads only, monitor may edit-#: and runs commands after asking, ask asks for everything mutating.+#: Legacy permission ceiling → the pre-migration Jarvis stance. Explicit+#: approval modes instead come from the roster's own persisted choice._CEILING_TO_MODE: Final[dict[str, str]] = {str(PermissionCeiling.SAFE): "plan",str(PermissionCeiling.MONITOR): "accept-edits",@@ -80,15 +79,30 @@ def _workspace(cfg: Any, agent: AgentRecord) -> str:def ensure_session(svc: Any, cfg: Any, agent: AgentRecord) -> Any:"""The agent's canonical session, created or re-seated to the roster row."""from jarvis.agent_chat.effort import default_effort- from jarvis.agent_chat.permissions import ladder_key, normalize_permission+ from jarvis.agent_chat.permissions import (+ ladder_key,+ normalize_permission,+ society_mode_supported,+ )from jarvis.agent_chat.service import resolve_runnerprovider, model, effort = pair_for(cfg, agent)+ runner = resolve_runner(provider, surface=SURFACE)+ if agent.approval_mode is not None and not society_mode_supported(+ runner, str(agent.approval_mode)+ ):+ raise PermissionError(+ f"{runner} cannot provide an actionable approval for {agent.approval_mode}"+ )session_id = agent.session_idexisting = svc.store.get_session(session_id)if existing is None:- ladder = ladder_key(SURFACE, resolve_runner(provider, surface=SURFACE))- mode = normalize_permission(ladder, _CEILING_TO_MODE[str(agent.permission_ceiling)])+ ladder = ladder_key(SURFACE, runner)+ if agent.approval_mode is None:+ # A pre-migration row keeps the old Jarvis ladder, including Plan.+ mode = normalize_permission("jarvis", _CEILING_TO_MODE[str(agent.permission_ceiling)])+ else:+ mode = normalize_permission(ladder, str(agent.approval_mode))return svc.store.create_session(provider=provider,model=model,@@ -104,6 +118,8 @@ def ensure_session(svc: Any, cfg: Any, agent: AgentRecord) -> Any:svc.store.reseat_session(session_id, provider=provider, model=model or existing.model)existing = svc.store.get_session(session_id)updates: dict[str, str] = {}+ if agent.approval_mode is not None and existing.permission_mode != str(agent.approval_mode):+ updates["permission_mode"] = str(agent.approval_mode)if getattr(existing, "account_id", "") != agent.account_id:updates["account_id"] = agent.account_idif effort and existing.effort != effort:diff --git a/jarvis/society/events.py b/jarvis/society/events.pyindex a1d9da0b24..69d095f764 100644--- a/jarvis/society/events.py+++ b/jarvis/society/events.py@@ -21,6 +21,7 @@ from pydantic import BaseModel, ConfigDict, Fieldfrom jarvis.missions.ids import uuid7_str__all__ = [+ "AgentApprovalMode","AgentState","ApprovalState","BrowserMode",@@ -119,6 +120,14 @@ class PermissionCeiling(StrEnum):ASK = "ask"+class AgentApprovalMode(StrEnum):+ """Per-agent approval behavior; capability denies and global blocks still apply."""++ BYPASS = "bypass"+ ASK = "ask"+ ALWAYS_ASK = "always_ask"++class BrowserMode(StrEnum):"""``own`` = the agent's persistent Chromium profile; ``attach`` = theperson's running Chrome over CDP."""diff --git a/jarvis/society/inherit.py b/jarvis/society/inherit.pyindex 602b1153f3..f5146a702d 100644--- a/jarvis/society/inherit.py+++ b/jarvis/society/inherit.py@@ -3,13 +3,14 @@When a society agent creates a teammate — typed chat or a subscription CLIcalling ``society-create-agent`` — the new row starts on the creator's modelseat (provider, model, effort, subscription account) and may not exceed the-creator's permission ceiling, grant mode, grants or denies. The Agents UI+creator's explicit approval mode, permission ceiling, grant mode, grants or denies. The Agents UIsends those fields itself, so an explicit choice still wins, and a blankcreate from the UI (no society session) keeps the usual defaults."""from __future__ import annotations+import loggingfrom typing import Anyfrom .events import GrantMode, PermissionCeiling@@ -22,6 +23,8 @@ __all__ = ["session_agent_id",]+log = logging.getLogger(__name__)+_CEILING_RANK: dict[str, int] = {str(PermissionCeiling.SAFE): 0,str(PermissionCeiling.MONITOR): 1,@@ -52,7 +55,7 @@ def caller_session_id() -> str | None:if stamped:return str(stamped)except Exception: # noqa: BLE001 — optional; a missing MCP server is not a create failure- pass+ log.debug("Society caller has no MCP session context", exc_info=True)try:from jarvis.core.chat_turn import current_chat_turn@@ -60,7 +63,7 @@ def caller_session_id() -> str | None:if turn is not None and turn.session_id:return str(turn.session_id)except Exception: # noqa: BLE001 — optional; a missing turn is not a create failure- pass+ log.debug("Society caller has no chat turn context", exc_info=True)return None@@ -105,6 +108,18 @@ def inherit_creator_fields(fields: dict[str, Any], creator: AgentRecord) -> dictelse creator_ceiling)+ # A child may ask more often, but cannot silently bypass a parent's+ # explicit Ask setting. Legacy parents made no approval-mode choice, so+ # their children use the new Bypass default under the inherited ceiling.+ creator_approval = str(creator.approval_mode or "bypass")+ requested_approval = str(fields.get("approval_mode") or creator_approval)+ approval_rank = {"always_ask": 0, "ask": 1, "bypass": 2}+ if requested_approval not in approval_rank:+ requested_approval = creator_approval+ fields["approval_mode"] = min(+ (creator_approval, requested_approval), key=lambda mode: approval_rank[mode]+ )+creator_mode = str(creator.grant_mode)requested_mode = str(fields.get("grant_mode") or "").strip()if creator_mode == str(GrantMode.ALLOWLIST):diff --git a/jarvis/society/roster.py b/jarvis/society/roster.pyindex 657824dd0c..d29638d14e 100644--- a/jarvis/society/roster.py+++ b/jarvis/society/roster.py@@ -24,6 +24,7 @@ from pydantic import ValidationErrorfrom .companion import validate_avatar_companionfrom .events import (+ AgentApprovalMode,AgentState,BrowserMode,Checkpoint,@@ -119,6 +120,8 @@ class AgentRecord:created_ms: intupdated_ms: intstats: dict[str, Any] = field(default_factory=dict)+ # NULL on pre-migration rows: their existing chat mode remains authoritative.+ approval_mode: AgentApprovalMode | None = None#: Where the agent's work executes: ``None`` = this computer, else the id#: of a connected machine (``jarvis.computers``) reached over SSH.computer_id: str | None = None@@ -155,6 +158,7 @@ class AgentRecord:"wiki_namespace": self.wiki_namespace,"knowledge_scope": str(self.knowledge_scope),"permission_ceiling": str(self.permission_ceiling),+ "approval_mode": str(self.approval_mode) if self.approval_mode else None,"approval_rules": {"require_approval": list(self.approval_rules.get("require_approval", [])),"always_allow": list(self.approval_rules.get("always_allow", [])),@@ -200,6 +204,9 @@ class AgentRecord:wiki_namespace=str(row.get("wiki_namespace") or ""),knowledge_scope=KnowledgeScope(str(row.get("knowledge_scope") or "shared")),permission_ceiling=PermissionCeiling(str(row.get("permission_ceiling") or "monitor")),+ approval_mode=(+ AgentApprovalMode(str(row["approval_mode"])) if row.get("approval_mode") else None+ ),approval_rules={"require_approval": [str(x) for x in rules.get("require_approval", [])],"always_allow": [str(x) for x in rules.get("always_allow", [])],@@ -210,8 +217,8 @@ class AgentRecord:browser_allowed_domains=[str(x) for x in _loads(row.get("browser_allowed_domains_json"), [])],- created_ms=int(row.get("created_ms") or 0),computer_id=str(row["computer_id"]) if row.get("computer_id") else None,+ created_ms=int(row.get("created_ms") or 0),updated_ms=int(row.get("updated_ms") or 0),)@@ -239,6 +246,7 @@ _EDITABLE: Final[frozenset[str]] = frozenset("wiki_namespace","knowledge_scope","permission_ceiling",+ "approval_mode","approval_rules","daily_budget_usd","max_concurrent_runs",@@ -329,6 +337,8 @@ def _coerce(field_name: str, value: Any) -> Any:return _enum(KnowledgeScope, value, field_name)if field_name == "permission_ceiling":return _enum(PermissionCeiling, value, field_name)+ if field_name == "approval_mode":+ return _enum(AgentApprovalMode, value, field_name)if field_name == "browser_mode":return _enum(BrowserMode, value, field_name)if field_name == "browser_allowed_domains":@@ -445,13 +455,18 @@ class Roster:return await self._hydrate(existing), Falsetier_value = Tier(_enum(Tier, tier, "tier"))agent_id = slugify(clean_name)+ if tier_value is Tier.LEAD and agent_id != LEAD_AGENT_ID:+ raise RosterError(+ FailureReason.TIER_NOT_ALLOWED, "exactly one lead exists and it is Jarvis"+ )if tier_value is Tier.LEAD and fields.get("computer_id"):raise RosterError(FailureReason.TIER_NOT_ALLOWED, "the lead always runs on this computer")- if tier_value is Tier.LEAD and agent_id != LEAD_AGENT_ID:+ if tier_value is Tier.LEAD and "approval_mode" in fields:raise RosterError(- FailureReason.TIER_NOT_ALLOWED, "exactly one lead exists and it is Jarvis"+ FailureReason.BLOCKED_BY_POLICY,+ "the Jarvis lead uses the app chat permission policy",)same_slug = await self._store.get_agent_row(agent_id)if same_slug is not None:@@ -471,6 +486,12 @@ class Roster:"updated_ms": now,"workspace_dir": f"society/{agent_id}/workspace","wiki_namespace": f"society/{agent_id}/",+ "approval_mode": (None if tier_value is Tier.LEAD else str(AgentApprovalMode.BYPASS)),+ "permission_ceiling": (+ str(PermissionCeiling.MONITOR)+ if tier_value is Tier.LEAD+ else str(PermissionCeiling.ASK)+ ),}if tier_value is Tier.ORCHESTRATOR:row["max_concurrent_runs"] = 3@@ -522,6 +543,11 @@ class Roster:raise RosterError(FailureReason.BLOCKED_BY_POLICY, f"field {key!r} is not editable")if key == "tier" and agent_id == LEAD_AGENT_ID and str(value) != str(Tier.LEAD):raise RosterError(FailureReason.TIER_NOT_ALLOWED, "Jarvis stays the lead")+ if key == "approval_mode" and agent_id == LEAD_AGENT_ID:+ raise RosterError(+ FailureReason.BLOCKED_BY_POLICY,+ "the Jarvis lead uses the app chat permission policy",+ )if key == "computer_id" and agent_id == LEAD_AGENT_ID and value:raise RosterError(FailureReason.TIER_NOT_ALLOWED, "the lead always runs on this computer"diff --git a/jarvis/society/society_schema.sql b/jarvis/society/society_schema.sqlindex 90e5b9db7e..9f4d5e1af6 100644--- a/jarvis/society/society_schema.sql+++ b/jarvis/society/society_schema.sql@@ -38,6 +38,8 @@ CREATE TABLE IF NOT EXISTS society_agents (CHECK (knowledge_scope IN ('shared', 'own')),permission_ceiling TEXT NOT NULL DEFAULT 'monitor'CHECK (permission_ceiling IN ('safe', 'monitor', 'ask')),+ approval_mode TEXT DEFAULT NULL+ CHECK (approval_mode IN ('bypass', 'ask', 'always_ask')),approval_rules_json TEXT NOT NULL DEFAULT '{}',daily_budget_usd REAL NOT NULL DEFAULT 2.0,browser_mode TEXT NOT NULL DEFAULT 'own'diff --git a/jarvis/society/store.py b/jarvis/society/store.pyindex 2e52844fc1..49ec42e64e 100644--- a/jarvis/society/store.py+++ b/jarvis/society/store.py@@ -135,6 +135,13 @@ class SocietyStore:"TEXT NOT NULL DEFAULT '[]'")log.info("society store: migration applied — added browser_allowed_domains")+ if "approval_mode" not in existing:+ # NULL preserves legacy sessions until the person chooses a mode.+ await self.conn.execute(+ "ALTER TABLE society_agents ADD COLUMN approval_mode TEXT DEFAULT NULL "+ "CHECK (approval_mode IN ('bypass', 'ask', 'always_ask'))"+ )+ log.info("society store: migration applied — added approval_mode")if "computer_id" not in existing:# NULL = this computer; every existing agent keeps running here.await self.conn.execute(diff --git a/jarvis/society/surface.py b/jarvis/society/surface.pyindex 924d1d0252..9160df1127 100644--- a/jarvis/society/surface.py+++ b/jarvis/society/surface.py@@ -68,8 +68,14 @@ _OWN_PREFIX: Final[str] = "society_"#: through its own contained shell (never the free-cwd shell tools)._SOCIETY_DENIED: Final[frozenset[str]] = frozenset({- "wiki-ingest", "run-shell", "run_shell", "RunCommand",- "remember", "update_profile", "profile-update", "update-profile",+ "wiki-ingest",+ "run-shell",+ "run_shell",+ "RunCommand",+ "remember",+ "update_profile",+ "profile-update",+ "update-profile",})@@ -528,12 +534,9 @@ def society_tool_filter(session: Any) -> Callable[[dict[str, Tool]], dict[str, Treturn Noneagent = rt.cached_agent(agent_id)if agent is None:- # The briefing fills the cache before the override is built; a miss- # means a turn without a briefing — keep the own hands, deny the rest- # of the write paths the agent must not have.- return lambda tools: {- n: t for n, t in tools.items() if n.startswith(_OWN_PREFIX) or n not in _SOCIETY_DENIED- }+ # The briefing fills the cache before the override is built. A miss+ # cannot establish the agent's mode or grants, so offer no hands.+ return lambda _tools: {}def _apply(tools: dict[str, Tool]) -> dict[str, Tool]:own = {@@ -549,22 +552,59 @@ 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.+ # Every granted hand obeys the agent's own approval rules and mode.+ # 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)+ if agent.approval_mode is not None:+ ordered.update(+ {+ name: cast(+ Tool,+ _GatedTool(tool, agent, capability_id_for_tool(name) or "core:society"),+ )+ for name, tool in own.items()+ # Asking the user IS the person's decision; gating it+ # behind an approval card would ask twice.+ if name != ASK_USER_TOOL_NAME+ }+ )+ if ASK_USER_TOOL_NAME in own:+ ordered[ASK_USER_TOOL_NAME] = own[ASK_USER_TOOL_NAME]+ else:+ ordered.update(own)ordered.update(picked)return orderedreturn _apply+def requires_explicit_approval(session_id: str, tool_name: str, args: dict[str, Any]) -> bool:+ """Keep an agent's explicit ask rules effective even in Bypass mode."""+ from .approvals import matches++ rt = current_runtime()+ agent_id = agent_id_of(session_id)+ if rt is None or agent_id is None:+ return True+ agent = rt.cached_agent(agent_id)+ if agent is None:+ return True+ bare = tool_name.split("__", 2)[-1] if tool_name.startswith("mcp__") else tool_name+ capability = capability_id_for_tool(bare)+ if capability is None:+ return True+ return any(+ matches(pattern, capability, _verb_of(args))+ for pattern in agent.approval_rules.get("require_approval", [])+ )++async def society_system_extra(cfg: Any, brain: Any, session: Any) -> str:rt = current_runtime()agent_id = agent_id_of(getattr(session, "session_id", "") or "")diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentLimits.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentLimits.test.tsxindex 20216b16f4..847f22ceac 100644--- a/jarvis/ui/web/frontend/src/components/society/card/AgentLimits.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentLimits.test.tsx@@ -103,6 +103,20 @@ describe("the card's limits", () => {});});+ test("saves an explicit approval mode while preserving the ceiling", async () => {+ renderCard({ approvalMode: "bypass" });+ fireEvent.click(await screen.findByTestId("agent-limits-edit"));+ fireEvent.click(screen.getByText("Always ask"));+ fireEvent.click(screen.getByText("Save"));++ await waitFor(() => {+ const patch = fetchMock.mock.calls.find((call) => call[1]?.method === "PATCH");+ const body = JSON.parse(String(patch?.[1]?.body));+ expect(body.approval_mode).toBe("always_ask");+ expect(body.permission_ceiling).toBe("monitor");+ });+ });+test("an empty budget means no cap rather than a broken number", async () => {renderCard();fireEvent.click(await screen.findByTestId("agent-limits-edit"));diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsxindex fc32fb5689..9ba0786a69 100644--- a/jarvis/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx@@ -31,6 +31,7 @@* Every string goes through the locale files.*/import { useMemo, useState } from "react";+import { useQuery } from "@tanstack/react-query";import { MessageSquare, Pause, Play, Server } from "lucide-react";import { ProviderLogo } from "@/components/providers/ProviderLogo";@@ -46,7 +47,7 @@ import { AgentRoutinesList } from "./AgentRoutinesList";import { RetireButton } from "./RetireButton";import { CapabilityChip } from "../CapabilityChip";import { useAgentActivity, useAgentSkills, type AgentActivity } from "../cardData";-import { PERMISSION_CEILINGS } from "@/lib/societyApi";+import { AGENT_APPROVAL_MODES, PERMISSION_CEILINGS, fetchSocietyProviders, type AgentApprovalMode } from "@/lib/societyApi";import {useSetAgentComputer,@@ -526,6 +527,9 @@ function LimitsSection({const [saving, setSaving] = useState(false);const [error, setError] = useState("");const [ceiling, setCeiling] = useState<PermissionCeiling>(agent.permissionCeiling);+ const [approvalMode, setApprovalMode] = useState<AgentApprovalMode | null>(agent.approvalMode ?? null);+ const providerRows = useQuery({ queryKey: ["society", "providers"], queryFn: fetchSocietyProviders });+ const runner = providerRows.data?.find((row) => row.id === agent.provider)?.runner;const [budget, setBudget] = useState(String(agent.dailyBudgetUsd));// The stored 0 IS 'no cap' (the scheduler skips the gate), so the switch// reads it back rather than asking the person to know that.@@ -534,6 +538,7 @@ function LimitsSection({const begin = () => {setCeiling(agent.permissionCeiling);+ setApprovalMode(agent.approvalMode ?? null);setBudget(String(agent.dailyBudgetUsd || 2));setBudgetOn(agent.dailyBudgetUsd > 0);setJobs(String(agent.maxConcurrentRuns));@@ -546,6 +551,7 @@ function LimitsSection({try {await update(agent, {permissionCeiling: ceiling,+ approvalMode,dailyBudgetUsd: budgetOn ? Math.max(0, Number.parseFloat(budget) || 0) : 0,maxConcurrentRuns: Number.parseInt(jobs, 10) || 1,});@@ -575,8 +581,37 @@ function LimitsSection({{editing ? (<div className="ac-prose flex flex-col gap-3">- <div className="flex flex-col gap-1">- <span className="text-xs text-muted-foreground">{t("society.card.permission")}</span>+ {agent.tier !== "lead" && <div className="flex flex-col gap-1">+ <span className="text-xs text-muted-foreground">{t("society.approval_mode.title")}</span>+ <div className="flex flex-wrap gap-1">+ {AGENT_APPROVAL_MODES.map((mode) => {+ const unknownRunner = Boolean(agent.provider) && runner == null;+ const unavailable = mode === "always_ask"+ ? unknownRunner || (runner != null && runner !== "codex-cli" && runner !== "brain")+ : mode === "ask" && (unknownRunner || (runner != null+ && !["codex-cli", "claude-cli", "glm-cli", "brain"].includes(runner)));+ return <button+ key={mode}+ type="button"+ disabled={saving || unavailable}+ title={unavailable ? t("society.approval_mode.unavailable") : t(`society.approval_mode.${mode}_hint`)}+ onClick={() => setApprovalMode(mode)}+ aria-pressed={approvalMode === mode}+ className={cn(+ "rounded-md border px-2.5 py-1 text-xs transition-colors disabled:opacity-50",+ approvalMode === mode+ ? "border-border-strong bg-secondary text-foreground"+ : "border-border text-muted-foreground hover:bg-secondary",+ )}+ >{t(`society.approval_mode.${mode}`)}</button>;+ })}+ </div>+ <p className="text-xs text-muted-foreground">+ {approvalMode ? t(`society.approval_mode.${approvalMode}_hint`) : t("society.approval_mode.legacy_hint")}+ </p>+ </div>}+ {(agent.tier === "lead" || !agent.approvalMode) && <div className="flex flex-col gap-1">+ <span className="text-xs text-muted-foreground">{t("society.approval_mode.legacy_ceiling")}</span><div className="flex flex-wrap gap-1">{PERMISSION_CEILINGS.map((step) => (<button@@ -596,7 +631,7 @@ function LimitsSection({</button>))}</div>- </div>+ </div>}<div className="flex flex-wrap items-end gap-4"><div className="flex flex-col gap-1">@@ -666,12 +701,18 @@ function LimitsSection({</div>) : (<>- <StepMeter- label={t("society.card.permission")}- steps={3}- filled={CEILING_STEP[agent.permissionCeiling] ?? 0}- value={t(`society.ceiling.${agent.permissionCeiling}`)}- />+ {agent.tier !== "lead" && agent.approvalMode ? (+ <div className="text-xs text-muted-foreground">+ {t("society.approval_mode.title")}: <span className="text-foreground">{t(`society.approval_mode.${agent.approvalMode}`)}</span>+ </div>+ ) : (+ <StepMeter+ label={t("society.approval_mode.legacy_ceiling")}+ steps={3}+ filled={CEILING_STEP[agent.permissionCeiling] ?? 0}+ value={t(`society.ceiling.${agent.permissionCeiling}`)}+ />+ )}<StepMeterlabel={t("society.card.meter_reach")}steps={REACH_STEPS}diff --git a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsxindex eb1f1cc121..83110ee5ce 100644--- a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx+++ b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx@@ -46,7 +46,7 @@ import {type AgentConnectionRow,type CuratedModel,} from "@/lib/agentChatApi";-import { fetchSocietyProviders, type SocietyProviderRow } from "@/lib/societyApi";+import { AGENT_APPROVAL_MODES, fetchSocietyProviders, type AgentApprovalMode, type SocietyProviderRow } from "@/lib/societyApi";import { cn } from "@/lib/utils";import { joinProviderOptions } from "@/store/agentChat";@@ -60,7 +60,7 @@ import {type BrainSeat,} from "./brainPicker";import { modelSeats } from "../chat/modelChoices";-import { useCreateAgent, type PermissionCeiling } from "../data";+import { useCreateAgent } from "../data";import { CompanionEditor } from "../companion/CompanionEditor";import { resolveCompanion } from "../companion/appearance";import { AgentFigureViewer } from "../figures/AgentFigureViewer";@@ -85,8 +85,6 @@ import {} from "../figures/figureRegistry";import type { FigureArchetype } from "../figures/figureRecipe";-const CEILINGS: readonly PermissionCeiling[] = ["safe", "monitor", "ask"];-/*** How tall a figure may be made, per archetype. One 1.5–2.1 m band fits a* person and nothing else: a fox at 1.75 m is a horse, and Gigi's own scale@@ -131,7 +129,7 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialoconst [accountId, setAccountId] = useState("");// "" = this computer; otherwise a connected computer (VPS / local VM) id.const [computerId, setComputerId] = useState("");- const [ceiling, setCeiling] = useState<PermissionCeiling>("monitor");+ const [approvalMode, setApprovalMode] = useState<AgentApprovalMode>("bypass");const [budget, setBudget] = useState("2");// A cap is the default because an agent that can spend without one is the// surprising case, not the ordinary one. Off sends 0, which is exactly what@@ -226,6 +224,7 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialosetModel(next ? next.provider.default_model || modelsFor(next)[0]?.id || "" : "");setEffort(next?.provider.default_effort ?? "");setAccountId("");+ setApprovalMode("bypass");};// A fresh dialog starts on the brain marked active, else the first seat —@@ -252,6 +251,7 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialosetModel("");setEffort("");setAccountId("");+ setApprovalMode("bypass");setImportProblems(null);setImportedName(null);setError(null);@@ -381,7 +381,8 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialograntMode: "all",toolGrants: [],focus: [],- permissionCeiling: ceiling,+ permissionCeiling: "ask",+ approvalMode,dailyBudgetUsd: budgetOn ? Math.max(0, Number.parseFloat(budget) || 0) : 0,});onCreated(agent.agentId);@@ -587,7 +588,9 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialotype="button"className="flex w-full items-center justify-between rounded-md border border-border px-3 py-2 text-sm font-medium text-foreground hover:bg-secondary">- {t("society.create.advanced")}+ <span>+ {t("society.create.advanced")} · {t(`society.approval_mode.${approvalMode}`)}+ </span><ChevronDownclassName={cn("h-4 w-4 transition-transform", advanced && "rotate-180")}aria-hidden@@ -596,12 +599,23 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialo</Collapsible.Trigger><Collapsible.Content className="flex flex-col gap-4 pt-4"><div>- <span className={labelClass}>{t("society.create.ceiling")}</span>+ <span className={labelClass}>{t("society.approval_mode.title")}</span><Segmented- value={ceiling}- options={CEILINGS.map((c) => ({ value: c, label: t(`society.ceiling.${c}`) }))}- onChange={(v) => setCeiling(v as PermissionCeiling)}+ value={approvalMode}+ options={AGENT_APPROVAL_MODES.map((mode) => ({+ value: mode,+ label: t(`society.approval_mode.${mode}`),+ disabled: mode === "always_ask"+ ? seat?.kind === "subscription" && seat.provider.runner !== "codex-cli"+ : mode === "ask" && seat?.kind === "subscription"+ && !["codex-cli", "claude-cli", "glm-cli"].includes(seat.provider.runner),+ hint: t(`society.approval_mode.${mode}_hint`),+ }))}+ onChange={(v) => setApprovalMode(v as AgentApprovalMode)}/>+ <p className="mt-1 text-xs text-muted-foreground">+ {t(`society.approval_mode.${approvalMode}_hint`)}+ </p></div><div><div className="mb-2 flex items-center gap-2">diff --git a/jarvis/ui/web/frontend/src/components/society/data.ts b/jarvis/ui/web/frontend/src/components/society/data.tsindex 072352d7cd..ff7e2cd5ff 100644--- a/jarvis/ui/web/frontend/src/components/society/data.ts+++ b/jarvis/ui/web/frontend/src/components/society/data.ts@@ -16,7 +16,7 @@ import { useCallback, useEffect } from "react";import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";import type { MentionPlugin } from "./chat/mentionItems";-import type { Checkpoint, SocietyAgentRow } from "@/lib/societyApi";+import type { AgentApprovalMode, Checkpoint, SocietyAgentRow } from "@/lib/societyApi";import { NEUTRAL_ASSISTANT_NAME } from "@/lib/assistantNameCache";import { useEventStore } from "@/store/events";@@ -43,6 +43,7 @@ export type AgentRunState = "idle" | "working" | "waiting" | "paused";/** §6.2 — the unattended ceiling; "block" never appears (block is block). */export type PermissionCeiling = "safe" | "monitor" | "ask";+export type { AgentApprovalMode };/** agent-definition.md §3.2 — everything the tiers allow, or only an allow-list. */export type GrantMode = "all" | "allowlist";@@ -116,6 +117,7 @@ export interface SocietyAgent {denies: string[];approvalRules: ApprovalRules;permissionCeiling: PermissionCeiling;+ approvalMode?: AgentApprovalMode | null;dailyBudgetUsd: number;checkpoint: AgentCheckpoint;state: AgentRunState;@@ -154,6 +156,7 @@ export interface NewAgentInput {toolGrants: string[];focus: string[];permissionCeiling: PermissionCeiling;+ approvalMode: AgentApprovalMode;dailyBudgetUsd: number;}@@ -239,6 +242,7 @@ export function rowToAgent(row: SocietyAgentRow): SocietyAgent {alwaysAllow: row.approval_rules?.always_allow ?? [],},permissionCeiling: row.permission_ceiling as PermissionCeiling,+ approvalMode: row.approval_mode ?? null,dailyBudgetUsd: row.daily_budget_usd,checkpoint: row.checkpoint as AgentCheckpoint,state: runState,@@ -417,6 +421,7 @@ export function useCreateAgent() {grants: input.grantMode === "allowlist" ? input.toolGrants : undefined,focus: input.focus.length ? input.focus : undefined,permission_ceiling: input.permissionCeiling,+ approval_mode: input.approvalMode,daily_budget_usd: input.dailyBudgetUsd,};try {@@ -464,6 +469,7 @@ export function useCreateAgent() {denies: [],approvalRules: { requireApproval: [], alwaysAllow: [] },permissionCeiling: input.permissionCeiling,+ approvalMode: input.approvalMode,dailyBudgetUsd: input.dailyBudgetUsd,checkpoint: "idle",state: "idle",@@ -559,6 +565,7 @@ export interface AgentLimits {/** 0 means no cap — the scheduler skips the budget gate entirely. */dailyBudgetUsd: number;permissionCeiling: PermissionCeiling;+ approvalMode?: AgentApprovalMode | null;maxConcurrentRuns: number;}@@ -583,6 +590,7 @@ export function useUpdateAgentLimits() {const body = {daily_budget_usd: Math.max(0, limits.dailyBudgetUsd),permission_ceiling: limits.permissionCeiling,+ ...(limits.approvalMode ? { approval_mode: limits.approvalMode } : {}),max_concurrent_runs: Math.max(1, Math.round(limits.maxConcurrentRuns)),};if (!sample) {@@ -595,6 +603,7 @@ export function useUpdateAgentLimits() {} else {agent.dailyBudgetUsd = body.daily_budget_usd;agent.permissionCeiling = body.permission_ceiling;+ if (limits.approvalMode) agent.approvalMode = limits.approvalMode;agent.maxConcurrentRuns = body.max_concurrent_runs;}await client.invalidateQueries({ queryKey: ROSTER_QUERY_KEY });diff --git a/jarvis/ui/web/frontend/src/components/society/roster/GroupRosterActions.tsx b/jarvis/ui/web/frontend/src/components/society/roster/GroupRosterActions.tsxnew file mode 100644index 0000000000..cb0f8aba5f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/roster/GroupRosterActions.tsx@@ -0,0 +1,108 @@+import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";+import { createPortal } from "react-dom";+import * as Dialog from "@radix-ui/react-dialog";+import { useQueryClient } from "@tanstack/react-query";+import { Pencil, Trash2 } from "lucide-react";++import { Button } from "@/components/ui/button";+import { useT } from "@/i18n";+import { deleteSocietyChatGroup, type SocietyChatGroup } from "@/lib/societyChatGroups";++interface Props {+ group: SocietyChatGroup;+ x: number;+ y: number;+ onEdit: () => void;+ onDismiss: () => void;+}++export function GroupRosterActions({ group, x, y, onEdit, onDismiss }: Props) {+ const t = useT();+ const client = useQueryClient();+ const menuRef = useRef<HTMLDivElement>(null);+ const [confirmUngroup, setConfirmUngroup] = useState(false);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState("");++ useEffect(() => {+ if (confirmUngroup) return;+ const onPointerDown = (event: PointerEvent) => {+ if (!menuRef.current?.contains(event.target as Node)) onDismiss();+ };+ const onKeyDown = (event: globalThis.KeyboardEvent) => {+ if (event.key === "Escape") onDismiss();+ };+ document.addEventListener("pointerdown", onPointerDown, true);+ document.addEventListener("keydown", onKeyDown, true);+ document.addEventListener("scroll", onDismiss, true);+ window.addEventListener("resize", onDismiss);+ return () => {+ document.removeEventListener("pointerdown", onPointerDown, true);+ document.removeEventListener("keydown", onKeyDown, true);+ document.removeEventListener("scroll", onDismiss, true);+ window.removeEventListener("resize", onDismiss);+ };+ }, [confirmUngroup, onDismiss]);++ useLayoutEffect(() => {+ const menu = menuRef.current;+ if (!menu || confirmUngroup) return;+ const { width, height } = menu.getBoundingClientRect();+ menu.style.left = `${Math.max(8, Math.min(x, window.innerWidth - width - 8))}px`;+ menu.style.top = `${Math.max(8, Math.min(y, window.innerHeight - height - 8))}px`;+ menu.style.visibility = "visible";+ menu.querySelector<HTMLButtonElement>("button")?.focus();+ }, [confirmUngroup, x, y]);++ const onMenuKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {+ if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;+ event.preventDefault();+ const items = Array.from(menuRef.current?.querySelectorAll<HTMLButtonElement>("button") ?? []);+ const index = items.indexOf(document.activeElement as HTMLButtonElement);+ items[(index + (event.key === "ArrowDown" ? 1 : -1) + items.length) % items.length]?.focus();+ };++ const remove = async () => {+ if (busy) return;+ setBusy(true);+ setError("");+ try {+ await deleteSocietyChatGroup(group.group_id);+ await client.invalidateQueries({ queryKey: ["society", "chat-groups"] });+ onDismiss();+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ } finally {+ setBusy(false);+ }+ };++ return createPortal(<>+ {!confirmUngroup && <div ref={menuRef} role="menu" aria-label={group.name} onKeyDown={onMenuKeyDown}+ style={{ width: 240, visibility: "hidden" }}+ className="fixed z-[100] overflow-hidden rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-float">+ <button type="button" role="menuitem" onClick={() => { onEdit(); onDismiss(); }}+ className="flex w-full items-center gap-2 rounded px-3 py-2 text-left text-sm hover:bg-secondary focus:bg-secondary focus:outline-none">+ <Pencil className="h-4 w-4" aria-hidden />{t("society.groups.edit")}+ </button>+ <button type="button" role="menuitem" onClick={() => setConfirmUngroup(true)}+ className="flex w-full items-center gap-2 rounded px-3 py-2 text-left text-sm text-destructive hover:bg-destructive/10 focus:bg-destructive/10 focus:outline-none">+ <Trash2 className="h-4 w-4" aria-hidden />{t("society.groups.delete")}+ </button>+ </div>}+ <Dialog.Root open={confirmUngroup} onOpenChange={(open) => { if (!open && !busy) onDismiss(); }}>+ <Dialog.Portal>+ <Dialog.Overlay className="fixed inset-0 z-[101] bg-scrim/60" />+ <Dialog.Content className="fixed left-1/2 top-1/2 z-[102] w-[min(400px,calc(100vw-24px))] -translate-x-1/2 -translate-y-1/2 rounded-xl border border-border bg-popover p-5 text-popover-foreground shadow-float outline-none">+ <Dialog.Title className="text-base font-semibold">{t("society.groups.delete")}</Dialog.Title>+ <Dialog.Description className="mt-2 text-sm text-muted-foreground">{t("society.groups.delete_confirm")}</Dialog.Description>+ {error && <p role="alert" className="mt-2 text-sm text-destructive">{error}</p>}+ <div className="mt-5 flex justify-end gap-2">+ <Button variant="ghost" disabled={busy} onClick={onDismiss}>{t("society.groups.cancel")}</Button>+ <Button variant="destructive" disabled={busy} onClick={() => void remove()}>{t("society.groups.delete")}</Button>+ </div>+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog.Root>+ </>, document.body);+}diff --git a/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.test.tsx b/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.test.tsxindex 9fa6a23c71..38081b72b6 100644--- a/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.test.tsx@@ -69,6 +69,31 @@ describe("RosterRail status", () => {fireEvent.click(screen.getByTestId("society-group-team"));expect(openGroup).toHaveBeenCalledWith("team");});+ it("opens team actions on right-click and only ungroups after confirmation", async () => {+ const request = vi.fn(async () => ({ ok: true, json: async () => ({}) }));+ vi.stubGlobal("fetch", request);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ render(<QueryClientProvider client={client}><RosterRail {...baseProps} activeAgentId={null}+ agents={[agent({ agentId: "scout", name: "Scout" }), agent({ agentId: "writer", name: "Writer" })]}+ groups={[{ group_id: "team", name: "Launch team", members: ["scout", "writer"], created_ms: 1, updated_ms: 1 }]}+ onOpenGroup={() => undefined} /></QueryClientProvider>);++ const row = screen.getByTestId("society-group-team");+ fireEvent.contextMenu(row, { clientX: 32, clientY: 56 });+ expect(screen.getByRole("menu", { name: "Launch team" })).toBeTruthy();+ expect(screen.getByRole("menuitem", { name: "society.groups.edit" })).toBeTruthy();+ fireEvent.click(screen.getByRole("menuitem", { name: "society.groups.delete" }));+ expect(screen.getByRole("dialog", { name: "society.groups.delete" })).toBeTruthy();+ expect(request).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "society.groups.cancel" }));+ expect(request).not.toHaveBeenCalled();++ fireEvent.contextMenu(row, { clientX: 32, clientY: 56 });+ fireEvent.click(screen.getByRole("menuitem", { name: "society.groups.delete" }));+ fireEvent.click(screen.getByRole("button", { name: "society.groups.delete" }));+ await waitFor(() => expect(request).toHaveBeenCalledWith("/api/society/chat-groups/team", { method: "DELETE" }));+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ });it("shows a loading spinner while an agent is thinking", () => {render(<RosterRaildiff --git a/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.tsx b/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.tsxindex 3321427ae3..cfa4bee0c4 100644--- a/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.tsx+++ b/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.tsx@@ -35,6 +35,7 @@ import type { SocietyChatGroup } from "@/lib/societyChatGroups";import { AgentSwatch } from "../AgentSwatch";import type { AgentRunState, SocietyAgent } from "../data";import { AgentRosterActions } from "./AgentRosterActions";+import { GroupRosterActions } from "./GroupRosterActions";import { useRosterUnread } from "./useRosterUnread";import { ChatGroupDialog } from "../chat/ChatGroupDialog";@@ -131,8 +132,12 @@ export function RosterRail({const [groupReady, setGroupReady] = useState(false);const [showHidden, setShowHidden] = useState(false);const [menu, setMenu] = useState<{ agentId: string; x: number; y: number } | null>(null);+ const [groupMenu, setGroupMenu] = useState<{ groupId: string; x: number; y: number } | null>(null);+ const [editingGroupId, setEditingGroupId] = useState<string | null>(null);const profile = agents.find((agent) => agent.agentId === profileId);const menuAgent = agents.find((agent) => agent.agentId === menu?.agentId);+ const menuGroup = groups.find((group) => group.group_id === groupMenu?.groupId);+ const editingGroup = groups.find((group) => group.group_id === editingGroupId);const unread = useRosterUnread(agents, activeAgentId);const assistantName = useEventStore((state) => state.assistantName);@@ -147,8 +152,15 @@ export function RosterRail({const openMenu = (event: MouseEvent, agentId: string) => {event.preventDefault();event.stopPropagation();+ setGroupMenu(null);setMenu({ agentId, x: event.clientX, y: event.clientY });};+ const openGroupMenu = (event: MouseEvent, groupId: string) => {+ event.preventDefault();+ event.stopPropagation();+ setMenu(null);+ setGroupMenu({ groupId, x: event.clientX, y: event.clientY });+ };const lead = useMemo(() => agents.find((a) => a.tier === "lead") ?? null, [agents]);const groupedIds = useMemo(() => new Set(groups.flatMap((group) => group.members)), [groups]);@@ -562,7 +574,7 @@ export function RosterRail({) : null}{visibleGroups.length > 0 && <ul className="flex flex-col gap-0.5 px-2 pb-2">{visibleGroups.map((group) => <li key={group.group_id}>- <button type="button" data-group-id={group.group_id} onClick={() => onOpenGroup?.(group.group_id)} aria-current={activeGroupId === group.group_id ? "true" : undefined}+ <button type="button" data-group-id={group.group_id} onClick={() => onOpenGroup?.(group.group_id)} onContextMenu={(event) => openGroupMenu(event, group.group_id)} aria-current={activeGroupId === group.group_id ? "true" : undefined}className={cn("flex w-full items-center gap-2.5 rounded-md px-2 py-2 text-left hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", activeGroupId === group.group_id && "bg-secondary", groupHover?.kind === "group" && groupHover.id === group.group_id && (groupReady ? "ring-2 ring-primary" : "ring-1 ring-border-strong"))}data-testid={`society-group-${group.group_id}`}><span className="flex w-12 shrink-0 items-center justify-center">@@ -646,8 +658,11 @@ export function RosterRail({{footer}{menu && menuAgent && <AgentRosterActions key={menu.agentId} agent={menuAgent} roster={agents} sample={sample}hidden={hiddenIds.includes(menu.agentId)} x={menu.x} y={menu.y} onVisibilityChange={setHidden} onDismiss={closeMenu} />}+ {groupMenu && menuGroup && <GroupRosterActions key={groupMenu.groupId} group={menuGroup} x={groupMenu.x} y={groupMenu.y}+ onEdit={() => setEditingGroupId(menuGroup.group_id)} onDismiss={() => setGroupMenu(null)} />}{profile && <Suspense fallback={null}><AgentProfileDialog key={profile.agentId} agent={profile} sample={sample} onClose={() => setProfileId(null)} /></Suspense>}{creatingGroup && <ChatGroupDialog agents={agents} onClose={() => setCreatingGroup(false)} onSaved={(id) => onOpenGroup?.(id)} />}+ {editingGroup && <ChatGroupDialog group={editingGroup} agents={agents} onClose={() => setEditingGroupId(null)} onSaved={(id) => onOpenGroup?.(id)} />}</aside>);}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex ff71286180..b65edf0e47 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -538,11 +538,9 @@"recent": "Letzte","pin_chat": "Chat anheften","unpin_chat": "Chat lösen",-"jarvis_tools": "Jarvis Tools","scheduled": "Geplant","more": "Mehr",-"instance_dev_hint": "Dev-Instanz — eine zweite, frei neustartbare Kopie der App mit eigenen Daten, Ports und eigenem Icon. Die normale App läuft daneben weiter.","surface_voice": "Voice","surface_chat": "Chat",@@ -1915,7 +1913,11 @@"managed_speaking_title": "Sprechen","managed_voice_unavailable": "noch nicht sprachgetestet","managed_voice_install_required": "Laufzeit-Installation nötig",- "managed_apply_test": "Anwenden & Sprache testen",+ "managed_apply_test": "Anwenden, testen & lokal sprechen",+ "managed_protocol_options": "Erweiterte Modell- und Stimmoptionen des Servers",+ "managed_setup_testing": "Die ausgewählten Modelle werden vorbereitet und die Sprachausgabe geprüft. Beim ersten Start kann das länger dauern.",+ "managed_selected": "Für Sprache ausgewählt. Diese Modelle starten automatisch mit Jarvis.",+ "managed_not_selected": "Dieser Server ist noch nicht für Sprache ausgewählt. Zwei Modelle auswählen und anwenden, um lokal zu sprechen.","managed_full_catalog": "Vollständigen Ollama-Katalog durchsuchen","managed_voice_catalog_title": "Open-Source-Sprachmodelle durchsuchen","managed_voice_catalog_search": "Nach Modell, Backend, Sprache oder Lizenz suchen…",@@ -2017,7 +2019,7 @@"cat_computer_use_desc": "Das Tool Model führt deine Aktionen aus: Es routet Sprachbefehle, plant Computer-Use auf deinem Bildschirm, startet Hintergrund-Agenten und steuert die App — unabhängig von deinem Chat-Brain.","cat_dictation_desc": "Das schnelle Modell, das diktierten Text aufräumt — Satzzeichen, Füllwörter und Satzgrenzen. Optional: Ohne Schlüssel hier kommt dein Diktat genau so an, wie es erkannt wurde.","cat_subagents_title": "{name}-Agents",- "cat_subagents_desc": "Dieser Provider übernimmt Textchat, Gedächtnis und Hintergrundaufgaben. Ein Abo kostet hier nichts extra; dein Voice-Key bleibt für das Sprachgespräch reserviert.",+ "cat_subagents_desc": "Übernimmt Chat, Gedächtnis und Hintergrundarbeit — nicht dein Voice-Key.","advanced_title": "Zugang & Integrationen","advanced_desc": "Optionale Extras: der Team-Key-Proxy, Telefonie und der Wissens-Wiki-Provider.","no_providers_in_tier": "In dieser Kategorie sind keine Provider verfügbar.",@@ -2051,7 +2053,7 @@"realtime_options_error": "Die Sprachoptionen konnten nicht geladen werden.","realtime_options_retry": "Erneut versuchen","realtime_model_managed": "Verwaltet",- "realtime_model_managed_hint": "ChatGPT wählt das Subscription-Modell. Bei einem API-Realtime-Anbieter kannst du ein GPT-Realtime-Modell festlegen.",+ "realtime_model_managed_hint": "Dieser Anbieter verwaltet das Modell. Die Auswahl lässt sich über die Einrichtung oben ändern.","guide_realtime_title": "Welches Modell soll ich nehmen?","guide_realtime_body": "OpenAI API: GPT Realtime 2.1 ist das aktuelle Flaggschiff, 2.1 Mini die günstigere Wahl. Google: Gemini 3.1 Flash Live ist das aktuelle Live-Flaggschiff.","guide_computer_use_title": "Welcher Provider soll das Tool Model antreiben?",@@ -2994,10 +2996,10 @@"summary_accepted": "Bedingungen akzeptiert"},"intro": {- "scene_1": "Dein sprachgesteuerter Assistent.",- "scene_2": "Einfach sprechen — er hört zu und handelt.",- "scene_3": "Er arbeitet im Hintergrund weiter, während du es nicht tust.",- "scene_4": "Deine Schlüssel, deine Daten, deine Regeln."+ "scene_1": "Dein Computer wird zum KI-Agenten.",+ "scene_2": "Gib Jarvis eine Aufgabe per Chat oder Sprache.",+ "scene_3": "Er kann Apps, Tools, Modelle und Agenten nutzen.",+ "scene_4": "Prüfe seine Aktionen und Ergebnisse an einem Ort."},"language": {"ui_label": "Sprache der Oberfläche",@@ -5161,9 +5163,22 @@},"society": {"groups": {- "create": "Neues Agent-Team", "edit": "Agent-Team bearbeiten", "description": "Agents in einem Eintrag bündeln. Jeder Agent behält seinen eigenen Chat.",- "name": "Teamname", "members": "Mitglieder", "cancel": "Abbrechen", "save": "Team speichern", "delete": "Gruppe auflösen", "delete_confirm": "Diese Gruppe auflösen? Die einzelnen Agent-Chats bleiben erhalten.",- "left_chat": "Linker Chat", "right_chat": "Rechter Chat", "open": "Öffnen", "open_individual": "Einzelchat von {0} öffnen", "missing_member": "Wähle einen verfügbaren Agent für diesen Chat.", "hold_to_group": "Halten zum Gruppieren", "release_to_group": "Loslassen zum Gruppieren"+ "create": "Neues Agent-Team",+ "edit": "Agent-Team bearbeiten",+ "description": "Agents in einem Eintrag bündeln. Jeder Agent behält seinen eigenen Chat.",+ "name": "Teamname",+ "members": "Mitglieder",+ "cancel": "Abbrechen",+ "save": "Team speichern",+ "delete": "Gruppe auflösen",+ "delete_confirm": "Diese Gruppe auflösen? Die einzelnen Agent-Chats bleiben erhalten.",+ "left_chat": "Linker Chat",+ "right_chat": "Rechter Chat",+ "open": "Öffnen",+ "open_individual": "Einzelchat von {0} öffnen",+ "missing_member": "Wähle einen verfügbaren Agent für diesen Chat.",+ "hold_to_group": "Halten zum Gruppieren",+ "release_to_group": "Loslassen zum Gruppieren"},"chat": {"placeholder": "Nachricht an {0}",@@ -5372,6 +5387,18 @@"monitor": "Beobachten","ask": "Erst fragen"},+ "approval_mode": {+ "title": "Agentenberechtigungen",+ "bypass": "Berechtigungen umgehen",+ "ask": "Fragen",+ "always_ask": "Immer fragen",+ "bypass_hint": "Jarvis-Werkzeuge laufen ohne Nachfragen; Sperren und verweigerte Werkzeuge gelten weiter. Eigene Werkzeuge einer Abo-CLI folgen deren Regeln.",+ "ask_hint": "Lesen ohne Nachfrage; vor Änderungen und anderen Aktionen hier im Chat fragen.",+ "always_ask_hint": "Vor jedem Jarvis-Werkzeugaufruf hier im Chat fragen, auch beim Lesen.",+ "legacy_hint": "Dieser Agent behält seine bisherigen Chat-Berechtigungen, bis du einen Modus auswählst.",+ "legacy_ceiling": "Bisherige Berechtigungsgrenze",+ "unavailable": "Dieser Runner kann für diesen Modus keine nutzbare Freigabekarte anzeigen."+ },"grant": {"all": "Alle verbundenen Werkzeuge","allowlist": "Nur Erlaubnisliste"diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex b5348d5cf7..ed8dcdc758 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -538,11 +538,9 @@"recent": "Recent","pin_chat": "Pin chat","unpin_chat": "Unpin chat",-"jarvis_tools": "Jarvis Tools","scheduled": "Scheduled","more": "More",-"instance_dev_hint": "Dev instance — a second, freely restartable copy of the app with its own data, ports and icon. The regular app keeps running beside it.","surface_voice": "Voice","surface_chat": "Chat",@@ -1948,7 +1946,11 @@"managed_speaking_title": "Speak","managed_voice_unavailable": "not voice-tested yet","managed_voice_install_required": "runtime install required",- "managed_apply_test": "Apply & voice-test",+ "managed_apply_test": "Apply, test & use local voice",+ "managed_protocol_options": "Advanced server model and voice options",+ "managed_setup_testing": "Preparing the selected models and testing speech. This can take longer on the first start.",+ "managed_selected": "Selected for voice. These models start automatically with Jarvis.",+ "managed_not_selected": "This server is not selected for voice yet. Choose two models and apply them to use local voice.","managed_full_catalog": "Browse the full Ollama catalog","managed_voice_catalog_title": "Browse open-source speech models","managed_voice_catalog_search": "Search by model, backend, language, or license…",@@ -2050,7 +2052,7 @@"cat_computer_use_desc": "The Tool Model runs your actions: it routes spoken commands, plans Computer-Use on your screen, starts background agents, and drives app controls — independent of your chat Brain.","cat_dictation_desc": "The fast model that tidies up dictated text — punctuation, filler words and sentence breaks. Optional: with no key here your dictation is delivered exactly as it was recognized.","cat_subagents_title": "{name}-Agents",- "cat_subagents_desc": "This provider runs text chat, memory and background tasks. A subscription here costs nothing extra; your voice key stays reserved for the voice call.",+ "cat_subagents_desc": "Runs chat, memory and background tasks — not your voice key.","advanced_title": "Access & Integrations","advanced_desc": "Optional extras: the team key proxy, telephony, and the knowledge Wiki provider.","no_providers_in_tier": "No providers available in this category.",@@ -2085,7 +2087,7 @@"realtime_options_error": "Voice options could not be loaded.","realtime_options_retry": "Try again","realtime_model_managed": "Managed",- "realtime_model_managed_hint": "ChatGPT selects the subscription model. Choose an API Realtime provider to pin a GPT Realtime model.",+ "realtime_model_managed_hint": "This provider manages the model. Use its setup controls above to change the selection.","guide_realtime_title": "Which model should I pick?","guide_realtime_body": "OpenAI API: GPT Realtime 2.1 is the current flagship and 2.1 Mini is the budget pick. Google: Gemini 3.1 Flash Live is the current Live flagship.","guide_computer_use_title": "Which provider should power the Tool Model?",@@ -3027,10 +3029,10 @@"summary_accepted": "Terms accepted"},"intro": {- "scene_1": "Meet your voice-first assistant.",- "scene_2": "Just talk — it listens and acts.",- "scene_3": "It keeps working in the background while you don't.",- "scene_4": "Your keys, your data, your rules."+ "scene_1": "Your computer becomes an AI agent.",+ "scene_2": "Give Jarvis a task by chat or voice.",+ "scene_3": "It can use apps, tools, models, and agents.",+ "scene_4": "Review its actions and results in one place."},"language": {"ui_label": "Interface language",@@ -5194,9 +5196,22 @@},"society": {"groups": {- "create": "New agent team", "edit": "Edit agent team", "description": "Bundle agents in one sidebar entry. Each agent keeps its own conversation.",- "name": "Team name", "members": "Members", "cancel": "Cancel", "save": "Save team", "delete": "Ungroup", "delete_confirm": "Ungroup these agents? Their individual chats will remain.",- "left_chat": "Left chat", "right_chat": "Right chat", "open": "Open", "open_individual": "Open {0}'s individual chat", "missing_member": "Select an available agent to view this chat.", "hold_to_group": "Hold to group", "release_to_group": "Release to group"+ "create": "New agent team",+ "edit": "Edit agent team",+ "description": "Bundle agents in one sidebar entry. Each agent keeps its own conversation.",+ "name": "Team name",+ "members": "Members",+ "cancel": "Cancel",+ "save": "Save team",+ "delete": "Ungroup",+ "delete_confirm": "Ungroup these agents? Their individual chats will remain.",+ "left_chat": "Left chat",+ "right_chat": "Right chat",+ "open": "Open",+ "open_individual": "Open {0}'s individual chat",+ "missing_member": "Select an available agent to view this chat.",+ "hold_to_group": "Hold to group",+ "release_to_group": "Release to group"},"chat": {"placeholder": "Message {0}",@@ -5405,6 +5420,18 @@"monitor": "Monitor","ask": "Ask first"},+ "approval_mode": {+ "title": "Agent permissions",+ "bypass": "Bypass permissions",+ "ask": "Ask",+ "always_ask": "Always ask",+ "bypass_hint": "Jarvis tools run without prompts; Jarvis blocks and denied tools still apply. A subscription CLI's native tools follow that runner's controls.",+ "ask_hint": "Read freely; ask in this chat before changes or other actions.",+ "always_ask_hint": "Ask in this chat before every Jarvis tool call, including reads.",+ "legacy_hint": "This agent keeps its existing chat permissions until you choose a mode.",+ "legacy_ceiling": "Existing permission ceiling",+ "unavailable": "This runner cannot show a usable approval card for this mode."+ },"grant": {"all": "All connected tools","allowlist": "Allow-list only"diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 861642056f..3cc590b0bd 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -538,11 +538,9 @@"recent": "Recientes","pin_chat": "Fijar chat","unpin_chat": "Desfijar chat",-"jarvis_tools": "Herramientas Jarvis","scheduled": "Programado","more": "Más",-"instance_dev_hint": "Instancia de desarrollo: una segunda copia de la app que puedes reiniciar libremente, con sus propios datos, puertos e icono. La app normal sigue funcionando al lado.","surface_voice": "Voz","surface_chat": "Chat",@@ -1915,7 +1913,11 @@"managed_speaking_title": "Hablar","managed_voice_unavailable": "aún sin prueba de voz","managed_voice_install_required": "requiere instalar el runtime",- "managed_apply_test": "Aplicar y probar la voz",+ "managed_apply_test": "Aplicar, probar y usar voz local",+ "managed_protocol_options": "Opciones avanzadas de modelo y voz del servidor",+ "managed_setup_testing": "Preparando los modelos seleccionados y probando la voz. El primer inicio puede tardar más.",+ "managed_selected": "Seleccionado para voz. Estos modelos se inician automáticamente con Jarvis.",+ "managed_not_selected": "Este servidor aún no está seleccionado para voz. Elige dos modelos y aplícalos para usar voz local.","managed_full_catalog": "Explorar todo el catálogo de Ollama","managed_voice_catalog_title": "Explorar modelos de voz de código abierto","managed_voice_catalog_search": "Buscar por modelo, backend, idioma o licencia…",@@ -2017,7 +2019,7 @@"cat_computer_use_desc": "El Tool Model ejecuta tus acciones: enruta comandos de voz, planifica Computer-Use en tu pantalla, inicia agentes en segundo plano y controla la app — independiente de tu Brain de chat.","cat_dictation_desc": "El modelo rápido que ordena el texto dictado: puntuación, muletillas y separación de frases. Opcional: sin clave aquí tu dictado llega tal y como se reconoció.","cat_subagents_title": "{name}-Agents",- "cat_subagents_desc": "Este proveedor ejecuta el chat de texto, la memoria y las tareas en segundo plano. Una suscripción aquí no cuesta nada extra; tu clave de voz queda reservada para la llamada.",+ "cat_subagents_desc": "Ejecuta chat, memoria y tareas de fondo, no tu clave de voz.","advanced_title": "Acceso e integraciones","advanced_desc": "Extras opcionales: el proxy de claves de equipo, telefonía y el proveedor del Wiki de conocimiento.","no_providers_in_tier": "No hay proveedores disponibles en esta categoría.",@@ -2051,7 +2053,7 @@"realtime_options_error": "No se pudieron cargar las opciones de voz.","realtime_options_retry": "Intentar de nuevo","realtime_model_managed": "Gestionado",- "realtime_model_managed_hint": "ChatGPT selecciona el modelo de suscripción. Elige un proveedor Realtime por API para fijar un modelo GPT Realtime.",+ "realtime_model_managed_hint": "Este proveedor gestiona el modelo. Usa los controles de configuración anteriores para cambiar la selección.","guide_realtime_title": "¿Qué modelo debería elegir?","guide_realtime_body": "API de OpenAI: GPT Realtime 2.1 es el modelo insignia actual y 2.1 Mini es la opción económica. Google: Gemini 3.1 Flash Live es el modelo insignia actual de Live.","guide_computer_use_title": "¿Qué proveedor debería impulsar el Tool Model?",@@ -2994,10 +2996,10 @@"summary_accepted": "Condiciones aceptadas"},"intro": {- "scene_1": "Conoce a tu asistente por voz.",- "scene_2": "Solo habla — escucha y actúa.",- "scene_3": "Sigue trabajando en segundo plano mientras tú no.",- "scene_4": "Tus claves, tus datos, tus reglas."+ "scene_1": "Tu ordenador se convierte en un agente de IA.",+ "scene_2": "Dale una tarea a Jarvis por chat o voz.",+ "scene_3": "Puede usar apps, herramientas, modelos y agentes.",+ "scene_4": "Revisa sus acciones y resultados en un solo lugar."},"language": {"ui_label": "Idioma de la interfaz",@@ -5161,9 +5163,22 @@},"society": {"groups": {- "create": "Nuevo equipo de agentes", "edit": "Editar equipo de agentes", "description": "Agrupa agentes en una entrada lateral. Cada agente conserva su propio chat.",- "name": "Nombre del equipo", "members": "Miembros", "cancel": "Cancelar", "save": "Guardar equipo", "delete": "Desagrupar", "delete_confirm": "¿Desagrupar estos agentes? Sus chats individuales permanecerán.",- "left_chat": "Chat izquierdo", "right_chat": "Chat derecho", "open": "Abrir", "open_individual": "Abrir el chat individual de {0}", "missing_member": "Selecciona un agente disponible para este chat.", "hold_to_group": "Mantén para agrupar", "release_to_group": "Suelta para agrupar"+ "create": "Nuevo equipo de agentes",+ "edit": "Editar equipo de agentes",+ "description": "Agrupa agentes en una entrada lateral. Cada agente conserva su propio chat.",+ "name": "Nombre del equipo",+ "members": "Miembros",+ "cancel": "Cancelar",+ "save": "Guardar equipo",+ "delete": "Desagrupar",+ "delete_confirm": "¿Desagrupar estos agentes? Sus chats individuales permanecerán.",+ "left_chat": "Chat izquierdo",+ "right_chat": "Chat derecho",+ "open": "Abrir",+ "open_individual": "Abrir el chat individual de {0}",+ "missing_member": "Selecciona un agente disponible para este chat.",+ "hold_to_group": "Mantén para agrupar",+ "release_to_group": "Suelta para agrupar"},"chat": {"placeholder": "Mensaje a {0}",@@ -5372,6 +5387,18 @@"monitor": "Supervisar","ask": "Preguntar primero"},+ "approval_mode": {+ "title": "Permisos del agente",+ "bypass": "Omitir permisos",+ "ask": "Preguntar",+ "always_ask": "Preguntar siempre",+ "bypass_hint": "Las herramientas de Jarvis se ejecutan sin preguntas; sus bloqueos siguen activos. Las herramientas nativas de una CLI de suscripción siguen sus propias reglas.",+ "ask_hint": "Lee libremente; pregunta en este chat antes de cambios u otras acciones.",+ "always_ask_hint": "Pregunta en este chat antes de cada herramienta de Jarvis, incluso para leer.",+ "legacy_hint": "Este agente conserva los permisos actuales del chat hasta que elijas un modo.",+ "legacy_ceiling": "Límite de permisos anterior",+ "unavailable": "Este ejecutor no puede mostrar una aprobación utilizable para este modo."+ },"grant": {"all": "Todas las herramientas conectadas","allowlist": "Solo lista permitida"diff --git a/jarvis/ui/web/frontend/src/lib/societyApi.ts b/jarvis/ui/web/frontend/src/lib/societyApi.tsindex 122995c6db..762e744cb7 100644--- a/jarvis/ui/web/frontend/src/lib/societyApi.ts+++ b/jarvis/ui/web/frontend/src/lib/societyApi.ts@@ -52,6 +52,9 @@ export type Checkpoint = (typeof CHECKPOINTS)[number];export const PERMISSION_CEILINGS = ["safe", "monitor", "ask"] as const;export type PermissionCeiling = (typeof PERMISSION_CEILINGS)[number];+export const AGENT_APPROVAL_MODES = ["bypass", "ask", "always_ask"] as const;+export type AgentApprovalMode = (typeof AGENT_APPROVAL_MODES)[number];+export const BROWSER_MODES = ["own", "attach"] as const;export type BrowserMode = (typeof BROWSER_MODES)[number];@@ -155,6 +158,8 @@ export interface SocietyAgentRow {wiki_namespace: string;knowledge_scope: KnowledgeScope;permission_ceiling: PermissionCeiling;+ /** Null only for an existing agent whose chat retains its legacy setting. */+ approval_mode: AgentApprovalMode | null;approval_rules: ApprovalRules;daily_budget_usd: number;max_concurrent_runs: number;diff --git a/jarvis/ui/web/mcp_server_routes.py b/jarvis/ui/web/mcp_server_routes.pyindex b18328b390..e9c771ded8 100644--- a/jarvis/ui/web/mcp_server_routes.py+++ b/jarvis/ui/web/mcp_server_routes.py@@ -137,7 +137,10 @@ def session_ref(scope: dict[str, Any]) -> str | None:value = raw_value.decode("latin-1").strip()# Society chats use a namespaced roster slug, while ordinary chats# use opaque alphanumeric IDs. Preserve that scope for tool lookup.- if len(value) <= 128 and re.fullmatch(r"society:[a-z0-9]+(?:-[a-z0-9]+)*", value):+ if len(value) <= 128 and re.fullmatch(+ r"society:[a-z0-9]+(?:-[a-z0-9]+)*(?::routine:[a-zA-Z0-9_-]+:[a-zA-Z0-9_-]+)?",+ value,+ ):return valueif len(value) <= 64 and re.fullmatch(r"[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*", value):return valuediff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.pyindex e24db48975..14d89c9d45 100644--- a/jarvis/ui/web/society_routes.py+++ b/jarvis/ui/web/society_routes.py@@ -90,6 +90,7 @@ class CreateAgentBody(BaseModel):denies: list[str] | None = Noneskills: list[str] | None = Nonepermission_ceiling: str | None = None+ approval_mode: str | None = Noneapproval_rules: dict[str, list[str]] | None = Nonedaily_budget_usd: float | None = Nonemax_concurrent_runs: int | None = None@@ -125,6 +126,7 @@ class PatchAgentBody(BaseModel):skills: list[str] | None = Noneknowledge_scope: str | None = Nonepermission_ceiling: str | None = None+ approval_mode: str | None = Noneapproval_rules: dict[str, list[str]] | None = Nonedaily_budget_usd: float | None = Nonemax_concurrent_runs: int | None = None@@ -262,6 +264,16 @@ async def create_agent(body: CreateAgentBody, request: Request) -> dict[str, Anyfrom jarvis.society.inherit import inherit_creator_fieldsfields = inherit_creator_fields(fields, creator)+ requested_mode = str(fields.get("approval_mode") or "bypass")+ provider = str(fields.get("provider") or body.provider)+ if provider:+ from jarvis.agent_chat.permissions import society_mode_supported+ from jarvis.agent_chat.service import resolve_runner++ if not society_mode_supported(resolve_runner(provider, surface="society"), requested_mode):+ raise HTTPException(+ 422, "This runner cannot provide an actionable approval for that mode."+ )derived_focus, derived_rules = rt.derive(body.title, description)if body.focus is None and derived_focus:fields["focus"] = derived_focus@@ -315,6 +327,18 @@ async def patch_agent(agent_id: str, body: PatchAgentBody, request: Request) ->if has_brief(brief):# A brief rewrites the standing instructions as a whole.fields["description"] = compose_description(body.description or "", brief)+ requested_mode = body.approval_mode or (+ str(agent.approval_mode) if body.provider and agent.approval_mode else ""+ )+ if requested_mode:+ from jarvis.agent_chat.permissions import society_mode_supported+ from jarvis.agent_chat.service import resolve_runner++ provider = body.provider or agent.provider+ if not society_mode_supported(resolve_runner(provider, surface="society"), requested_mode):+ raise HTTPException(+ 422, "This runner cannot provide an actionable approval for that mode."+ )if ("title" in fields or "description" in fields) and "focus" not in fields:# A prose edit must not wipe what the agent earned in its chat: the# derived focus is APPENDED to the existing order (existing first,@@ -336,6 +360,10 @@ async def patch_agent(agent_id: str, body: PatchAgentBody, request: Request) ->updated = await rt.roster.update(agent.agent_id, fields)except RosterError as exc:raise _typed_error(exc) from exc+ if "approval_mode" in fields:+ svc = rt.chat_service()+ if svc is not None and svc.store.get_session(updated.session_id) is not None:+ svc.store.update_session(updated.session_id, permission_mode=str(updated.approval_mode))if "state" in fields:await rt.checkpoints.refresh(agent.agent_id)updated = await rt.roster.get(agent.agent_id) or updated@@ -356,7 +384,10 @@ async def bind_agent_chat(agent_id: str, request: Request) -> dict[str, Any]:raise HTTPException(503, "agent chat service unavailable")from jarvis.society.chat_binding import ensure_session- session = ensure_session(svc, rt.config(), agent)+ try:+ session = ensure_session(svc, rt.config(), agent)+ except PermissionError as exc:+ raise HTTPException(422, str(exc)) from excreturn {"session": session.to_dict(), "agent_id": agent.agent_id}@@ -685,6 +716,7 @@ async def switch_agent_model(agent_id: str, body: ModelBody, request: Request) -"""Move the agent onto another provider / model / effort / subscription seat.Its canonical chat is re-seated at once (transcript kept)."""from jarvis.agent_chat.catalog import offers+ from jarvis.agent_chat.permissions import society_mode_supportedfrom jarvis.agent_chat.service import resolve_runnerrt = await _runtime(request)@@ -696,6 +728,10 @@ async def switch_agent_model(agent_id: str, body: ModelBody, request: Request) -422,{"reason": str(FailureReason.BLOCKED_BY_POLICY), "detail": "provider not offered"},)+ if agent.approval_mode and not society_mode_supported(+ resolve_runner(body.provider, surface="society"), str(agent.approval_mode)+ ):+ raise HTTPException(422, "This runner cannot provide an actionable approval for that mode.")fields = {"provider": body.provider.strip().lower(),"model": body.model.strip(),diff --git a/tests/contract/test_agent_mcp_harmony.py b/tests/contract/test_agent_mcp_harmony.pyindex b9e19fe41c..10d82b5bd0 100644--- a/tests/contract/test_agent_mcp_harmony.py+++ b/tests/contract/test_agent_mcp_harmony.py@@ -154,6 +154,21 @@ WITHHELD: Final[dict[str, str]] = {"editing a routine changes recurring spend; the owner does it on the ""routine card where the schedule is visible, not via a remote client"),+ "POST /api/society/agents/{agent_id}/routines/{task_id}/operation": (+ "pausing, deleting or running a routine now changes recurring spend; "+ "the owner does it on the routine card, not via a remote client"+ ),+ "GET /api/society/chat-groups": (+ "group chats are the owner's own chat layout in the app; a remote "+ "client addresses agents directly"+ ),+ "POST /api/society/chat-groups": "arranging the owner's group chats is app-only UI state",+ "PATCH /api/society/chat-groups/{group_id}": (+ "renaming or regrouping the owner's group chats is app-only UI state"+ ),+ "DELETE /api/society/chat-groups/{group_id}": (+ "ungrouping the owner's chats is app-only UI state"+ ),}diff --git a/tests/contract/test_society_coding_sessions.py b/tests/contract/test_society_coding_sessions.pyindex 9348797713..13a53e0797 100644--- a/tests/contract/test_society_coding_sessions.py+++ b/tests/contract/test_society_coding_sessions.py@@ -86,8 +86,26 @@ async def test_new_society_agent_gets_grantable_gated_tool(rig, tmp_path):cfg = SimpleNamespace(wiki=SimpleNamespace(vault_root=str(tmp_path / "vault")))await society_system_extra(cfg, None, session)selected = society_tool_filter(session)(society_tools(cfg, None, session))+ # A new agent defaults to Bypass under an ask ceiling: the gated tool is+ # there and opening runs without a card.+ assert selected["coding-session"].risk_tier_for_args({"action": "open"}) == "monitor"+ assert selected["coding-session"].risk_tier_for_args({"action": "context"}) == "monitor"+ # An explicit require-approval rule still cards the call under Bypass.+ await runtime.roster.update(+ agent.agent_id,+ {"approval_rules": {"require_approval": ["core:coding-session:open"]}},+ )+ await society_system_extra(cfg, None, session)+ selected = society_tool_filter(session)(society_tools(cfg, None, session))assert selected["coding-session"].risk_tier_for_args({"action": "open"}) == "ask"assert selected["coding-session"].risk_tier_for_args({"action": "context"}) == "monitor"+ # Ask mode cards the open; a read above safe also waits for the person.+ await runtime.roster.update(+ agent.agent_id, {"approval_mode": "ask", "approval_rules": {"require_approval": []}}+ )+ await society_system_extra(cfg, None, session)+ selected = society_tool_filter(session)(society_tools(cfg, None, session))+ assert selected["coding-session"].risk_tier_for_args({"action": "open"}) == "ask"await runtime.roster.update(agent.agent_id, {"denies": ["core:coding-session"]})denied = await rig[4].execute({"action": "discover"}, None)assert not denied.success@@ -222,6 +240,8 @@ async def test_subscription_seat_gets_scoped_catalog_and_executor_gate(rig):from jarvis.society.surface import coding_tool_for_sessioncalls = []+ # The executor gate follows the agent's explicit Ask mode.+ await rig[3].roster.update(rig[5].agent_id, {"approval_mode": "ask"})class Executor:async def execute(self, tool, arguments, **kwargs):diff --git a/tests/contract/test_society_voice_management.py b/tests/contract/test_society_voice_management.pyindex e27eb9ded7..89383854cc 100644--- a/tests/contract/test_society_voice_management.py+++ b/tests/contract/test_society_voice_management.py@@ -134,7 +134,11 @@ async def test_management_rejects_missing_agent_invalid_model_and_unexposed_fiel},context(),)- assert not escalation.success and "unknown argument" in escalation.error+ # The ceiling is editable by voice now, but only within safe/monitor/ask:+ # an escalation past "ask" is refused before anything runs.+ assert not escalation.success+ assert "permission_ceiling" in escalation.error+ assert "Nothing was executed" in escalation.errordef test_management_is_supervisor_only_and_degrades_without_server():diff --git a/tests/unit/agent_chat/test_approval_bridge.py b/tests/unit/agent_chat/test_approval_bridge.pyindex ff1ab45fc3..4c58d08bab 100644--- a/tests/unit/agent_chat/test_approval_bridge.py+++ b/tests/unit/agent_chat/test_approval_bridge.py@@ -178,10 +178,47 @@ async def test_bypass_asks_nothing(tmp_path: Path):assert card.asked == []+async def test_bypass_still_cards_an_explicit_require_approval_rule(tmp_path: Path):+ """Society's require-approval rules (``force_ask``) override Bypass."""+ executor, bridge, _ = _stack()+ card = _Card("deny")+ seen: list[tuple[str, dict[str, Any]]] = []++ def force_ask(name: str, args: dict[str, Any]) -> bool:+ seen.append((name, dict(args)))+ return "rm" in str(args.get("command") or "")++ grant = _grant(card, "bypass")+ grant.force_ask = force_ask+ bridge.arm(REF, grant)+ run = ft.folder_tools(tmp_path)["RunCommand"]++ forced = await executor.execute(run, {"command": "rm x"}, config_snapshot=_snapshot())+ assert not forced.success and forced.error+ assert forced.error.startswith(APPROVAL_DENIED_PREFIX)+ assert [a[1] for a in card.asked] == ["RunCommand"]+ assert seen[0] == ("RunCommand", {"command": "rm x"})++ ran = await executor.execute(run, {"command": "echo hi"}, config_snapshot=_snapshot())+ assert ran.success, ran.error+ assert len(card.asked) == 1+++async def test_always_ask_cards_even_a_remembered_tool(tmp_path: Path):+ executor, bridge, _ = _stack()+ card = _Card("deny")+ bridge.arm(REF, _grant(card, "always_ask", {"RunCommand"}))+ run = ft.folder_tools(tmp_path)["RunCommand"]+ result = await executor.execute(run, {"command": "echo hi"}, config_snapshot=_snapshot())+ assert not result.success and result.error+ assert result.error.startswith(APPROVAL_DENIED_PREFIX)+ assert [a[1] for a in card.asked] == ["RunCommand"]++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"):+ for stance in ("ask", "accept-edits", "bypass", "always_ask"):executor, bridge, _ = _stack(safety=safety)card = _Card("allow")bridge.arm(REF, _grant(card, stance))diff --git a/tests/unit/agent_chat/test_jarvis_identity.py b/tests/unit/agent_chat/test_jarvis_identity.pyindex 2d028b3c49..b2d01e68b9 100644--- a/tests/unit/agent_chat/test_jarvis_identity.py+++ b/tests/unit/agent_chat/test_jarvis_identity.py@@ -301,7 +301,16 @@ def test_the_mcp_route_reads_the_session_header_and_ignores_junk():assert mcp_server_routes.session_ref({"headers": [(b"x-jarvis-chat-session", b"../x")]}) is None[email protected]("value", ["society:nala", "society:gmail-agent", "sess-1", "0123abcd"])+ "value",+ [+ "society:nala",+ "society:gmail-agent",+ "society:reddit-community-agent:routine:task123:exec456",+ "sess-1",+ "0123abcd",+ ],+)def test_session_header_preserves_canonical_chat_scopes(value):assert (mcp_server_routes.session_ref({"headers": [(b"x-jarvis-chat-session", value.encode())]})diff --git a/tests/unit/society/test_approvals.py b/tests/unit/society/test_approvals.pyindex dca1f7d8cd..d5cc6c81a9 100644--- a/tests/unit/society/test_approvals.py+++ b/tests/unit/society/test_approvals.py@@ -2,6 +2,7 @@from __future__ import annotations+from dataclasses import replacefrom pathlib import Pathimport pytest@@ -34,12 +35,15 @@ def test_pattern_matching():async def test_verdict_order(world):+ """A pre-migration row (``approval_mode`` NULL) keeps the legacy+ rules → always-allow → ceiling order."""_, roster, _ = world- agent, _ = await roster.create(+ created, _ = await roster.create(name="Mailbox",permission_ceiling="monitor",approval_rules={"require_approval": ["plugin:gmail:send"], "always_allow": ["cli:gh"]},)+ agent = replace(created, approval_mode=None)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@@ -50,14 +54,60 @@ async def test_verdict_order(world):assert decide(agent, "plugin:spotify", "block") is Verdict.BLOCKstrict, _ = await roster.create(name="Reader", permission_ceiling="safe")+ strict = replace(strict, approval_mode=None)assert decide(strict, "core:search-web", "safe") is Verdict.RUNassert decide(strict, "plugin:gmail", "monitor") is Verdict.QUEUEtrusting, _ = await roster.create(name="Doer", permission_ceiling="ask")+ trusting = replace(trusting, approval_mode=None)assert decide(trusting, "plugin:gmail", "monitor") is Verdict.RUNassert decide(trusting, "plugin:gmail", "ask") is Verdict.QUEUE # ask still asks a human+async def test_verdict_order_per_approval_mode(world):+ """Explicit modes: require-approval and blocks win in every mode; Bypass+ runs up to the ceiling and denies above it; Ask queues everything past a+ safe read; Always ask queues everything, even a standing yes."""+ _, roster, _ = world+ rules = {"require_approval": ["plugin:gmail:send"], "always_allow": ["cli:gh"]}++ bypass, _ = await roster.create(name="Bypasser", approval_rules=rules)+ assert str(bypass.approval_mode) == "bypass" # the new-agent default+ assert str(bypass.permission_ceiling) == "ask"+ assert decide(bypass, "core:search-web", "safe") is Verdict.RUN+ assert decide(bypass, "plugin:gmail", "monitor", verb="read") is Verdict.RUN+ assert decide(bypass, "core:run-shell", "ask") is Verdict.RUN+ assert decide(bypass, "plugin:gmail", "monitor", verb="send") is Verdict.QUEUE+ assert decide(bypass, "plugin:gmail", "ask", verb="send") is Verdict.QUEUE+ assert decide(bypass, "plugin:spotify", "block") is Verdict.BLOCK+ assert decide(bypass, "cli:gh", "block") is Verdict.BLOCK++ capped, _ = await roster.create(+ name="Capped", permission_ceiling="monitor", approval_rules=rules+ )+ assert str(capped.approval_mode) == "bypass"+ assert decide(capped, "plugin:gmail", "monitor", verb="read") is Verdict.RUN+ # Bypass removes prompts, not the ceiling: above it the call is denied.+ assert decide(capped, "core:run-shell", "ask") is Verdict.BLOCK+ assert decide(capped, "cli:gh", "ask") is Verdict.RUN # the person's standing yes+ assert decide(capped, "plugin:gmail", "ask", verb="send") is Verdict.QUEUE++ asker, _ = await roster.create(name="Asker", approval_mode="ask", approval_rules=rules)+ assert decide(asker, "core:search-web", "safe") is Verdict.RUN+ assert decide(asker, "plugin:gmail", "monitor", verb="read") is Verdict.QUEUE+ assert decide(asker, "core:run-shell", "ask") is Verdict.QUEUE+ assert decide(asker, "cli:gh", "ask") is Verdict.RUN # standing yes up to ask+ assert decide(asker, "plugin:gmail", "safe", verb="send") is Verdict.QUEUE+ assert decide(asker, "plugin:spotify", "block") is Verdict.BLOCK++ always, _ = await roster.create(+ name="Careful", approval_mode="always_ask", approval_rules=rules+ )+ assert decide(always, "core:search-web", "safe") is Verdict.QUEUE+ assert decide(always, "cli:gh", "monitor") is Verdict.QUEUE # ignores the standing yes+ assert decide(always, "plugin:spotify", "block") is Verdict.BLOCK++async def test_enqueue_resolve_and_board_projection(world):store, roster, approvals = worldawait roster.create(name="Mailbox")@@ -132,12 +182,13 @@ 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 anask-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.QUEUE+ rules = {"require_approval": [], "always_allow": ["plugin:gmail:send"]}+ for mode in (None, "ask"):+ created, _ = await roster.create(+ name=f"Mailbox {mode}", permission_ceiling="ask", approval_rules=rules+ )+ agent = replace(created, approval_mode=mode)+ 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_browser.py b/tests/unit/society/test_browser.pyindex 8df9b5add2..ff38625700 100644--- a/tests/unit/society/test_browser.py+++ b/tests/unit/society/test_browser.py@@ -180,9 +180,30 @@ async def test_tool_gates(rt, tmp_path, fake_runner):jobs = _jobs(tmp_path, fake_runner)tool = BrowserTool(rt, "scout", jobs)assert tool.risk_tier_for_args({"task": "delete the old posts"}) == "ask"+ # An explicit Ask agent queues an acting task for the person.+ await rt.roster.update("scout", {"approval_mode": "ask"})queued = await tool.execute({"task": "send the report to the team"}, CTX)assert queued.success is False and queued.output["reason"] == "approval_required"assert len(await rt.approvals.pending()) == 1+ # Bypass still honors an explicit require-approval rule.+ await rt.roster.update(+ "scout",+ {+ "approval_mode": "bypass",+ "approval_rules": {"require_approval": ["core:browser:act"], "always_allow": []},+ },+ )+ forced = await tool.execute({"task": "send the report to the team"}, CTX)+ assert forced.success is False and forced.output["reason"] == "approval_required"+ assert len(await rt.approvals.pending()) == 2+ # Bypass under a lower inherited ceiling denies instead of escalating.+ await rt.roster.update(+ "scout",+ {"permission_ceiling": "monitor", "approval_rules": {"require_approval": []}},+ )+ denied = await tool.execute({"task": "send the report to the team"}, CTX)+ assert denied.success is False and denied.output["reason"] == "blocked_by_policy"+ assert len(await rt.approvals.pending()) == 2off = BrowserTool(rt, "scout", _jobs(tmp_path, fake_runner, installed=False))not_ready = await off.execute({"task": "read"}, CTX)assert not_ready.success is False and "install_action" in not_ready.outputdiff --git a/tests/unit/society/test_chat_binding.py b/tests/unit/society/test_chat_binding.pyindex 37a8df501b..25da99fdb7 100644--- a/tests/unit/society/test_chat_binding.py+++ b/tests/unit/society/test_chat_binding.py@@ -2,6 +2,7 @@from __future__ import annotations+import dataclassesimport osfrom pathlib import Pathfrom types import SimpleNamespace@@ -61,7 +62,8 @@ async def test_ensure_session_is_deterministic_and_reseats(world):assert first.session_id == "society:scout"assert first.surface == "society"assert first.provider == "openai" and first.model == "gpt-5.2"- assert first.permission_mode == "accept-edits"+ # New agents start on the Society ladder's Bypass default.+ assert first.permission_mode == "bypass"assert first.title == "Scout"assert Path(first.cwd).name == "workspace" and os.path.isdir(first.cwd) # noqa: ASYNC240assert Path(first.cwd).is_absolute()@@ -76,14 +78,24 @@ async def test_ensure_session_is_deterministic_and_reseats(world):assert reseated.session_id == "society:scout"-async def test_ceiling_maps_to_stance(world):+async def test_legacy_ceiling_maps_to_stance(world):+ """A pre-migration row (no approval mode) keeps its ceiling's old stance."""rt, svc, cfg = worldsafe, _ = await rt.roster.create(name="Reader", provider="openai", permission_ceiling="safe")ask, _ = await rt.roster.create(name="Asker", provider="openai", permission_ceiling="ask")+ safe = dataclasses.replace(safe, approval_mode=None)+ ask = dataclasses.replace(ask, approval_mode=None)assert ensure_session(svc, cfg, safe).permission_mode == "plan"assert ensure_session(svc, cfg, ask).permission_mode == "ask"+async def test_explicit_approval_mode_wins(world):+ rt, svc, cfg = world+ asker, _ = await rt.roster.create(name="Asker", provider="openai")+ asker = await rt.roster.update("asker", {"approval_mode": "ask"})+ assert ensure_session(svc, cfg, asker).permission_mode == "ask"++async def test_without_provider_the_agents_tier_answers(world, monkeypatch):rt, svc, cfg = worldimport jarvis.local_models.assistant_session as tier_moddiff --git a/tests/unit/society/test_cli_routines.py b/tests/unit/society/test_cli_routines.pyindex 421ee18926..bcc8ebd326 100644--- a/tests/unit/society/test_cli_routines.py+++ b/tests/unit/society/test_cli_routines.py@@ -227,9 +227,23 @@ def test_resumed_society_seat_refreshes_routine_contract(monkeypatch, tmp_path):identity=identity,)assert "mcp_servers.jarvis.required=true" in plan.argv- assert 'mcp_servers.jarvis.tools.society_propose_change.approval_mode="approve"' in plan.argv+ # Codex exec cannot answer its own MCP prompts; every Jarvis tool defers+ # to the session catalog and ToolExecutor, which own the approval card.+ assert 'mcp_servers.jarvis.default_tools_approval_mode="approve"' in plan.argvassert 'mcp_servers.jarvis.tools.society_browser.approval_mode="approve"' in plan.argv- assert not any("default_tools_approval_mode" in arg for arg in plan.argv)+ # A society seat gets no vendor-native hands that would bypass that gate.+ assert 'sandbox_mode="read-only"' in plan.argv+ assert 'approval_policy="never"' in plan.argv+ for feature in ("shell_tool", "apps", "browser_use", "computer_use", "web_search_request"):+ index = plan.argv.index(feature)+ assert plan.argv[index - 1] == "--disable"+ assert "--dangerously-bypass-approvals-and-sandbox" not in plan.argv+ # The blanket approve is only for society seats, never an ordinary chat.+ for session_id in (None, "ordinary-chat"):+ assert not any(+ "default_tools_approval_mode" in arg+ for arg in jarvis_harness.codex_config_args(session_id)+ )assert "society_propose_change" in plan.stdin_textassert "LARGE OLD IDENTITY" not in plan.stdin_textassert plan.stdin_text.endswith("Check comments every hour")diff --git a/tests/unit/society/test_creator_inherit.py b/tests/unit/society/test_creator_inherit.pyindex 7e92f86a12..f397b9c2ee 100644--- a/tests/unit/society/test_creator_inherit.py+++ b/tests/unit/society/test_creator_inherit.py@@ -67,6 +67,26 @@ async def test_inherit_fills_blank_seat_and_permissions_and_caps_a_raise(tmp_patassert "core:run-shell" in capped["denies"] and "core:search-web" in capped["denies"]+async def test_inherit_never_loosens_the_creators_approval_mode(tmp_path: Path) -> None:+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False)+ await runtime.ensure_started()+ try:+ asker, _ = await runtime.roster.create(name="Asker", approval_mode="ask")+ assert inherit_creator_fields({}, asker)["approval_mode"] == "ask"+ raised = inherit_creator_fields({"approval_mode": "bypass"}, asker)+ assert raised["approval_mode"] == "ask"+ stricter = inherit_creator_fields({"approval_mode": "always_ask"}, asker)+ assert stricter["approval_mode"] == "always_ask"+ bogus = inherit_creator_fields({"approval_mode": "yolo"}, asker)+ assert bogus["approval_mode"] == "ask"++ careful, _ = await runtime.roster.create(name="Careful", approval_mode="always_ask")+ kid = inherit_creator_fields({"approval_mode": "bypass"}, careful)+ assert kid["approval_mode"] == "always_ask"+ finally:+ await runtime.close()++async def test_create_from_society_session_inherits_seat_and_permissions(tmp_path: Path) -> None:client, runtime = _client(tmp_path)await runtime.ensure_started()@@ -135,12 +155,15 @@ async def test_ui_create_without_session_keeps_defaults_and_explicit_seat(tmp_paassert blank["provider"] == ""assert blank["model"] == ""assert blank["account_id"] == ""- assert blank["permission_ceiling"] == "monitor"+ # New agents default to Bypass under an ask ceiling.+ assert blank["permission_ceiling"] == "ask"+ assert blank["approval_mode"] == "bypass"assert blank["grant_mode"] == "all"assert blank["parent_agent_id"] is Noneassert picked["provider"] == "openai"assert picked["model"] == "gpt-5"assert picked["permission_ceiling"] == "safe"+ assert picked["approval_mode"] == "bypass"assert picked["grant_mode"] == "all"@@ -151,7 +174,8 @@ async def test_paused_creator_session_does_not_inherit(tmp_path: Path) -> None:name="Bot Maker",provider="grok-build",model="grok-4.6",- permission_ceiling="ask",+ permission_ceiling="safe",+ approval_mode="always_ask",)await runtime.roster.update(creator.agent_id, {"state": AgentState.PAUSED})with client as c:@@ -161,5 +185,6 @@ async def test_paused_creator_session_does_not_inherit(tmp_path: Path) -> None:headers={"X-Jarvis-Chat-Session": creator.session_id},).json()["agent"]assert agent["provider"] == ""- assert agent["permission_ceiling"] == "monitor"+ assert agent["permission_ceiling"] == "ask"+ assert agent["approval_mode"] == "bypass"assert agent["parent_agent_id"] is Nonediff --git a/tests/unit/society/test_roster.py b/tests/unit/society/test_roster.pyindex ca00018936..45a29e373e 100644--- a/tests/unit/society/test_roster.py+++ b/tests/unit/society/test_roster.py@@ -7,7 +7,13 @@ from pathlib import Pathimport pytest-from jarvis.society.events import AgentState, GrantMode, PermissionCeiling, Tier+from jarvis.society.events import (+ AgentApprovalMode,+ AgentState,+ GrantMode,+ PermissionCeiling,+ Tier,+)from jarvis.society.failure_reasons import FailureReasonfrom jarvis.society.roster import Roster, RosterError, canonical_session_id, slugifyfrom jarvis.society.store import SocietyStore@@ -40,7 +46,9 @@ async def test_create_then_adopt_by_name(roster: Roster):assert scout.tier is Tier.SPECIALISTassert scout.state is AgentState.ACTIVEassert scout.grant_mode is GrantMode.ALL- assert scout.permission_ceiling is PermissionCeiling.MONITOR+ # New agents default to Bypass under an ask ceiling.+ assert scout.permission_ceiling is PermissionCeiling.ASK+ assert scout.approval_mode is AgentApprovalMode.BYPASSassert scout.wiki_namespace == "society/scout/"assert scout.session_id == "society:scout"diff --git a/tests/unit/society/test_surface.py b/tests/unit/society/test_surface.pyindex 7d484e1713..66b6ae5c5e 100644--- a/tests/unit/society/test_surface.py+++ b/tests/unit/society/test_surface.py@@ -16,6 +16,7 @@ from jarvis.society.agent_tools import (SHELL_TOOL_NAME,WIKI_NOTE_TOOL_NAME,)+from jarvis.society.ask_tool import ASK_USER_TOOL_NAMEfrom jarvis.society.learning import RUN_SKILL_TOOL_NAMEfrom jarvis.society.runtime import SocietyRuntimefrom jarvis.society.surface import (@@ -200,8 +201,24 @@ async def test_a_granted_tool_is_gated_by_the_agents_rules(rt: SocietyRuntime, tassert gmail.name == "gmail" and gmail.schema == TOOLS["gmail"].schemaassert 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")+ # Under an explicit approval mode even the own hands ride the gate, so+ # Always ask can card a read; asking the user is never gated twice.+ assert hasattr(picked[SHELL_TOOL_NAME], "_capability_id")+ if ASK_USER_TOOL_NAME in picked:+ assert not hasattr(picked[ASK_USER_TOOL_NAME], "_capability_id")+ await rt.roster.update("mailbox", {"approval_mode": "always_ask"})+ await society_system_extra(cfg, None, session)+ careful = society_tool_filter(session)({**TOOLS, **society_tools(cfg, None, session)}) # type: ignore[misc]+ assert careful["gmail"].risk_tier_for_args({"action": "list"}) == "ask"+ assert careful[SHELL_TOOL_NAME].risk_tier_for_args({}) == "ask"+ # A pre-migration row (approval_mode NULL) keeps its own hands unwrapped:+ # the society tools gate themselves, as before the migration.+ await rt.store.update_agent("mailbox", {"approval_mode": None})+ await society_system_extra(cfg, None, session)+ legacy = society_tool_filter(session)({**TOOLS, **society_tools(cfg, None, session)}) # type: ignore[misc]+ assert not hasattr(legacy[SHELL_TOOL_NAME], "_capability_id")+ assert legacy["gmail"].risk_tier_for_args({"action": "send"}) == "ask" # require_approval+ await rt.roster.update("mailbox", {"approval_mode": "bypass"})# An always-allow rule is the person's standing yes: an ask-tier call runs.await rt.roster.update("mailbox",