Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(society): serialize direct chat seats and recheck live permissions (#376)

Ruben Lütke5e02080eea92
diff --git a/jarvis/agent_chat/control.py b/jarvis/agent_chat/control.py
index 936e73b88f..d62a8d79ad 100644
--- a/jarvis/agent_chat/control.py
+++ b/jarvis/agent_chat/control.py
@@ -486,14 +486,14 @@ class ChatControls:
raise ValueError(completed[-1].error if completed else "Command was interrupted")
return {"result": completed[-1].output}
- async def user_message(self, sid: str, text: str) -> None:
+ async def user_message(self, sid: str, text: str) -> int | None:
state = self.state(sid)
if state.goal and state.goal.native_pending and state.goal.status != "active":
await self._clear_saved_native(sid)
state = self.state(sid)
active = state.goal is not None and state.goal.status == "active"
if self.service.is_running(sid) and not active:
- return
+ return None
if active:
await self.pause(sid, "User is steering the task")
state = self.state(sid)
@@ -502,6 +502,31 @@ class ChatControls:
state.last_request = text
state.last_status = "running"
self.store.save(state)
+ return state.revision
+
+ async def message_rejected(self, sid: str, text: str, revision: int) -> None:
+ """Close a control status when validation rejects a message before its turn.
+
+ A later control write owns a newer revision and must not be rolled back.
+ Keep an active goal for a later explicit continuation, but pause it
+ because no runner was admitted for this message.
+ """
+ state = self.state(sid)
+ if (
+ state.revision != revision
+ or state.last_request != text
+ or state.last_status != "running"
+ or self.service.is_running(sid)
+ ):
+ return
+ if state.goal and state.goal.status == "active":
+ state.goal.status = "paused"
+ state.goal.reason = "Message was not started"
+ state.goal.updated_ms = int(time.time() * 1000)
+ state.last_status = "interrupted"
+ else:
+ state.last_status = "failed"
+ await self.publish(state)
async def turn_completed(
self, sid: str, turn_id: str, text: str, direct_user: bool, read_only: bool
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index 84963288b5..b0ff9f3574 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -199,13 +199,22 @@ def _expires_ms(timeout_s: float) -> int:
return int(time.time() * 1000 + timeout_s * 1000)
+def _current_task() -> asyncio.Task[Any] | None:
+ try:
+ return asyncio.current_task()
+ except RuntimeError: # Synchronous routes may inspect status off the event loop.
+ return None
+
+
class _Running:
- __slots__ = ("asks", "task", "cancel", "turn_id")
+ __slots__ = ("asks", "task", "cancel", "turn_id", "setup_task", "ready")
def __init__(self, turn_id: str, cancel: asyncio.Event) -> None:
self.turn_id = turn_id
self.cancel = cancel
self.task: asyncio.Task[None] | None = None
+ self.setup_task: asyncio.Task[Any] | None = _current_task()
+ self.ready = asyncio.Event()
#: Question cards this turn has shown (MAX_ASKS_PER_TURN).
self.asks = 0
@@ -236,6 +245,9 @@ class AgentChatService:
# is NOT held by this lock.
self._brain_lock = asyncio.Lock()
self._running: dict[str, _Running] = {}
+ # Reserved before control state is marked running. The runner has not
+ # started yet, but a competing send and Stop must both see this owner.
+ self._preparing: dict[str, _Running] = {}
self._subscribers: dict[str, set[Subscriber]] = {}
self._approvals: dict[str, asyncio.Future[str]] = {}
self._approval_session: dict[str, str] = {}
@@ -376,12 +388,18 @@ class AgentChatService:
)
def is_running(self, session_id: str) -> bool:
+ preparing = self._preparing.get(session_id)
+ if preparing is not None and preparing.setup_task is not _current_task():
+ return True
run = self._running.get(session_id)
- return bool(run and run.task and not run.task.done())
+ return bool(run and (run.task is None or not run.task.done()))
def running_session_ids(self) -> list[str]:
- """Every session with a live turn right now."""
- return [sid for sid in list(self._running) if self.is_running(sid)]
+ """Sessions occupying a chat seat, including pre-admission setup."""
+ return [
+ *[sid for sid in list(self._running) if self.is_running(sid)],
+ *list(self._preparing),
+ ]
async def seal_stopped_turn(self, session_id: str) -> bool:
"""Close a turn the stop button can still see after its runner is gone.
@@ -639,156 +657,311 @@ class AgentChatService:
command = re.match(r"^/([a-z]+)(?:\s|$)", text.strip())
if command and command[1] in {row["name"] for row in COMMANDS}:
raise ValueError("Use the chat command endpoint for slash commands")
- if hasattr(self, "_controls"):
- await self._controls.user_message(session_id, text)
- if read_only:
- session = replace(session, permission_mode="plan")
- if session.permission_mode in ("plan", "read-only") and session.surface in (
- "jarvis",
- "society",
- ):
- from .control import supports_restricted_turn
-
- if not supports_restricted_turn(session):
- raise ValueError("This runner cannot enforce read-only mode; choose an API model")
- if incoming is not None:
- receipt = await self.receive_message(session_id, incoming)
- if receipt["status"] == "delivered":
- return str(receipt.get("turn_id") or "")
- if receipt["status"] == "failed":
- raise ValueError("This internal message already failed")
- if self.is_running(session_id):
+ if session_id in self._preparing:
raise SessionBusy(session_id)
- kit = kit_for(session.surface)
- text = text.strip()
- attached = chat_attachments.to_analysis(attachments)
- if not text and not attached:
- raise ValueError("empty message")
- # What the turn receives; ``text`` stays what the person typed so the
- # timeline shows their sentence rather than a page of extracted PDF.
- prompt = chat_attachments.compose(text, attached)
- # Agent cards serialize Add selections as capability pins. Translate the
- # browser pin to the same validated receipt used by the root composer.
- if session.surface == "jarvis" and any(
- "core:browser" in {item.strip() for item in match.split(",")}
- for match in re.findall(r"(?m)^\[tools:\s*([^\]\r\n]+)\]\s*$", text)
- ):
- tool_choices = list(dict.fromkeys([*(tool_choices or []), "tool:society_browser"]))
- selected = []
- if tool_choices:
- if session.surface != "jarvis":
- raise ValueError("Tool selections are supported by the Jarvis chat")
- from jarvis.agent_chat.runner_brain import brain_manager
- from jarvis.agent_chat.tool_catalog import live_catalog, resolve_choices
-
- inventory = await asyncio.to_thread(
- live_catalog, brain_manager(), cwd=session.cwd, stance=session.permission_mode
+ if self.is_running(session_id):
+ # A person may steer an active Jarvis goal: user_message pauses
+ # its old turn before this preparation can become a new runner.
+ goal = (
+ self._controls.state(session_id).goal
+ if session.surface == "jarvis"
+ and direct_user
+ and incoming is None
+ and not control_owned
+ and hasattr(self, "_controls")
+ else None
)
- selected = resolve_choices(tool_choices, inventory)
- # Discovery yields; another send may have acquired this session.
- if self.is_running(session_id):
+ if goal is None or goal.status != "active":
raise SessionBusy(session_id)
+ if session.surface == "society":
+ from jarvis.society.chat_binding import direct_chat_owner
+ owner = direct_chat_owner(session_id)
+ if owner is not None and any(
+ direct_chat_owner(sid) == owner for sid in self.running_session_ids()
+ ):
+ raise SessionBusy(session_id)
turn_id = uuid.uuid4().hex
cancel = asyncio.Event()
run = _Running(turn_id, cancel)
- self._running[session_id] = run
- if session.surface == "jarvis" and direct_user and incoming is None and not control_owned:
- from .store import ChatSelection
+ self._preparing[session_id] = run
+ control_revision: int | None = None
+ control_text = text
+ if (
+ session.surface in ("jarvis", "society")
+ and direct_user
+ and incoming is None
+ and not control_owned
+ ):
+ if hasattr(self, "_controls"):
+ try:
+ control_revision = await self._controls.user_message(session_id, text)
+ except (asyncio.CancelledError, Exception):
+ if self._preparing.get(session_id) is run:
+ self._preparing.pop(session_id, None)
+ run.ready.set()
+ raise
+ try:
+ if read_only:
+ session = replace(session, permission_mode="plan")
+ if session.permission_mode in ("plan", "read-only") and session.surface in (
+ "jarvis",
+ "society",
+ ):
+ from .control import supports_restricted_turn
+
+ if not supports_restricted_turn(session):
+ raise ValueError(
+ "This runner cannot enforce read-only mode; choose an API model"
+ )
+ if incoming is not None:
+ receipt = await self.receive_message(session_id, incoming)
+ if receipt["status"] == "delivered":
+ if self._preparing.get(session_id) is run:
+ self._preparing.pop(session_id, None)
+ run.ready.set()
+ return str(receipt.get("turn_id") or "")
+ if receipt["status"] == "failed":
+ raise ValueError("This internal message already failed")
+ if self.is_running(session_id):
+ raise SessionBusy(session_id)
+ kit = kit_for(session.surface)
+ text = text.strip()
+ attached = chat_attachments.to_analysis(attachments)
+ if not text and not attached:
+ raise ValueError("empty message")
+ # What the turn receives; ``text`` stays what the person typed so the
+ # timeline shows their sentence rather than a page of extracted PDF.
+ prompt = chat_attachments.compose(text, attached)
+ # Agent cards serialize Add selections as capability pins. Translate the
+ # browser pin to the same validated receipt used by the root composer.
+ if session.surface == "jarvis" and any(
+ "core:browser" in {item.strip() for item in match.split(",")}
+ for match in re.findall(r"(?m)^\[tools:\s*([^\]\r\n]+)\]\s*$", text)
+ ):
+ tool_choices = list(dict.fromkeys([*(tool_choices or []), "tool:society_browser"]))
+ selected = []
+ if tool_choices:
+ if session.surface != "jarvis":
+ raise ValueError("Tool selections are supported by the Jarvis chat")
+ from jarvis.agent_chat.runner_brain import brain_manager
+ from jarvis.agent_chat.tool_catalog import live_catalog, resolve_choices
+
+ inventory = await asyncio.to_thread(
+ live_catalog, brain_manager(), cwd=session.cwd, stance=session.permission_mode
+ )
+ selected = resolve_choices(tool_choices, inventory)
+ # Discovery yields; another send may have acquired this session.
+ if self.is_running(session_id):
+ raise SessionBusy(session_id)
+
+ # Roster state can change while a control message or an internal
+ # delivery is being recorded. Rebind after those awaits, then reserve
+ # the seat without yielding again. Keep the caller's read-only choice.
+ if session.surface == "society":
+ session = await self.bind_society_session(session_id, routine_run=routine_run)
+ if read_only:
+ session = replace(session, permission_mode="plan")
+ if session.permission_mode in ("plan", "read-only"):
+ from .control import supports_restricted_turn
+
+ if not supports_restricted_turn(session):
+ raise ValueError(
+ "This runner cannot enforce read-only mode; choose an API model"
+ )
- self.store.save_chat_selection(
- ChatSelection(session.provider, session.model, session.effort, session.account_id)
- )
- from jarvis.core.tool_read_only import set_chat_read_only
+ # Revalidate after the last await, then transfer the reservation
+ # to the runner without yielding. Scheduled runs stay independent.
+ if cancel.is_set():
+ raise asyncio.CancelledError
+ if self._preparing.get(session_id) is not run or self.is_running(session_id):
+ raise SessionBusy(session_id)
+ if session.surface == "society":
+ from jarvis.society.chat_binding import direct_chat_owner
+
+ owner = direct_chat_owner(session_id)
+ if owner is not None and any(
+ direct_chat_owner(sid) == owner and self.is_running(sid)
+ for sid in self._running if sid != session_id
+ ):
+ raise SessionBusy(session_id)
+
+ self._preparing.pop(session_id, None)
+ self._running[session_id] = run
+ except (asyncio.CancelledError, Exception):
+ if self._preparing.get(session_id) is run:
+ self._preparing.pop(session_id, None)
+ try:
+ if control_revision is not None:
+ await self._controls.message_rejected(
+ session_id, control_text, control_revision
+ )
+ except Exception:
+ log.exception(
+ "chat control status could not close rejected message in %s", session_id
+ )
+ finally:
+ run.ready.set()
+ raise
+ turn_started_emitted = False
+ try:
+ if (
+ session.surface == "jarvis"
+ and direct_user
+ and incoming is None
+ and not control_owned
+ ):
+ from .store import ChatSelection
+
+ self.store.save_chat_selection(
+ ChatSelection(
+ session.provider, session.model, session.effort, session.account_id
+ )
+ )
+ from jarvis.core.tool_read_only import set_chat_read_only
- set_chat_read_only(session_id, session.permission_mode in ("plan", "read-only"))
+ set_chat_read_only(session_id, session.permission_mode in ("plan", "read-only"))
- history_start = kit.history_start(session) if kit.history_start is not None else 0
- history = self.store.list_events(session_id, after_seq=history_start)
- if incoming is not None:
- await self.message_status(session_id, incoming.message_id, "delivered", turn_id=turn_id)
- else:
+ history_start = kit.history_start(session) if kit.history_start is not None else 0
+ history = self.store.list_events(session_id, after_seq=history_start)
+ if incoming is not None:
+ await self.message_status(
+ session_id, incoming.message_id, "delivered", turn_id=turn_id
+ )
+ else:
+ await self._emit(
+ session_id,
+ make_event(
+ "user_message",
+ {
+ # The full prompt: this is what was actually sent, and the
+ # API runner rebuilds the conversation from these events —
+ # storing only the sentence would lose the picture on the
+ # NEXT turn (runner_api.messages_from_events).
+ "text": prompt,
+ **({"origin": "control"} if control_owned and not direct_user else {}),
+ **(
+ {"tool_choices": [row.model_dump(mode="json") for row in selected]}
+ if selected
+ else {}
+ ),
+ # What the person typed, when it differs from the prompt.
+ # Absent on an ordinary message, so nothing changes there.
+ **(
+ {"typed": display_text if display_text is not None else text}
+ if attached or display_text is not None
+ else {}
+ ),
+ **(
+ {
+ "attachments": [
+ {
+ "name": item.name,
+ "reference": item.reference,
+ "kind": item.kind,
+ "described_by": item.described_by,
+ "note": item.note,
+ }
+ for item in attached
+ ]
+ }
+ if attached
+ else {}
+ ),
+ },
+ ),
+ )
+ runner = selected_runner or resolve_runner(session.provider, surface=session.surface)
+ turn_started_emitted = True
await self._emit(
session_id,
make_event(
- "user_message",
+ "turn_started",
{
- # The full prompt: this is what was actually sent, and the
- # API runner rebuilds the conversation from these events —
- # storing only the sentence would lose the picture on the
- # NEXT turn (runner_api.messages_from_events).
- "text": prompt,
- **({"origin": "control"} if control_owned and not direct_user else {}),
- **(
- {"tool_choices": [row.model_dump(mode="json") for row in selected]}
- if selected
- else {}
- ),
- # What the person typed, when it differs from the prompt.
- # Absent on an ordinary message, so nothing changes there.
- **(
- {"typed": display_text if display_text is not None else text}
- if attached or display_text is not None
- else {}
- ),
- **(
- {
- "attachments": [
- {
- "name": item.name,
- "reference": item.reference,
- "kind": item.kind,
- "described_by": item.described_by,
- "note": item.note,
- }
- for item in attached
- ]
- }
- if attached
- else {}
- ),
+ "turn_id": turn_id,
+ "provider": session.provider,
+ "model": session.model,
+ # The effort the turn RUNS with. It is the session's own
+ # pick: no surface overrides it any more (the kit's
+ # `effort` went with the setup helper), so reading one off
+ # the kit would only be a way to raise an AttributeError
+ # on every turn.
+ "effort": normalize_effort(session.provider, session.effort),
+ "runner": runner,
+ "surface": session.surface,
},
),
)
- runner = selected_runner or resolve_runner(session.provider, surface=session.surface)
- await self._emit(
- session_id,
- make_event(
- "turn_started",
- {
- "turn_id": turn_id,
- "provider": session.provider,
- "model": session.model,
- # The effort the turn RUNS with. It is the session's own
- # pick: no surface overrides it any more (the kit's
- # `effort` went with the setup helper), so reading one off
- # the kit would only be a way to raise an AttributeError
- # on every turn.
- "effort": normalize_effort(session.provider, session.effort),
- "runner": runner,
- "surface": session.surface,
- },
- ),
- )
- bus = self._bus()
- handle = TurnHandle(
- session=session,
- turn_id=turn_id,
- emit=lambda ev: self._emit(session_id, ev),
- request_approval=lambda call_id, name, args, summary: self._ask(
- session_id, turn_id, call_id, name, args, summary
- ),
- cancel=cancel,
- history=history,
- assistant_name=self._assistant_name(),
- bus=bus,
- surface=session.surface,
- stance=session.permission_mode if kit.uses_stance else "",
- output_language=output_language,
- goal_turn=native_goal,
- control_service=self,
- )
+ bus = self._bus()
+ handle = TurnHandle(
+ session=session,
+ turn_id=turn_id,
+ emit=lambda ev: self._emit(session_id, ev),
+ request_approval=lambda call_id, name, args, summary: self._ask(
+ session_id, turn_id, call_id, name, args, summary
+ ),
+ cancel=cancel,
+ history=history,
+ assistant_name=self._assistant_name(),
+ bus=bus,
+ surface=session.surface,
+ stance=session.permission_mode if kit.uses_stance else "",
+ output_language=output_language,
+ goal_turn=native_goal,
+ control_service=self,
+ )
+ except BaseException as exc:
+ try:
+ if turn_started_emitted:
+ await self._emit(
+ session_id,
+ make_event(
+ "turn_finished",
+ {
+ "turn_id": turn_id,
+ "status": (
+ "cancelled" if isinstance(exc, asyncio.CancelledError)
+ else "error"
+ ),
+ "duration_ms": 0,
+ "usage": {},
+ "error": (
+ None if isinstance(exc, asyncio.CancelledError) else str(exc)
+ ),
+ },
+ ),
+ )
+ except asyncio.CancelledError:
+ pass # A second stop still releases the pending reservation.
+ except Exception:
+ log.exception("agent chat could not close the failed start for %s", turn_id)
+ finally:
+ if self._running.get(session_id) is run:
+ self._running.pop(session_id, None)
+ run.ready.set()
+ from jarvis.core.tool_read_only import set_chat_read_only
+
+ stored_session = self.store.get_session(session_id)
+ set_chat_read_only(
+ session_id,
+ bool(
+ stored_session
+ and stored_session.permission_mode in ("plan", "read-only")
+ ),
+ )
+ if hasattr(self, "_controls"):
+ try:
+ await self._controls.turn_completed(
+ session_id,
+ turn_id,
+ display_text if display_text is not None else text,
+ direct_user and incoming is None,
+ read_only,
+ )
+ except Exception:
+ log.exception("chat completion hook failed for aborted start %s", turn_id)
+ raise
async def _body() -> None:
started = time.monotonic()
@@ -944,7 +1117,8 @@ class AgentChatService:
from jarvis.society.browser.tool import stop_chat_browser
await stop_chat_browser(session_id)
- self._running.pop(session_id, None)
+ if self._running.get(session_id) is run:
+ self._running.pop(session_id, None)
stored_session = self.store.get_session(session_id)
set_chat_read_only(
session_id,
@@ -975,7 +1149,14 @@ class AgentChatService:
session_id, turn_id, origin.user_text, origin.direct_user, read_only
)
- run.task = asyncio.create_task(_body(), name=f"agent-chat-{turn_id[:8]}")
+ try:
+ run.task = asyncio.create_task(_body(), name=f"agent-chat-{turn_id[:8]}")
+ except BaseException:
+ if self._running.get(session_id) is run:
+ self._running.pop(session_id, None)
+ run.ready.set()
+ raise
+ run.ready.set()
return turn_id
# ------------------------------------------------------------ voice chat
@@ -1154,13 +1335,19 @@ class AgentChatService:
def signal_cancel(self, session_id: str, *, expected_turn_id: str | None = None) -> bool:
"""Stop planning synchronously before releasing an in-flight tool reply."""
- run = self._running.get(session_id)
- if run is None or run.task is None or run.task.done():
+ run = self._running.get(session_id) or getattr(self, "_preparing", {}).get(session_id)
+ if run is None or (run.task is not None and run.task.done()):
+ return False
+ if run.task is None and run.setup_task is _current_task():
+ # A goal's user_message pauses its old work while preparing this
+ # very send. That pause must not cancel the new send itself.
return False
# A resumed station must never cancel a newer unrelated conversation turn.
if expected_turn_id is not None and run.turn_id != expected_turn_id:
return False
run.cancel.set()
+ if run.task is None and run.setup_task is not None:
+ run.setup_task.cancel()
for aid in self.pending_approvals(session_id):
fut = self._approvals.get(aid)
if fut is not None and not fut.done():
@@ -1169,10 +1356,20 @@ class AgentChatService:
return True
async def cancel(self, session_id: str, *, expected_turn_id: str | None = None) -> bool:
- run = self._running.get(session_id)
+ run = self._running.get(session_id) or self._preparing.get(session_id)
if not self.signal_cancel(session_id, expected_turn_id=expected_turn_id):
return False
- assert run is not None and run.task is not None
+ assert run is not None
+ if run.task is None:
+ try:
+ await asyncio.wait_for(run.ready.wait(), timeout=15.0)
+ except TimeoutError:
+ # Keep the seat reserved until the cancelled setup actually
+ # unwinds; releasing it here could admit a second runner.
+ log.warning("agent chat setup did not stop within 15 seconds: %s", session_id)
+ return True
+ if run.task is None:
+ return True
try:
await asyncio.wait_for(asyncio.shield(run.task), timeout=15.0)
except TimeoutError: # Stop escalates to task cancellation after the bounded wait.
@@ -1189,7 +1386,7 @@ class AgentChatService:
async def cancel_all(self) -> None:
if hasattr(self, "_controls"):
await self._controls.close()
- for sid in list(self._running):
+ for sid in list(dict.fromkeys([*self._running, *self._preparing])):
await self.cancel(sid)
@property
@@ -1201,7 +1398,9 @@ class AgentChatService:
return self._controls
async def wait_turn(self, session_id: str) -> None:
- run = self._running.get(session_id)
+ run = self._running.get(session_id) or self._preparing.get(session_id)
+ if run is not None and run.task is None:
+ await run.ready.wait()
if run is not None and run.task is not None:
await asyncio.shield(run.task)
diff --git a/jarvis/society/chat_binding.py b/jarvis/society/chat_binding.py
index ba1c2c5a17..384b591a07 100644
--- a/jarvis/society/chat_binding.py
+++ b/jarvis/society/chat_binding.py
@@ -41,6 +41,7 @@ log = logging.getLogger(__name__)
__all__ = [
"SURFACE",
"bind_society_session",
+ "direct_chat_owner",
"ensure_session",
"frame_assignment",
"frame_incoming",
@@ -258,13 +259,22 @@ def _agent_busy(svc: Any, agent: AgentRecord) -> bool:
two message turns never share its seat, workspace and browser at once.
Routine runs are background work and do not hold messages up.
"""
- if svc.is_running(agent.session_id):
- return True
running = getattr(svc, "running_session_ids", None)
if not callable(running):
- return False
- prefix = agent.session_id + PAIR_SESSION_MARKER
- return any(sid.startswith(prefix) for sid in running())
+ return svc.is_running(agent.session_id)
+ return any(direct_chat_owner(sid) == agent.session_id for sid in running())
+
+
+def direct_chat_owner(session_id: str) -> str | None:
+ """Return the shared seat owner for a canonical or conversation chat.
+
+ Scheduled runs intentionally have independent admission and never reserve
+ the direct-chat seat.
+ """
+ if not session_id.startswith("society:") or ":routine:" in session_id:
+ return None
+ return session_id.split(PAIR_SESSION_MARKER, 1)[0]
+
def frame_incoming(env: SocietyEnvelope, sender_name: str) -> str:
"""How a board envelope reads inside the receiving agent's chat."""
diff --git a/jarvis/society/surface.py b/jarvis/society/surface.py
index 40abe8521e..33932527cf 100644
--- a/jarvis/society/surface.py
+++ b/jarvis/society/surface.py
@@ -250,35 +250,40 @@ async def _scoped_tool_for_session(session_id: str, capability: str) -> Tool | N
rt = getattr(state, "society", None) or factory()
state.society = rt
await rt.ensure_started()
+ try:
+ service = rt.chat_service()
+ store = getattr(service, "store", None)
+ session = store.get_session(session_id) if store is not None else None
+ except Exception: # noqa: BLE001 — a missing chat provenance must not offer a tool
+ log.warning("society: scoped chat lookup failed for %s", session_id, exc_info=True)
+ return None
+ if session is None or str(getattr(session, "session_id", "") or "") != session_id:
+ return None
+ surface = str(getattr(session, "surface", "") or "")
agent_id = agent_id_of(session_id)
if agent_id is None:
- service = rt.chat_service()
- session = service.store.get_session(session_id) if service is not None else None
- if session is None or str(session.surface) != "jarvis":
+ if surface != "jarvis":
return None
from .roster import LEAD_AGENT_ID
agent_id = LEAD_AGENT_ID
+ elif surface != SURFACE:
+ return None
agent = await rt.roster.get(agent_id)
if agent is None or str(agent.state) != "active":
return None
- read_only = str(agent.permission_ceiling) == "safe"
- service = rt.chat_service()
- session = None
- if service is not None:
- session = service.store.get_session(session_id)
- if session is None:
- return None
- read_only = session.permission_mode in ("plan", "read-only")
- if read_only and capability != "core:browser":
- return None
+ read_only = str(agent.permission_ceiling) == "safe" or session.permission_mode in (
+ "plan", "read-only"
+ )
+ if read_only and capability != "core:browser":
+ return None
tool: Tool
if capability == "core:browser":
from .browser.tool import BrowserTool
pick = (
(session.provider, session.model)
- if service is not None and getattr(session, "surface", "") == "jarvis"
+ if getattr(session, "surface", "") == "jarvis"
else None
)
tool = cast(
@@ -303,6 +308,8 @@ async def _scoped_tool_for_session(session_id: str, capability: str) -> Tool | N
capability,
_effective_approval_mode(agent, session, _permission_override(rt, session)),
rt,
+ session=session,
+ requires_grant=True,
),
)
@@ -434,12 +441,34 @@ class _GatedTool:
capability_id: str,
approval_mode: str | None,
runtime: Any,
+ *,
+ session: Any = None,
+ requires_grant: bool = False,
) -> None:
self._inner = inner
self._agent = agent
self._capability_id = capability_id
self._approval_mode = approval_mode
self._runtime = runtime
+ self._session = session
+ self._session_id = str(getattr(session, "session_id", "") or "")
+ self._session_surface = str(getattr(session, "surface", "") or "")
+ self._session_mode = str(getattr(session, "permission_mode", "") or "")
+ try:
+ service = runtime.chat_service()
+ store = getattr(service, "store", None)
+ persisted = store.get_session(self._session_id) if store is not None else None
+ except Exception: # noqa: BLE001 — a missing persisted policy must fail closed at execution
+ log.warning("society gate: stored chat lookup failed for %s", inner.name, exc_info=True)
+ persisted = None
+ self._persisted_session_mode = (
+ str(getattr(persisted, "permission_mode", "") or "") if persisted is not None else None
+ )
+ self._permission_override = _permission_override(runtime, session)
+ self._permission_ceiling = str(agent.permission_ceiling)
+ self._require_approval = frozenset(agent.approval_rules.get("require_approval", []))
+ self._always_allow = frozenset(agent.approval_rules.get("always_allow", []))
+ self._requires_grant = requires_grant
self.name = inner.name
self.description = inner.description
self.schema = inner.schema
@@ -448,9 +477,7 @@ class _GatedTool:
def __getattr__(self, item: str) -> Any:
return getattr(self._inner, item)
- def risk_tier_for_args(self, args: dict[str, Any]) -> str | None:
- from .approvals import Verdict, decide
-
+ def _base_tier_for_args(self, args: dict[str, Any]) -> str:
base = str(self.risk_tier or "monitor")
hook = getattr(self._inner, "risk_tier_for_args", None)
if callable(hook):
@@ -461,6 +488,12 @@ class _GatedTool:
own = None
if isinstance(own, str) and own:
base = own
+ return base
+
+ def risk_tier_for_args(self, args: dict[str, Any]) -> str | None:
+ from .approvals import Verdict, decide
+
+ base = self._base_tier_for_args(args)
try:
verdict = decide(
self._agent,
@@ -483,13 +516,85 @@ class _GatedTool:
async def execute(self, args: dict[str, Any], ctx: Any) -> Any:
# The catalog was selected at turn start. A pause or kill switch that
# arrives while the model is thinking must still stop its next call.
- if await self._runtime.store.kill_switch():
+ if self._requires_grant and (
+ self._session is None
+ or not self._session_id
+ or self._session_surface not in (SURFACE, "jarvis")
+ or self._persisted_session_mode is None
+ ):
+ return ToolResult(False, {"reason": "blocked_by_policy"}, "chat provenance unavailable")
+ try:
+ halted = await self._runtime.store.kill_switch()
+ live = await self._runtime.roster.get(self._agent.agent_id)
+ service = self._runtime.chat_service()
+ store = getattr(service, "store", None)
+ session = store.get_session(self._session_id) if store is not None else None
+ except Exception: # noqa: BLE001 — unavailable policy data must not authorize a call
+ log.warning("society gate: live policy lookup failed for %s", self.name, exc_info=True)
+ return ToolResult(
+ False, {"reason": "blocked_by_policy"}, "live permissions unavailable"
+ )
+ if halted:
return ToolResult(False, {"reason": "kill_switch"}, "the society is halted")
- live = await self._runtime.roster.get(self._agent.agent_id)
if live is None or str(live.state) != "active":
return ToolResult(
False, {"reason": "blocked_by_policy"}, "caller is not an active agent"
)
+ if self._session_id and (
+ session is None
+ or str(getattr(session, "session_id", "")) != self._session_id
+ or str(getattr(session, "surface", "") or "") != self._session_surface
+ or str(getattr(session, "permission_mode", "") or "")
+ != self._persisted_session_mode
+ or str(getattr(self._session, "permission_mode", "") or "") != self._session_mode
+ or _permission_override(self._runtime, session) != self._permission_override
+ ):
+ return ToolResult(False, {"reason": "blocked_by_policy"}, "chat permissions changed")
+ if self._session_mode in ("plan", "read-only"):
+ from jarvis.core.tool_read_only import allows_read
+
+ if not allows_read(self._inner, args):
+ return ToolResult(False, {"reason": "blocked_by_policy"}, "read-only turn")
+ if self._requires_grant and self.name not in select_tools(
+ {self.name: self._inner},
+ grant_mode=str(live.grant_mode),
+ grants=live.grants,
+ focus=live.focus,
+ denies=live.denies,
+ ):
+ return ToolResult(False, {"reason": "blocked_by_policy"}, "tool grant was revoked")
+ # A standing "always allow" may be added by the card that approved
+ # this same call. Other permission edits require a fresh executor pass.
+ rules = live.approval_rules
+ if (
+ str(live.permission_ceiling) != self._permission_ceiling
+ or frozenset(rules.get("require_approval", [])) != self._require_approval
+ or not self._always_allow.issubset(rules.get("always_allow", []))
+ or _effective_approval_mode(live, self._session, self._permission_override)
+ != self._approval_mode
+ ):
+ return ToolResult(False, {"reason": "blocked_by_policy"}, "agent permissions changed")
+ from .approvals import Verdict, decide
+
+ try:
+ verdict = decide(
+ live,
+ self._capability_id,
+ self._base_tier_for_args(args),
+ verb=_verb_of(args),
+ approval_mode=_effective_approval_mode(
+ live, self._session, self._permission_override
+ ),
+ )
+ except Exception: # noqa: BLE001 — a broken live policy may not authorize execution
+ log.warning("society gate: live decision failed for %s", self.name, exc_info=True)
+ return ToolResult(
+ False, {"reason": "blocked_by_policy"}, "live permissions unavailable"
+ )
+ if verdict is Verdict.BLOCK:
+ return ToolResult(False, {"reason": "blocked_by_policy"}, "tool class is blocked")
+ if verdict is Verdict.QUEUE and getattr(ctx, "approved_by", None) != "user":
+ return ToolResult(False, {"reason": "blocked_by_policy"}, "fresh approval required")
return await self._inner.execute(args, ctx)
@@ -646,34 +751,38 @@ def society_tool_filter(session: Any) -> Callable[[dict[str, Tool]], dict[str, T
# 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, approval_mode, rt))
+ name: cast(
+ Tool,
+ _GatedTool(
+ tool, agent, cap_id, approval_mode, rt,
+ session=session, requires_grant=True,
+ ),
+ )
for name, tool in picked.items()
if (cap_id := capability_id_for_tool(name)) is not None
}
ordered: dict[str, Tool] = {}
- if approval_mode is not None:
- ordered.update(
- {
- name: cast(
- Tool,
- _GatedTool(
- tool,
- agent,
- capability_id_for_tool(name) or "core:society",
- approval_mode,
- rt,
- ),
- )
- 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(
+ {
+ name: cast(
+ Tool,
+ _GatedTool(
+ tool,
+ agent,
+ capability_id_for_tool(name) or "core:society",
+ approval_mode,
+ rt,
+ session=session,
+ ),
+ )
+ for name, tool in own.items()
+ # A legacy row still needs a live gate if its permissions change
+ # mid-turn. Asking the user is never gated behind its own card.
+ if name != ASK_USER_TOOL_NAME
+ }
+ )
+ if ASK_USER_TOOL_NAME in own:
+ ordered[ASK_USER_TOOL_NAME] = own[ASK_USER_TOOL_NAME]
ordered.update(picked)
return ordered
diff --git a/tests/contract/test_browser_desktop_mcp.py b/tests/contract/test_browser_desktop_mcp.py
index 490deba71c..ff3dd8417c 100644
--- a/tests/contract/test_browser_desktop_mcp.py
+++ b/tests/contract/test_browser_desktop_mcp.py
@@ -89,7 +89,11 @@ async def test_plan_session_gets_readonly_browser_but_not_coding_control(tmp_pat
try:
await rt.roster.create(name="Nala", permission_ceiling="safe")
rt.chat_service = lambda: SimpleNamespace(
- store=SimpleNamespace(get_session=lambda _: SimpleNamespace(permission_mode="plan"))
+ store=SimpleNamespace(
+ get_session=lambda _: SimpleNamespace(
+ session_id="society:nala", surface="society", permission_mode="plan"
+ )
+ )
)
browser = await browser_tool_for_session("society:nala")
assert browser is not None and browser.risk_tier == "safe"
@@ -154,7 +158,11 @@ async def test_root_subscription_browser_uses_chat_model_without_changing_roster
await rt.ensure_started()
seen = []
session = SimpleNamespace(
- surface="jarvis", provider="openai-codex", model="picked-model", permission_mode="ask"
+ session_id="root-chat",
+ surface="jarvis",
+ provider="openai-codex",
+ model="picked-model",
+ permission_mode="ask",
)
rt.chat_service = lambda: SimpleNamespace(store=SimpleNamespace(get_session=lambda _: session))
@@ -167,7 +175,9 @@ async def test_root_subscription_browser_uses_chat_model_without_changing_roster
original = await rt.roster.get(rt.lead_id)
browser = await browser_tool_for_session("root-chat")
assert browser is not None
- result = await browser.execute({"task": "Read the page"}, SimpleNamespace())
+ result = await browser.execute(
+ {"task": "Read the page"}, SimpleNamespace(approved_by="user")
+ )
assert result.success
assert seen == [(rt.lead_id, "openai-codex", "picked-model")]
current = await rt.roster.get(rt.lead_id)
diff --git a/tests/contract/test_society_coding_sessions.py b/tests/contract/test_society_coding_sessions.py
index 13a53e0797..fd2a61014a 100644
--- a/tests/contract/test_society_coding_sessions.py
+++ b/tests/contract/test_society_coding_sessions.py
@@ -7,6 +7,7 @@ from types import SimpleNamespace
import pytest
+from jarvis.agent_chat.store import AgentChatStore
from jarvis.agentic_ide import agent_transcript, control, fleet_actions
from jarvis.agentic_ide import session as sessions
from jarvis.agentic_ide.control import CodingSessionControl
@@ -45,12 +46,24 @@ async def rig(tmp_path, monkeypatch):
gateway = CodingSessionControl(registry)
runtime._coding_sessions = gateway
agent, _ = await runtime.roster.create(name="New coding coordinator", grant_mode="all")
+ chat_store = AgentChatStore(tmp_path / "chat-sessions.sqlite3")
+ chat_store.create_session(
+ provider=agent.provider,
+ model=agent.model,
+ effort="medium",
+ cwd=str(tmp_path),
+ permission_mode=str(agent.approval_mode or "ask"),
+ session_id=agent.session_id,
+ surface="society",
+ )
+ runtime._get_chat = lambda: SimpleNamespace(store=chat_store)
tool = CodingSessionTool(runtime, agent.agent_id)
try:
yield registry, manager, gateway, runtime, tool, agent
finally:
await registry.close_all()
await runtime.close()
+ chat_store.close()
async def open_one(rig, tmp_path, agent="claude"):
@@ -419,11 +432,7 @@ async def test_new_registered_cli_is_discovered_and_can_open(rig, tmp_path, monk
async def test_plan_mode_cannot_use_subscription_gate(rig):
from jarvis.society.surface import coding_tool_for_session
- rig[3]._get_chat = lambda: SimpleNamespace(
- store=SimpleNamespace(
- get_session=lambda session_id: SimpleNamespace(permission_mode="plan"),
- )
- )
+ rig[3].chat_service().store.update_session(rig[5].session_id, permission_mode="plan")
assert await coding_tool_for_session(rig[5].session_id) is None
assert not (await rig[4].execute({"action": "open", "request_id": "plan"}, None)).success
@@ -505,7 +514,7 @@ async def test_jarvis_chat_receives_controller_without_becoming_a_coding_cli(rig
assert "Read" in tools and "coding-session" in tools
result = await tools["coding-session"].execute({
"action": "open", "cwd": str(tmp_path), "agent": "codex", "request_id": "lead-request",
- }, None)
+ }, SimpleNamespace(approved_by="user"))
assert result.success and result.output["agent"] == "codex"
session.permission_mode = "plan"
tools, _ = await kit_payload(session, SimpleNamespace(_config=None))
diff --git a/tests/unit/agent_chat/test_agent_chat_service.py b/tests/unit/agent_chat/test_agent_chat_service.py
index 89d4d85030..218172c9a8 100644
--- a/tests/unit/agent_chat/test_agent_chat_service.py
+++ b/tests/unit/agent_chat/test_agent_chat_service.py
@@ -186,6 +186,63 @@ def test_cancel_ends_the_turn(tmp_path: Path, scripted):
asyncio.run(scenario())
+async def test_failed_turn_setup_releases_pending_reservation(
+ tmp_path: Path, scripted, monkeypatch: pytest.MonkeyPatch,
+):
+ svc = AgentChatService(AgentChatStore(":memory:"))
+ session = svc.create_session(provider="fakeprov", cwd=str(tmp_path))
+ original_emit = svc._emit
+ fail_once = True
+
+ async def failing_emit(session_id, event):
+ nonlocal fail_once
+ await original_emit(session_id, event)
+ if fail_once and event["kind"] == "turn_started":
+ fail_once = False
+ raise RuntimeError("start recorder failed")
+
+ monkeypatch.setattr(svc, "_emit", failing_emit)
+
+ async def fake_runner(_handle, _text):
+ return None
+
+ with pytest.raises(RuntimeError, match="start recorder failed"):
+ await svc.send(session.session_id, "First task", control_runner=fake_runner)
+ assert not svc.is_running(session.session_id)
+ assert svc.running_session_ids() == []
+ assert svc.store.list_events(session.session_id)[-1]["payload"]["status"] == "error"
+
+ await svc.send(session.session_id, "Next task", control_runner=fake_runner)
+ await svc.wait_turn(session.session_id)
+ assert not svc.is_running(session.session_id)
+
+
+async def test_delivered_incoming_receipt_releases_pre_admission_reservation(
+ tmp_path: Path, scripted,
+):
+ from jarvis.society.delivery import IncomingMessage
+
+ svc = AgentChatService(AgentChatStore(":memory:"))
+ session = svc.create_session(provider="fakeprov", cwd=str(tmp_path))
+ incoming = IncomingMessage(
+ message_id="message-1", sender_id="scout", sender_name="Scout",
+ sender_kind="agent", text="Already delivered", prompt="Already delivered",
+ trace_id="trace-1", status="delivered", turn_id="prior-turn",
+ )
+
+ assert await svc.send(session.session_id, "Duplicate", incoming=incoming) == "prior-turn"
+ assert not svc.is_running(session.session_id)
+ assert svc.running_session_ids() == []
+
+ async def fake_runner(_handle, _text):
+ return None
+
+ await svc.send(session.session_id, "New task", control_runner=fake_runner)
+ await svc.wait_turn(session.session_id)
+ assert not svc.is_running(session.session_id)
+
+
def test_provider_error_is_reported_not_raised(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
class Boom:
def __init__(self, model=None):
diff --git a/tests/unit/agent_chat/test_controls.py b/tests/unit/agent_chat/test_controls.py
index 099dc57d71..68767206cc 100644
--- a/tests/unit/agent_chat/test_controls.py
+++ b/tests/unit/agent_chat/test_controls.py
@@ -91,6 +91,24 @@ def request(command: str, arguments: str = "", rid: str = "r1") -> CommandReques
return CommandRequest(command=command, arguments=arguments, request_id=rid)
+async def test_rejected_message_cannot_replace_a_newer_control_status() -> None:
+ svc = FakeService()
+ sid = seat(svc)
+ controls = ChatControls(svc, adapters=[])
+ first_revision = await controls.user_message(sid, "Same text")
+ second_revision = await controls.user_message(sid, "Same text")
+ assert first_revision is not None and second_revision is not None
+ assert second_revision > first_revision
+
+ await controls.message_rejected(sid, "Same text", first_revision)
+ state = controls.state(sid)
+ assert state.last_status == "running"
+ assert state.revision == second_revision
+
+ await controls.message_rejected(sid, "Same text", second_revision)
+ assert controls.state(sid).last_status == "failed"
+
+
def test_plan_build_and_review_preserve_original_permissions_and_history() -> None:
async def scenario() -> None:
svc = FakeService()
diff --git a/tests/unit/society/test_chat_binding.py b/tests/unit/society/test_chat_binding.py
index 395d91d76b..976dd674f2 100644
--- a/tests/unit/society/test_chat_binding.py
+++ b/tests/unit/society/test_chat_binding.py
@@ -404,6 +404,165 @@ async def test_busy_turn_defers_provider_reseat_until_it_finishes(tmp_path: Path
await rt.close()
[email protected]("first_is_pair", [False, True])
+async def test_direct_chats_of_one_agent_share_a_turn_seat(tmp_path: Path, first_is_pair: bool):
+ import asyncio
+
+ from jarvis.agent_chat.service import AgentChatService, SessionBusy
+
+ store = AgentChatStore(tmp_path / "agent_chat.db")
+ svc = AgentChatService(store, assistant_name=lambda: "Test")
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ rt = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg
+ )
+ await rt.ensure_started()
+ entered = asyncio.Event()
+ release = asyncio.Event()
+ try:
+ agent, _ = await rt.roster.create(name="Scout", provider="openai")
+ canonical = ensure_session(svc, cfg, agent)
+ pair = ensure_session(svc, cfg, agent, counterpart="jarvis")
+ first, second = (pair, canonical) if first_is_pair else (canonical, pair)
+
+ async def held_runner(_handle, _text):
+ entered.set()
+ await release.wait()
+
+ await svc.send(
+ first.session_id, "First task", control_runner=held_runner,
+ control_owned=True, direct_user=False,
+ )
+ await asyncio.wait_for(entered.wait(), timeout=3)
+ before = store.list_events(second.session_id)
+ with pytest.raises(SessionBusy):
+ await svc.send(
+ second.session_id, "Concurrent task", control_runner=held_runner,
+ control_owned=True, direct_user=False,
+ )
+ assert store.list_events(second.session_id) == before
+
+ release.set()
+ await svc.wait_turn(first.session_id)
+ await svc.send(
+ second.session_id, "Next task", control_runner=held_runner,
+ control_owned=True, direct_user=False,
+ )
+ await svc.wait_turn(second.session_id)
+ finally:
+ release.set()
+ await svc.cancel_all()
+ await rt.close()
+
+
+async def test_pair_cannot_enter_during_canonical_start_and_stop_releases_seat(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+):
+ import asyncio
+
+ from jarvis.agent_chat.service import AgentChatService, SessionBusy
+
+ store = AgentChatStore(tmp_path / "agent_chat.db")
+ svc = AgentChatService(store, assistant_name=lambda: "Test")
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ rt = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg
+ )
+ await rt.ensure_started()
+ entered = asyncio.Event()
+ release = asyncio.Event()
+ original_emit = svc._emit
+
+ async def held_start(session_id, event):
+ await original_emit(session_id, event)
+ if event["kind"] == "turn_started" and session_id == agent.session_id:
+ entered.set()
+ await release.wait()
+
+ monkeypatch.setattr(svc, "_emit", held_start)
+ try:
+ agent, _ = await rt.roster.create(name="Scout", provider="openai")
+ canonical = ensure_session(svc, cfg, agent)
+ pair = ensure_session(svc, cfg, agent, counterpart="jarvis")
+
+ async def fake_runner(_handle, _text):
+ return None
+
+ sending = asyncio.create_task(svc.send(
+ canonical.session_id, "First task", control_runner=fake_runner,
+ control_owned=True, direct_user=False,
+ ))
+ await asyncio.wait_for(entered.wait(), timeout=3)
+ assert svc.is_running(canonical.session_id)
+ assert canonical.session_id in svc.running_session_ids()
+ with pytest.raises(SessionBusy):
+ await svc.send(
+ pair.session_id, "Concurrent task", control_runner=fake_runner,
+ control_owned=True, direct_user=False,
+ )
+ assert store.list_events(pair.session_id) == []
+
+ assert await svc.cancel(canonical.session_id)
+ with pytest.raises(asyncio.CancelledError):
+ await sending
+ assert not svc.is_running(canonical.session_id)
+ assert store.list_events(canonical.session_id)[-1]["payload"]["status"] == "cancelled"
+
+ await svc.send(
+ pair.session_id, "Next task", control_runner=fake_runner,
+ control_owned=True, direct_user=False,
+ )
+ await svc.wait_turn(pair.session_id)
+ finally:
+ release.set()
+ await svc.cancel_all()
+ await rt.close()
+
+
+async def test_routine_turn_does_not_reserve_direct_chat_seat(tmp_path: Path):
+ import asyncio
+
+ from jarvis.agent_chat.service import AgentChatService
+
+ store = AgentChatStore(tmp_path / "agent_chat.db")
+ svc = AgentChatService(store, assistant_name=lambda: "Test")
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ rt = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg
+ )
+ await rt.ensure_started()
+ entered = asyncio.Event()
+ release = asyncio.Event()
+ try:
+ agent, _ = await rt.roster.create(name="Scout", provider="openai")
+ direct = ensure_session(svc, cfg, agent)
+ routine = store.create_session(
+ session_id=f"{agent.session_id}:routine:task-1:run-1",
+ surface="society", provider="openai", model="", effort="low",
+ cwd=direct.cwd, permission_mode="bypass",
+ )
+
+ async def held_runner(_handle, _text):
+ entered.set()
+ await release.wait()
+
+ await svc.send(
+ direct.session_id, "Direct task", control_runner=held_runner,
+ control_owned=True, direct_user=False,
+ )
+ await asyncio.wait_for(entered.wait(), timeout=3)
+ await svc.send(
+ routine.session_id, "Scheduled task", control_runner=held_runner,
+ control_owned=True, direct_user=False, routine_run=True,
+ )
+ assert svc.is_running(direct.session_id)
+ assert svc.is_running(routine.session_id)
+ finally:
+ release.set()
+ await svc.cancel_all()
+ await rt.close()
+
+
async def test_build_cannot_raise_a_safe_agent_above_its_ceiling(world):
from jarvis.agent_chat.control import ChatControls
from jarvis.agent_chat.control_types import CommandRequest
@@ -511,6 +670,270 @@ async def test_inactive_agent_cannot_bind_canonical_chat(world, blocked_by):
await bind_society_session(svc, agent.session_id)
+ ("blocked_by", "active_goal"), [("paused", True), ("kill_switch", False)]
+)
+async def test_live_roster_change_during_pre_admission_await_blocks_turn(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, blocked_by: str, active_goal: bool,
+):
+ import asyncio
+
+ from jarvis.agent_chat.control_types import GoalState
+ from jarvis.agent_chat.service import AgentChatService
+
+ store = AgentChatStore(tmp_path / "agent_chat.db")
+ svc = AgentChatService(store, assistant_name=lambda: "Test")
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ rt = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg
+ )
+ await rt.ensure_started()
+ entered = asyncio.Event()
+ release = asyncio.Event()
+ sending = None
+ try:
+ agent, _ = await rt.roster.create(name="Scout", provider="openai")
+ session = ensure_session(svc, cfg, agent)
+ controls = svc.controls
+ if active_goal:
+ state = controls.state(session.session_id)
+ state.goal = GoalState(
+ id="goal-1", objective="Keep the task", started_ms=1, updated_ms=1
+ )
+ controls.store.save(state)
+ original_get = rt.roster.get
+ calls = 0
+
+ async def held_second_roster_read(agent_id):
+ nonlocal calls
+ calls += 1
+ if calls == 2:
+ entered.set()
+ await release.wait()
+ return await original_get(agent_id)
+
+ monkeypatch.setattr(rt.roster, "get", held_second_roster_read)
+
+ async def fake_runner(_handle, _text):
+ pytest.fail("a disabled Society agent must never start paid work")
+
+ sending = asyncio.create_task(
+ svc.send(session.session_id, "Task", control_runner=fake_runner)
+ )
+ await asyncio.wait_for(entered.wait(), timeout=3)
+ assert controls.state(session.session_id).last_status == "running"
+ if blocked_by == "paused":
+ await rt.roster.update(agent.agent_id, {"state": "paused"})
+ else:
+ await rt.store.set_kill_switch(True)
+ release.set()
+ with pytest.raises(PermissionError, match="paused or disabled"):
+ await sending
+ assert not svc.is_running(session.session_id)
+ state = controls.state(session.session_id)
+ assert state.last_status == ("interrupted" if active_goal else "failed")
+ if active_goal:
+ assert state.goal is not None
+ assert state.goal.status == "paused"
+ assert state.goal.objective == "Keep the task"
+ assert not any(
+ event["kind"] in ("user_message", "turn_started")
+ for event in store.list_events(session.session_id)
+ )
+ finally:
+ release.set()
+ if sending is not None and not sending.done():
+ sending.cancel()
+ await asyncio.gather(sending, return_exceptions=True)
+ await svc.cancel_all()
+ await rt.close()
+
+
+async def test_final_society_rebind_keeps_read_only_turn_override(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+):
+ import asyncio
+
+ from jarvis.agent_chat.service import AgentChatService
+
+ store = AgentChatStore(tmp_path / "agent_chat.db")
+ svc = AgentChatService(store, assistant_name=lambda: "Test")
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ rt = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg
+ )
+ await rt.ensure_started()
+ entered = asyncio.Event()
+ release = asyncio.Event()
+ observed: list[tuple[str, str]] = []
+
+ async def held_control_message(_sid, _text):
+ entered.set()
+ await release.wait()
+
+ monkeypatch.setattr(svc.controls, "user_message", held_control_message)
+ try:
+ agent, _ = await rt.roster.create(name="Scout", provider="openai")
+ session = ensure_session(svc, cfg, agent)
+
+ async def fake_runner(handle, _text):
+ observed.append((handle.session.permission_mode, handle.stance))
+
+ sending = asyncio.create_task(
+ svc.send(session.session_id, "Read only task", read_only=True,
+ control_runner=fake_runner)
+ )
+ await asyncio.wait_for(entered.wait(), timeout=3)
+ release.set()
+ await sending
+ await svc.wait_turn(session.session_id)
+ assert observed == [("plan", "plan")]
+ assert store.get_session(session.session_id).permission_mode == "bypass"
+ finally:
+ release.set()
+ await svc.cancel_all()
+ await rt.close()
+
+
+async def test_two_sends_cannot_replace_pre_admission_control_owner(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+):
+ import asyncio
+
+ from jarvis.agent_chat.events import make_event
+ from jarvis.agent_chat.service import AgentChatService, SessionBusy
+
+ store = AgentChatStore(tmp_path / "agent_chat.db")
+ svc = AgentChatService(store, assistant_name=lambda: "Test")
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ rt = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg
+ )
+ await rt.ensure_started()
+ entered = asyncio.Event()
+ release = asyncio.Event()
+ finished = asyncio.Event()
+ sending = None
+ try:
+ agent, _ = await rt.roster.create(name="Scout", provider="openai")
+ session = ensure_session(svc, cfg, agent)
+ controls = svc.controls
+ original_completed = controls.turn_completed
+
+ async def mark_completed(*args):
+ await original_completed(*args)
+ finished.set()
+
+ monkeypatch.setattr(controls, "turn_completed", mark_completed)
+ original_get = rt.roster.get
+ calls = 0
+
+ async def held_second_roster_read(agent_id):
+ nonlocal calls
+ calls += 1
+ if calls == 2:
+ entered.set()
+ await release.wait()
+ return await original_get(agent_id)
+
+ monkeypatch.setattr(rt.roster, "get", held_second_roster_read)
+
+ async def fake_runner(handle, _text):
+ await handle.emit(make_event(
+ "turn_finished", {"turn_id": handle.turn_id, "status": "done"}
+ ))
+
+ sending = asyncio.create_task(
+ svc.send(session.session_id, "Task A", control_runner=fake_runner)
+ )
+ await asyncio.wait_for(entered.wait(), timeout=3)
+ assert controls.state(session.session_id).last_request == "Task A"
+ with pytest.raises(SessionBusy):
+ await svc.send(session.session_id, "Task B", control_runner=fake_runner)
+ assert controls.state(session.session_id).last_request == "Task A"
+
+ release.set()
+ await sending
+ await asyncio.wait_for(finished.wait(), timeout=3)
+ state = controls.state(session.session_id)
+ assert state.last_request == "Task A"
+ assert state.last_status == "done"
+ assert not any(
+ event["kind"] == "user_message"
+ and event["payload"].get("text") == "Task B"
+ for event in store.list_events(session.session_id)
+ )
+ finally:
+ release.set()
+ if sending is not None and not sending.done():
+ sending.cancel()
+ await asyncio.gather(sending, return_exceptions=True)
+ await svc.cancel_all()
+ await rt.close()
+
+
+async def test_stop_during_final_roster_lookup_prevents_a_runner(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+):
+ import asyncio
+
+ from jarvis.agent_chat.service import AgentChatService
+
+ store = AgentChatStore(tmp_path / "agent_chat.db")
+ svc = AgentChatService(store, assistant_name=lambda: "Test")
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ rt = SocietyRuntime(
+ tmp_path, seed_starter_team=False, chat_service=lambda: svc, cfg=lambda: cfg
+ )
+ await rt.ensure_started()
+ entered = asyncio.Event()
+ release = asyncio.Event()
+ sending = None
+ try:
+ agent, _ = await rt.roster.create(name="Scout", provider="openai")
+ session = ensure_session(svc, cfg, agent)
+ controls = svc.controls
+ original_get = rt.roster.get
+ calls = 0
+
+ async def held_second_roster_read(agent_id):
+ nonlocal calls
+ calls += 1
+ if calls == 2:
+ entered.set()
+ await release.wait()
+ return await original_get(agent_id)
+
+ monkeypatch.setattr(rt.roster, "get", held_second_roster_read)
+
+ async def fake_runner(_handle, _text):
+ pytest.fail("Stop must prevent the runner from starting")
+
+ sending = asyncio.create_task(
+ svc.send(session.session_id, "Task", control_runner=fake_runner)
+ )
+ await asyncio.wait_for(entered.wait(), timeout=3)
+ assert controls.state(session.session_id).last_status == "running"
+ assert svc.is_running(session.session_id)
+ await controls.pause(session.session_id, "Stopped by the user")
+ release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await sending
+ assert not svc.is_running(session.session_id)
+ assert controls.state(session.session_id).last_status == "interrupted"
+ assert not any(
+ event["kind"] == "turn_started"
+ for event in store.list_events(session.session_id)
+ )
+ finally:
+ release.set()
+ if sending is not None and not sending.done():
+ sending.cancel()
+ await asyncio.gather(sending, return_exceptions=True)
+ await svc.cancel_all()
+ await rt.close()
+
+
async def test_roster_mode_edit_defers_busy_chat_and_preserves_override(world, monkeypatch):
from jarvis.ui.web.society_routes import router
diff --git a/tests/unit/society/test_surface.py b/tests/unit/society/test_surface.py
index 182938c957..41327490bd 100644
--- a/tests/unit/society/test_surface.py
+++ b/tests/unit/society/test_surface.py
@@ -3,12 +3,14 @@
from __future__ import annotations
import asyncio
+from dataclasses import replace
from pathlib import Path
from types import SimpleNamespace
import pytest
from jarvis.agent_chat.approval_bridge import ChatApprovalBridge, ChatGrant, approval_ref
+from jarvis.agent_chat.store import AgentChatStore
from jarvis.core.bus import EventBus
from jarvis.core.config import SafetyConfig
from jarvis.core.protocols import ToolResult
@@ -30,8 +32,10 @@ from jarvis.society.runtime import SocietyRuntime
from jarvis.society.shell import ShellResult
from jarvis.society.surface import (
agent_id_of,
+ browser_tool_for_session,
build_briefing,
capability_epoch,
+ coding_tool_for_session,
society_system_extra,
society_tool_filter,
society_tools,
@@ -64,6 +68,23 @@ async def rt(tmp_path: Path):
await runtime.close()
+def _live_chat(rt: SocietyRuntime, session: SimpleNamespace):
+ session.surface = "society"
+
+ class Store:
+ live = session
+
+ def get_session(self, session_id: str):
+ return self.live if self.live.session_id == session_id else None
+
+ def permission_override(self, _session_id: str) -> str:
+ return ""
+
+ store = Store()
+ rt._get_chat = lambda: SimpleNamespace(store=store) # noqa: SLF001 — live store seam
+ return store
+
+
async def test_task_execution_contract_survives_long_memory_and_compact_transport(rt):
from jarvis.agent_chat.jarvis_harness import SYSTEM_PREAMBLE, compact_identity
@@ -91,6 +112,40 @@ def test_without_runtime_everything_is_empty():
assert society_tool_filter(session) is None
+async def test_scoped_hands_require_a_live_chat_record(rt: SocietyRuntime):
+ await rt.roster.create(name="Mailer", approval_mode="bypass")
+ for session_id in ("society:mailer", "jarvis-chat"):
+ assert await coding_tool_for_session(session_id) is None
+ assert await browser_tool_for_session(session_id) is None
+
+ rt._get_chat = lambda: SimpleNamespace( # noqa: SLF001 — missing-record seam
+ store=SimpleNamespace(get_session=lambda _session_id: None)
+ )
+ for session_id in ("society:mailer", "jarvis-chat"):
+ assert await coding_tool_for_session(session_id) is None
+ assert await browser_tool_for_session(session_id) is None
+
+
+async def test_granted_hand_fails_closed_without_chat_provenance(rt: SocietyRuntime):
+ await rt.roster.create(name="Mailer", approval_mode="bypass")
+ session = SimpleNamespace(session_id="society:mailer", surface="society")
+ await society_system_extra(None, None, session)
+ calls: list[dict] = []
+
+ async def execute(args: dict, _ctx: object) -> ToolResult:
+ calls.append(args)
+ return ToolResult(True, "ok", None)
+
+ tool = _tool("gmail")
+ tool.execute = execute
+ filt = society_tool_filter(session)
+ assert filt is not None
+ gated = filt({"gmail": tool})["gmail"]
+ result = await gated.execute({"action": "list"}, SimpleNamespace(approved_by="auto"))
+ assert not result.success and result.output["reason"] == "blocked_by_policy"
+ assert calls == []
+
+
async def test_tools_and_filter_follow_the_roster_row(rt: SocietyRuntime, tmp_path: Path):
await rt.roster.create(
name="Mailbox",
@@ -235,12 +290,12 @@ async def test_a_granted_tool_is_gated_by_the_agents_rules(rt: SocietyRuntime, t
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.
+ # A pre-migration row keeps its ceiling policy, but its own hands still
+ # need a live wrapper so later roster changes cannot bypass the gate.
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 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.
@@ -262,6 +317,7 @@ async def test_bound_chat_always_ask_cards_a_safe_read(rt: SocietyRuntime, tmp_p
session = SimpleNamespace(
session_id="society:reader", permission_mode="always_ask", cwd=str(workspace)
)
+ _live_chat(rt, session)
cfg = SimpleNamespace(wiki=SimpleNamespace(vault_root=str(tmp_path / "vault")))
await society_system_extra(cfg, None, session)
filt = society_tool_filter(session)
@@ -334,6 +390,7 @@ async def test_bound_chat_ask_gates_monitor_without_widening_roster(rt: SocietyR
async def test_in_flight_tool_stops_after_kill_or_agent_pause(rt: SocietyRuntime):
await rt.roster.create(name="Mailer", approval_mode="bypass")
session = SimpleNamespace(session_id="society:mailer", permission_mode="bypass")
+ _live_chat(rt, session)
await society_system_extra(None, None, session)
calls: list[dict] = []
@@ -358,12 +415,244 @@ async def test_in_flight_tool_stops_after_kill_or_agent_pause(rt: SocietyRuntime
assert calls == [{"action": "list"}]
+async def test_in_flight_grant_revocation_blocks_after_chat_approval(rt: SocietyRuntime):
+ await rt.roster.create(
+ name="Mailer", grant_mode="allowlist", grants=["plugin:gmail"],
+ approval_mode="always_ask",
+ )
+ session = SimpleNamespace(session_id="society:mailer", permission_mode="always_ask")
+ _live_chat(rt, session)
+ await society_system_extra(None, None, session)
+ calls: list[dict] = []
+
+ async def execute(args: dict, _ctx: object) -> ToolResult:
+ calls.append(args)
+ return ToolResult(True, "sent", None)
+
+ tool = _tool("gmail")
+ tool.execute = execute
+ filt = society_tool_filter(session)
+ assert filt is not None
+ gated = filt({"gmail": tool})["gmail"]
+ bus = EventBus()
+ executor = ToolExecutor(bus, RiskTierEvaluator(SafetyConfig()), ApprovalWorkflow(bus))
+ bridge = ChatApprovalBridge(bus)
+ asked = asyncio.Event()
+ release = asyncio.Event()
+ cards: list[str] = []
+
+ async def card(_call_id: str, name: str, _args: dict, _summary: str) -> str:
+ cards.append(name)
+ asked.set()
+ await release.wait()
+ return "allow"
+
+ ref = approval_ref(session.session_id)
+ bridge.arm(
+ ref,
+ ChatGrant(
+ session_id=session.session_id,
+ turn_id="turn-1",
+ stance="always_ask",
+ always_allowed=set(),
+ ask=card,
+ ),
+ )
+ running = asyncio.create_task(
+ executor.execute(
+ gated,
+ {"action": "send"},
+ config_snapshot={
+ "approval_surface": "interactive", "approval_ref": ref,
+ "approval_timeout_s": 5,
+ },
+ )
+ )
+ try:
+ await asyncio.wait_for(asked.wait(), timeout=5)
+ await rt.roster.update("mailer", {"grants": []})
+ finally:
+ release.set()
+ result = await asyncio.wait_for(running, timeout=5)
+ assert not result.success and result.output["reason"] == "blocked_by_policy"
+ assert cards == ["gmail"] and calls == []
+
+
+async def test_in_flight_policy_changes_block_stale_auto_grant(rt: SocietyRuntime):
+ await rt.roster.create(name="Mailer", approval_mode="bypass")
+ session = SimpleNamespace(session_id="society:mailer", permission_mode="bypass")
+ _live_chat(rt, session)
+ await society_system_extra(None, None, session)
+ calls: list[dict] = []
+
+ async def execute(args: dict, _ctx: object) -> ToolResult:
+ calls.append(args)
+ return ToolResult(True, "ok", None)
+
+ tool = _tool("gmail")
+ tool.execute = execute
+ ctx = SimpleNamespace(approved_by="auto")
+
+ def offered():
+ filt = society_tool_filter(session)
+ assert filt is not None
+ return filt({"gmail": tool})["gmail"]
+
+ gated = offered()
+ assert gated.risk_tier_for_args({"action": "list"}) == "monitor"
+ await rt.roster.update("mailer", {"approval_mode": "ask"})
+ changed_mode = await gated.execute({"action": "list"}, ctx)
+ assert not changed_mode.success and changed_mode.output["reason"] == "blocked_by_policy"
+
+ await society_system_extra(None, None, session)
+ gated = offered()
+ await rt.roster.update(
+ "mailer", {"approval_rules": {"require_approval": ["plugin:gmail"], "always_allow": []}}
+ )
+ changed_rule = await gated.execute({"action": "list"}, ctx)
+ assert not changed_rule.success and changed_rule.output["reason"] == "blocked_by_policy"
+
+ await society_system_extra(None, None, session)
+ gated = offered()
+ session.permission_mode = "always_ask"
+ changed_session = await gated.execute({"action": "list"}, ctx)
+ assert not changed_session.success and changed_session.output["reason"] == "blocked_by_policy"
+
+ session.permission_mode = "bypass"
+ await rt.roster.update(
+ "mailer",
+ {"approval_mode": "bypass", "approval_rules": {"require_approval": [], "always_allow": []}},
+ )
+ await society_system_extra(None, None, session)
+ gated = offered()
+ await rt.roster.update("mailer", {"permission_ceiling": "safe"})
+ changed_ceiling = await gated.execute({"action": "list"}, ctx)
+ assert not changed_ceiling.success and changed_ceiling.output["reason"] == "blocked_by_policy"
+ assert calls == []
+
+
+async def test_live_session_record_can_revoke_an_offered_tool(rt: SocietyRuntime):
+ await rt.roster.create(name="Mailer", approval_mode="bypass")
+ session = SimpleNamespace(
+ session_id="society:mailer", permission_mode="bypass", surface="society"
+ )
+ await society_system_extra(None, None, session)
+ calls: list[dict] = []
+
+ async def execute(args: dict, _ctx: object) -> ToolResult:
+ calls.append(args)
+ return ToolResult(True, "ok", None)
+
+ tool = _tool("gmail")
+ tool.execute = execute
+ class Store:
+ live = SimpleNamespace(
+ session_id="society:mailer", permission_mode="bypass", surface="society"
+ )
+
+ def get_session(self, _session_id: str):
+ return self.live
+
+ def permission_override(self, _session_id: str) -> str:
+ return ""
+
+ store = Store()
+ rt._get_chat = lambda: SimpleNamespace(store=store) # noqa: SLF001 — live store seam
+ filt = society_tool_filter(session)
+ assert filt is not None
+ gated = filt({"gmail": tool})["gmail"]
+ ctx = SimpleNamespace(approved_by="auto")
+ assert (await gated.execute({"action": "list"}, ctx)).success
+ store.live = SimpleNamespace(
+ session_id="society:mailer", permission_mode="ask", surface="society"
+ )
+ changed = await gated.execute({"action": "list"}, ctx)
+ assert not changed.success and changed.output["reason"] == "blocked_by_policy"
+ store.live = None
+ removed = await gated.execute({"action": "list"}, ctx)
+ assert not removed.success and removed.output["reason"] == "blocked_by_policy"
+ assert calls == [{"action": "list"}]
+
+
+async def test_ephemeral_read_only_turn_checks_saved_mode_without_blocking_reads(
+ rt: SocietyRuntime, tmp_path: Path
+):
+ await rt.roster.create(name="Reader", approval_mode="bypass")
+ store = AgentChatStore(tmp_path / "chat.sqlite")
+ try:
+ saved = store.create_session(
+ session_id="society:reader", surface="society", provider="test",
+ model="test", effort="", cwd=str(tmp_path), permission_mode="ask",
+ )
+ turn = replace(saved, permission_mode="plan")
+ rt._get_chat = lambda: SimpleNamespace(store=store) # noqa: SLF001 — persisted chat seam
+ await society_system_extra(None, None, turn)
+ calls: list[str] = []
+
+ def offered(name: str, read_only: bool, risk_tier: str):
+ async def execute(_args: dict, _ctx: object) -> ToolResult:
+ calls.append(name)
+ return ToolResult(True, "ok", None)
+
+ return SimpleNamespace(
+ name=name, description="x.", schema={}, risk_tier=risk_tier,
+ read_only=read_only, execute=execute,
+ )
+
+ filt = society_tool_filter(turn)
+ assert filt is not None
+ picked = filt({
+ "society_memory_recall": offered("society_memory_recall", True, "safe"),
+ "society_wiki_note": offered("society_wiki_note", False, "monitor"),
+ })
+ ctx = SimpleNamespace(approved_by="auto")
+ read = picked["society_memory_recall"]
+ assert (await read.execute({}, ctx)).success
+ write = await picked["society_wiki_note"].execute({}, ctx)
+ assert not write.success and write.output["reason"] == "blocked_by_policy"
+ assert calls == ["society_memory_recall"]
+
+ store.update_session(saved.session_id, permission_mode="bypass")
+ changed = await read.execute({}, ctx)
+ assert not changed.success and changed.output["reason"] == "blocked_by_policy"
+ assert calls == ["society_memory_recall"]
+ finally:
+ store.close()
+
+
+async def test_legacy_own_hand_stops_when_roster_tightens_mid_turn(rt: SocietyRuntime):
+ await rt.roster.create(name="Courier", approval_mode="bypass")
+ await rt.store.update_agent("courier", {"approval_mode": None})
+ session = SimpleNamespace(session_id="society:courier", permission_mode="bypass")
+ _live_chat(rt, session)
+ await society_system_extra(None, None, session)
+ calls: list[str] = []
+
+ async def execute(_args: dict, _ctx: object) -> ToolResult:
+ calls.append("sent")
+ return ToolResult(True, "ok", None)
+
+ own = SimpleNamespace(
+ name=MESSAGE_TOOL_NAME, description="x.", schema={}, risk_tier="safe",
+ execute=execute,
+ )
+ filt = society_tool_filter(session)
+ assert filt is not None
+ gated = filt({MESSAGE_TOOL_NAME: own})[MESSAGE_TOOL_NAME]
+ assert hasattr(gated, "_capability_id")
+ await rt.roster.update("courier", {"approval_mode": "always_ask"})
+ blocked = await gated.execute({}, SimpleNamespace(approved_by="auto"))
+ assert not blocked.success and blocked.output["reason"] == "blocked_by_policy"
+ assert calls == []
+
+
async def test_shell_uses_one_chat_approval_for_one_command(rt: SocietyRuntime, tmp_path: Path):
await rt.roster.create(name="Runner", approval_mode="ask")
workspace = tmp_path / "workspace"
session = SimpleNamespace(
session_id="society:runner", permission_mode="ask", cwd=str(workspace)
)
+ _live_chat(rt, session)
await society_system_extra(None, None, session)
from jarvis.society.agent_tools import ShellTool