Skip to content

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

feat(society): the society chat surface, canonical chat binding and agent tools

rubenluetke10-beep61888d0bd23b
diff --git a/jarvis/agent_chat/runner_brain.py b/jarvis/agent_chat/runner_brain.py
index 482ac4403c..7e0006d1ca 100644
--- a/jarvis/agent_chat/runner_brain.py
+++ b/jarvis/agent_chat/runner_brain.py
@@ -161,7 +161,9 @@ def build_override(
dict(kit_tools) if kit_tools is not None else folder_tools(cwd, stance=stance)
),
tool_filter=_compose_filters(
- kit.tool_filter, plan_filter if stance == PLAN_STANCE else None
+ kit.tool_filter,
+ kit.session_tool_filter(session) if kit.session_tool_filter is not None else None,
+ plan_filter if stance == PLAN_STANCE else None,
),
credential_scope=kit.credential_scope,
system_extra=system_extra,
@@ -206,13 +208,26 @@ async def kit_payload(session: AgentChatSession, brain: Any) -> tuple[dict[str,
cfg = getattr(brain, "_config", None)
tools: dict[str, Tool] | None = None
extra = ""
- if kit.tools is not None:
+ if kit.session_tools is not None:
+ try:
+ tools = kit.session_tools(cfg, brain, session)
+ except Exception as exc: # noqa: BLE001 - the turn runs without the kit's hands
+ log.warning("surface %s: kit tools not built: %s", session.surface, exc, exc_info=True)
+ tools = {}
+ elif kit.tools is not None:
try:
tools = kit.tools(cfg, brain)
except Exception as exc: # noqa: BLE001 — the turn runs without the kit's hands
log.warning("surface %s: kit tools not built: %s", session.surface, exc, exc_info=True)
tools = {}
- if kit.system_extra is not None:
+ if kit.session_system_extra is not None:
+ try:
+ extra = await kit.session_system_extra(cfg, brain, session)
+ except Exception as exc: # noqa: BLE001 - the turn runs without the briefing
+ log.warning(
+ "surface %s: kit briefing not built: %s", session.surface, exc, exc_info=True
+ )
+ elif kit.system_extra is not None:
try:
extra = await kit.system_extra(cfg, brain)
except Exception as exc: # noqa: BLE001 — the turn runs without the briefing
diff --git a/jarvis/agent_chat/store.py b/jarvis/agent_chat/store.py
index 29706a080b..b9d3977a21 100644
--- a/jarvis/agent_chat/store.py
+++ b/jarvis/agent_chat/store.py
@@ -74,8 +74,10 @@ _PREVIEW_MAX_CHARS = 120
#: ``tests/unit/agent_chat/test_agent_chat_surface_parity.py`` keeps the three
#: in step (AP-4). ``"local-models"`` is the Local models section's setup
#: assistant: one session per install, its own hands, never in either chat's
-#: session list.
-SURFACES: Final[tuple[str, ...]] = ("jarvis", "agent", "local-models")
+#: session list. ``"society"`` is an agent's one canonical chat (session id
+#: ``society:<agent_id>``, see ``jarvis/society/chat_binding.py``): Jarvis'
+#: brain runner with the agent's own hands, listed only inside the society.
+SURFACES: Final[tuple[str, ...]] = ("jarvis", "agent", "local-models", "society")
DEFAULT_SURFACE: Final[str] = "agent"
diff --git a/jarvis/agent_chat/surface_kits.py b/jarvis/agent_chat/surface_kits.py
index dbc6568379..ee30bf3767 100644
--- a/jarvis/agent_chat/surface_kits.py
+++ b/jarvis/agent_chat/surface_kits.py
@@ -35,6 +35,12 @@ _JARVIS_LADDER: Final[str] = "jarvis"
ToolsBuilder = Callable[[Any, Any], dict[str, Tool]]
ExtraBuilder = Callable[[Any, Any], Awaitable[str]]
+#: Session-aware twins: ``(cfg, brain, session)``. A surface whose hands and
+#: briefing depend on WHICH session is talking (one chat per society agent)
+#: uses these; ``kit_payload`` prefers them over the session-blind builders.
+SessionToolsBuilder = Callable[[Any, Any, Any], dict[str, Tool]]
+SessionExtraBuilder = Callable[[Any, Any, Any], Awaitable[str]]
+SessionFilterBuilder = Callable[[Any], Callable[[dict[str, Tool]], dict[str, Tool]] | None]
@dataclass(frozen=True, slots=True)
@@ -87,6 +93,11 @@ class SurfaceKit:
#: which is what the IDE's chat wants: a coding agent is pointed at a
#: project, and its composer shows the folder chip so it can be moved.
workspace_dir: Callable[[], Path] | None = None
+ #: Session-aware builders (see the type aliases above). ``None`` = use the
+ #: session-blind ``tools`` / ``system_extra`` / ``tool_filter``.
+ session_tools: SessionToolsBuilder | None = None
+ session_system_extra: SessionExtraBuilder | None = None
+ session_tool_filter: SessionFilterBuilder | None = None
def _chat_workspace() -> Path:
@@ -117,6 +128,27 @@ async def _local_models_extra(cfg: Any, _brain: Any) -> str:
return await build_system_extra(cfg, root=server_root(cfg))
+def _society_tools(cfg: Any, brain: Any, session: Any) -> dict[str, Tool]:
+ """The agent's own hands - teammate messaging and its wiki namespace (lazy)."""
+ from jarvis.society.surface import society_tools
+
+ return society_tools(cfg, brain, session)
+
+
+async def _society_extra(cfg: Any, brain: Any, session: Any) -> str:
+ """Who the agent is, what it reaches for, how the ecosystem works (lazy)."""
+ from jarvis.society.surface import society_system_extra
+
+ return await society_system_extra(cfg, brain, session)
+
+
+def _society_filter(session: Any) -> Callable[[dict[str, Tool]], dict[str, Tool]] | None:
+ """Grant / focus / deny over the merged tool set (lazy)."""
+ from jarvis.society.surface import society_tool_filter
+
+ return society_tool_filter(session)
+
+
def _only_local_models(tools: dict[str, Tool]) -> dict[str, Tool]:
"""Its own hands and nothing else.
@@ -171,6 +203,24 @@ _KITS: Final[dict[str, SurfaceKit]] = {
# the local server and the config, and the composer shows no chip.
workspace_dir=_chat_workspace,
),
+ # An agent-society member's canonical chat (jarvis/society). Jarvis' own
+ # harness on an API provider (the roster row's pick, else the Agents
+ # tier), the Jarvis ladder as stances, and per-session hands: the agent's
+ # grant/focus/deny over the brain's tool set plus its two society tools.
+ # The briefing is assembled per session from the roster row and the
+ # capability catalog (agent-definition section 3.3).
+ "society": SurfaceKit(
+ surface="society",
+ brain_runner=True,
+ cli_seats=False,
+ ladder=_JARVIS_LADDER,
+ uses_stance=True,
+ tool_origin="society",
+ session_tools=_society_tools,
+ session_system_extra=_society_extra,
+ session_tool_filter=_society_filter,
+ workspace_dir=_chat_workspace,
+ ),
}
diff --git a/jarvis/society/agent_tools.py b/jarvis/society/agent_tools.py
new file mode 100644
index 0000000000..d047afbe37
--- /dev/null
+++ b/jarvis/society/agent_tools.py
@@ -0,0 +1,267 @@
+"""The two hands only a society agent has: messaging a teammate, and writing
+into its own corner of the wiki.
+
+``society_message_agent`` (agent-definition §4.1) is the ONE send path
+between agents. It does exactly one thing — append a typed envelope for ONE
+teammate — and never spawns or runs a turn; turning envelopes into activity
+is the scheduler's monopoly. Two gates: the schema exists only in a society
+session's tool set (built per session by ``jarvis/society/surface.py``), and
+execution re-checks that the caller is a live active roster row, the target
+resolves, and the kill switch is off. The tool runs under
+``ToolExecutor.execute()`` like every other (AP-3).
+
+``society_wiki_note`` (agent-definition §5) writes a page under the agent's
+namespace ``society/<agent_id>/`` in the Obsidian vault — never anywhere
+else, by construction (there is no path argument) — with provenance
+frontmatter, and records the page in the knowledge staging table as
+unreviewed. The agent's durable notes live in ``memory.md`` of the same
+folder.
+"""
+
+from __future__ import annotations
+
+import datetime as _dt
+import logging
+import os
+import re
+import tempfile
+from pathlib import Path
+from typing import Any, Final
+
+from jarvis.core.protocols import ToolResult
+
+from .events import MsgType, now_ms
+from .failure_reasons import FailureReason, retry_action
+from .roster import AgentState, slugify
+
+log = logging.getLogger(__name__)
+
+__all__ = ["MESSAGE_TOOL_NAME", "WIKI_NOTE_TOOL_NAME", "MessageAgentTool", "WikiNoteTool"]
+
+MESSAGE_TOOL_NAME: Final[str] = "society_message_agent"
+WIKI_NOTE_TOOL_NAME: Final[str] = "society_wiki_note"
+_KINDS: Final[dict[str, MsgType]] = {
+ "say": MsgType.SAY,
+ "query": MsgType.QUERY,
+ "answer": MsgType.ANSWER,
+ "propose": MsgType.PROPOSE,
+}
+_MAX_TEXT: Final[int] = 8_000
+_MAX_NOTE: Final[int] = 40_000
+
+
+def _failure(reason: FailureReason, detail: str) -> ToolResult:
+ return ToolResult(
+ success=False,
+ output={"reason": str(reason), "retry": str(retry_action(reason))},
+ error=f"{reason}: {detail}",
+ )
+
+
+class MessageAgentTool:
+ """Send one message to ONE teammate. Fire-and-forget."""
+
+ name: str = MESSAGE_TOOL_NAME
+ risk_tier: str = "monitor"
+ description: str = (
+ "Send a message to ONE teammate in your agent society. Compose the message "
+ "yourself — never forward another message verbatim — and address the one "
+ "teammate whose role fits; do not fan out to several. Use kind 'query' when "
+ "you need an answer, 'propose' to suggest a plan, 'answer' when replying to a "
+ "query, else 'say'. The teammate reads it in their own chat and may reply "
+ "later; this call returns at once. It never assigns work — ask Jarvis or an "
+ "orchestrator to assign."
+ )
+ schema: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "target": {
+ "type": "string",
+ "description": "The teammate's name or id, exactly as listed under Teammates.",
+ },
+ "text": {"type": "string", "description": "Your message, in your own words."},
+ "kind": {
+ "type": "string",
+ "enum": sorted(_KINDS),
+ "description": "say (default) | query | answer | propose",
+ },
+ "refs": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "Optional pointers the teammate should open: wiki:..., file:...",
+ },
+ },
+ "required": ["target", "text"],
+ }
+ is_action_tool: bool = True
+
+ def __init__(self, runtime: Any, agent_id: str) -> None:
+ self._runtime = runtime
+ self._agent_id = agent_id
+
+ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:
+ rt = self._runtime
+ if await rt.store.kill_switch():
+ return _failure(FailureReason.KILL_SWITCH, "the society is halted")
+ caller = await rt.roster.get(self._agent_id)
+ if caller is None or caller.state is not AgentState.ACTIVE:
+ return _failure(FailureReason.BLOCKED_BY_POLICY, "caller is not an active agent")
+ target_key = str(args.get("target", "")).strip()
+ text = str(args.get("text", "")).strip()[:_MAX_TEXT]
+ if not target_key or not text:
+ return _failure(FailureReason.BLOCKED_BY_POLICY, "target and text are required")
+ target = await rt.roster.resolve(target_key)
+ if target is None or target.state is AgentState.ARCHIVED:
+ return _failure(FailureReason.TARGET_UNKNOWN, f"no teammate named {target_key!r}")
+ if target.agent_id == caller.agent_id:
+ return _failure(FailureReason.BLOCKED_BY_POLICY, "you cannot message yourself")
+ if target.state is AgentState.PAUSED:
+ return _failure(FailureReason.TARGET_PAUSED, f"{target.name} is paused")
+ kind = str(args.get("kind") or "say").strip().lower()
+ msg_type = _KINDS.get(kind)
+ if msg_type is None:
+ return _failure(FailureReason.BLOCKED_BY_POLICY, f"unknown kind {kind!r}")
+ refs = args.get("refs")
+ payload: dict[str, Any] = {}
+ if isinstance(refs, list) and refs:
+ payload["refs"] = [str(r) for r in refs][:20]
+ trace_id = f"chat:{caller.agent_id}:{target.agent_id}"
+ env = await rt.say(
+ from_agent=caller.agent_id,
+ to_agent=target.agent_id,
+ text=text,
+ trace_id=trace_id,
+ msg_type=msg_type,
+ payload=payload,
+ )
+ return ToolResult(
+ success=True,
+ output={
+ "delivered_to": target.name,
+ "kind": kind,
+ "seq": env.seq,
+ "trace_id": env.trace_id,
+ },
+ )
+
+
+_FRONTMATTER_SAFE = re.compile(r"[\r\n\"]")
+
+
+def _atomic_write(path: Path, text: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp = tempfile.mkstemp(prefix=".society-", suffix=".tmp", dir=str(path.parent))
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as handle:
+ handle.write(text)
+ os.replace(tmp, path)
+ except Exception:
+ try:
+ os.unlink(tmp)
+ except OSError:
+ pass
+ raise
+
+
+class WikiNoteTool:
+ """Write into ``society/<agent_id>/`` of the vault — the agent's memory."""
+
+ name: str = WIKI_NOTE_TOOL_NAME
+ risk_tier: str = "monitor"
+ description: str = (
+ "Write a note into YOUR folder of the shared wiki (society/<you>/). Use kind "
+ "'note' for a work note about something you found or produced (one page per "
+ "topic, give it a title), or kind 'memory' to append a durable fact to your "
+ "memory page. Pages are marked unreviewed until the user promotes them; write "
+ "conclusions and facts, not chat transcripts. Reading the wiki is wiki-recall "
+ "and wiki-page-read."
+ )
+ schema: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "title": {"type": "string", "description": "Short page title (kind 'note')."},
+ "text": {"type": "string", "description": "Markdown body."},
+ "kind": {"type": "string", "enum": ["note", "memory"], "description": "note | memory"},
+ "origin": {
+ "type": "string",
+ "enum": ["tool", "web", "agent", "user"],
+ "description": "Where the knowledge came from (default 'agent').",
+ },
+ },
+ "required": ["text"],
+ }
+ is_action_tool: bool = True
+
+ def __init__(self, runtime: Any, agent_id: str, *, vault_root: Path) -> None:
+ self._runtime = runtime
+ self._agent_id = agent_id
+ self._vault_root = Path(vault_root)
+
+ @property
+ def namespace(self) -> Path:
+ return self._vault_root / "society" / self._agent_id
+
+ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:
+ rt = self._runtime
+ caller = await rt.roster.get(self._agent_id)
+ if caller is None or caller.state is not AgentState.ACTIVE:
+ return _failure(FailureReason.BLOCKED_BY_POLICY, "caller is not an active agent")
+ text = str(args.get("text", "")).strip()[:_MAX_NOTE]
+ if not text:
+ return _failure(FailureReason.BLOCKED_BY_POLICY, "text is required")
+ kind = str(args.get("kind") or "note").strip().lower()
+ origin = str(args.get("origin") or "agent").strip().lower()
+ if origin not in ("tool", "web", "agent", "user"):
+ origin = "agent"
+ trace = str(getattr(ctx, "trace_id", "") or "")
+ today = _dt.datetime.now(tz=_dt.UTC).date().isoformat()
+ if kind == "memory":
+ path = self.namespace / "memory.md"
+ existing = path.read_text(encoding="utf-8") if path.is_file() else ""
+ if not existing:
+ existing = self._frontmatter(f"{caller.name} — memory", origin, trace) + "\n"
+ body = existing.rstrip("\n") + f"\n\n## {today}\n\n{text}\n"
+ _atomic_write(path, body)
+ summary = text[:280]
+ else:
+ title = _FRONTMATTER_SAFE.sub(" ", str(args.get("title") or text[:60])).strip()
+ if not title:
+ title = "note"
+ slug = slugify(title)[:60]
+ path = self.namespace / f"{today}-{slug}.md"
+ n = 2
+ while path.exists():
+ path = self.namespace / f"{today}-{slug}-{n}.md"
+ n += 1
+ page = self._frontmatter(title, origin, trace) + f"\n# {title}\n\n{text}\n"
+ _atomic_write(path, page)
+ summary = f"{title}: {text[:220]}"
+ rel = path.relative_to(self._vault_root).as_posix()
+ try:
+ await rt.store.insert_knowledge(
+ {
+ "agent_id": caller.agent_id,
+ "wiki_path": rel,
+ "origin": origin,
+ "source_event": None,
+ "trace_id": trace or None,
+ "reviewed": 0,
+ "summary": summary,
+ "created_ms": now_ms(),
+ }
+ )
+ except Exception: # noqa: BLE001 — the page is written; the staging row is bookkeeping
+ log.warning("society wiki note: knowledge row not recorded for %s", rel, exc_info=True)
+ return ToolResult(success=True, output={"path": rel, "kind": kind, "reviewed": False})
+
+ def _frontmatter(self, title: str, origin: str, trace: str) -> str:
+ safe_title = _FRONTMATTER_SAFE.sub(" ", title)
+ return (
+ "---\n"
+ f'title: "{safe_title}"\n'
+ f"author: agent:{self._agent_id}\n"
+ f"origin: {origin}\n"
+ f"trace: {trace or 'none'}\n"
+ "reviewed: false\n"
+ "---\n"
+ )
diff --git a/jarvis/society/chat_binding.py b/jarvis/society/chat_binding.py
new file mode 100644
index 0000000000..007e739335
--- /dev/null
+++ b/jarvis/society/chat_binding.py
@@ -0,0 +1,134 @@
+"""Binding an agent to its one canonical chat, and delivering board messages
+into it.
+
+Identity chain (agent-definition §2, build plan decision b): roster row →
+session id ``society:<agent_id>`` (a pure function; no pointer column) →
+``ensure_session`` mirrors the row's provider / model / effort onto the
+session at bind time and re-seats it when the card changes (transcript
+kept). Without a provider on the row the session runs on the Agents tier
+the rest of the app uses (``local_models.assistant_session.agents_tier``).
+
+``make_deliver_hook`` is what the scheduler calls for SAY / QUERY / ANSWER /
+PROPOSE / RESULT envelopes: ensure the target's session, then start a turn
+with the message framed as coming from the sender. A busy session raises
+``target busy`` so the scheduler writes a typed veto and the envelope stays
+in the inbox for the next turn.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Callable
+from pathlib import Path
+from typing import Any, Final
+
+from .events import MsgType, SocietyEnvelope
+from .roster import AgentRecord, PermissionCeiling
+from .scheduler import DeliverHook
+
+log = logging.getLogger(__name__)
+
+__all__ = ["SURFACE", "ensure_session", "frame_incoming", "make_deliver_hook", "pair_for"]
+
+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.
+_CEILING_TO_MODE: Final[dict[str, str]] = {
+ str(PermissionCeiling.SAFE): "plan",
+ str(PermissionCeiling.MONITOR): "accept-edits",
+ str(PermissionCeiling.ASK): "ask",
+}
+
+
+def pair_for(cfg: Any, agent: AgentRecord) -> tuple[str, str, str]:
+ """``(provider, model, effort)`` the agent's chat runs on."""
+ if agent.provider:
+ return agent.provider, agent.model, agent.effort
+ from jarvis.local_models.assistant_session import agents_tier
+
+ tier = agents_tier(cfg)
+ if not tier.ready:
+ raise PermissionError(tier.reason or "no provider can run the agent chat")
+ return tier.provider, tier.model, agent.effort
+
+
+def _workspace(cfg: Any, agent: AgentRecord) -> str:
+ data_dir = Path(getattr(getattr(cfg, "memory", None), "data_dir", None) or "data")
+ folder = data_dir / (agent.workspace_dir or f"society/{agent.agent_id}/workspace")
+ try:
+ folder.mkdir(parents=True, exist_ok=True)
+ except OSError:
+ log.warning("society: workspace %s could not be created", folder, exc_info=True)
+ return str(folder)
+
+
+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.service import resolve_runner
+
+ provider, model, effort = pair_for(cfg, agent)
+ session_id = agent.session_id
+ existing = 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)])
+ return svc.store.create_session(
+ provider=provider,
+ model=model,
+ effort=effort or default_effort(provider),
+ cwd=_workspace(cfg, agent),
+ permission_mode=mode,
+ title=agent.name,
+ session_id=session_id,
+ surface=SURFACE,
+ )
+ if existing.provider != provider or (model and existing.model != model):
+ svc.store.reseat_session(session_id, provider=provider, model=model or existing.model)
+ existing = svc.store.get_session(session_id)
+ return existing
+
+
+def frame_incoming(env: SocietyEnvelope, sender_name: str) -> str:
+ """How a board envelope reads inside the receiving agent's chat."""
+ kind = str(env.msg_type).lower()
+ lines = [f"[{kind} from {sender_name}]"]
+ if env.msg_type is MsgType.RESULT:
+ p = env.payload
+ lines.append(f"Status: {p.get('status', 'done')}")
+ lines.append(f"Done: {p.get('done', '')}")
+ if p.get("output"):
+ lines.append("Output: " + ", ".join(str(x) for x in p.get("output", [])))
+ if p.get("open"):
+ lines.append("Open: " + "; ".join(str(x) for x in p.get("open", [])))
+ text = env.text
+ if text:
+ lines.append(text)
+ refs = env.payload.get("refs")
+ if isinstance(refs, list) and refs:
+ lines.append("Refs: " + ", ".join(str(r) for r in refs))
+ return "\n".join(lines)
+
+
+def make_deliver_hook(
+ get_service: Callable[[], Any | None],
+ get_cfg: Callable[[], Any],
+ resolve_name: Callable[[str], str] | None = None,
+) -> DeliverHook:
+ """The scheduler's deliver hook over the agent-chat service."""
+
+ async def _deliver(target: AgentRecord, env: SocietyEnvelope) -> None:
+ svc = get_service()
+ if svc is None:
+ raise RuntimeError("agent chat service unavailable: message stays in the inbox")
+ cfg = get_cfg()
+ session = ensure_session(svc, cfg, target)
+ if svc.is_running(session.session_id):
+ raise RuntimeError(f"target busy: {target.name} is running a turn")
+ sender = resolve_name(env.from_agent) if resolve_name else env.from_agent
+ await svc.send(session.session_id, frame_incoming(env, sender))
+
+ return _deliver
diff --git a/jarvis/society/failure_reasons.py b/jarvis/society/failure_reasons.py
index 951012cad9..c58109cafb 100644
--- a/jarvis/society/failure_reasons.py
+++ b/jarvis/society/failure_reasons.py
@@ -126,6 +126,10 @@ _PATTERNS: Final[tuple[tuple[FailureReason, re.Pattern[str]], ...]] = (
re.I,
),
),
+ (
+ FailureReason.TARGET_BUSY,
+ re.compile(r"(session ?busy|target busy|already running a turn)", re.I),
+ ),
(
FailureReason.TARGET_OFFLINE,
re.compile(r"(connection refused|not reachable|unreachable|offline|econnrefused)", re.I),
diff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.py
index 98bc746164..2322154f2f 100644
--- a/jarvis/society/runtime.py
+++ b/jarvis/society/runtime.py
@@ -33,10 +33,22 @@ from .store import SocietyStore
log = logging.getLogger(__name__)
-__all__ = ["SocietyRuntime"]
+__all__ = ["SocietyRuntime", "current_runtime", "set_current_runtime"]
_DB_NAME = "society.db"
+_current: SocietyRuntime | None = None
+
+
+def current_runtime() -> SocietyRuntime | None:
+ """The runtime the app built (the society surface reaches it through here)."""
+ return _current
+
+
+def set_current_runtime(runtime: SocietyRuntime | None) -> None:
+ global _current # noqa: PLW0603 - one process, one society
+ _current = runtime
+
def _agent_frame(agent: AgentRecord, task: str) -> str:
"""The mission prompt that carries the agent's identity to a worker."""
@@ -85,6 +97,9 @@ class SocietyRuntime:
self.store, owner_of=self.owner_of, on_run_ended=self.scheduler.note_run_ended
)
self._owners: dict[str, str] = {}
+ #: Roster rows the society surface read for a turn - the sync tool
+ #: filter reads them here (the briefing fills the cache first).
+ self._agent_cache: dict[str, AgentRecord] = {}
self._started = False
# ------------------------------------------------------------ lifecycle
@@ -100,6 +115,7 @@ class SocietyRuntime:
self.bridge.attach(bus)
await self.seed_lead()
self._started = True
+ set_current_runtime(self)
log.info("society runtime started (%s)", self.store.path)
return self
@@ -108,6 +124,14 @@ class SocietyRuntime:
self.bridge.detach()
await self.store.close()
self._started = False
+ if current_runtime() is self:
+ set_current_runtime(None)
+
+ def cache_agent(self, agent: AgentRecord) -> None:
+ self._agent_cache[agent.agent_id] = agent
+
+ def cached_agent(self, agent_id: str) -> AgentRecord | None:
+ return self._agent_cache.get(agent_id)
def set_deliver(self, deliver: DeliverHook | None) -> None:
"""The chat binding (M2) installs the canonical-chat deliverer here."""
diff --git a/jarvis/society/surface.py b/jarvis/society/surface.py
new file mode 100644
index 0000000000..29e31dc6c8
--- /dev/null
+++ b/jarvis/society/surface.py
@@ -0,0 +1,255 @@
+"""The ``society`` chat surface: per-session hands and briefing.
+
+One agent = one canonical chat (``society:<agent_id>``) on Jarvis' own brain
+runner. Per turn this module gives the runner three things (agent-definition
+§3.2–§3.3):
+
+* ``society_tools`` — the agent's two own tools (teammate messaging, wiki
+ namespace), built from the roster row behind the session id;
+* ``society_tool_filter`` — grant / focus / deny applied to the merged tool
+ set, in the deterministic order that keeps the provider prompt cache warm;
+* ``society_system_extra`` — the briefing: who the agent is, its standing
+ instructions, its hands (focus first, one-liners), the ecosystem card, and
+ the roster of teammates. Assembled from cached, byte-stable parts.
+
+The runtime is reached through ``jarvis.society.runtime.current_runtime()``;
+without a runtime (a stripped install, a test without the society) every
+builder returns nothing and the turn runs as a plain Jarvis chat.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+from collections.abc import Callable
+from pathlib import Path
+from typing import Any, Final, cast
+
+from jarvis.core.protocols import Tool
+
+from .agent_tools import MessageAgentTool, WikiNoteTool
+from .capabilities import CapabilityKind, CapabilityRow, select_tools
+from .roster import AgentRecord, canonical_session_id
+from .runtime import current_runtime
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "SURFACE",
+ "agent_id_of",
+ "build_briefing",
+ "capability_epoch",
+ "society_system_extra",
+ "society_tool_filter",
+ "society_tools",
+]
+
+SURFACE: Final[str] = "society"
+_PREFIX: Final[str] = "society:"
+#: Tools every society session keeps regardless of grants — its own hands.
+_OWN_PREFIX: Final[str] = "society_"
+#: Tools a society session never gets even in ``all`` mode: the agent writes
+#: the wiki only through its namespaced note tool.
+_SOCIETY_DENIED: Final[frozenset[str]] = frozenset({"wiki-ingest"})
+
+_ECOSYSTEM_CARD: Final[str] = """\
+## The Jarvis ecosystem you work in
+- Jarvis is the voice-steered lead of this society; the user talks to Jarvis by voice and to \
+you by typed chat. Only Jarvis and orchestrators assign work; a scheduler (not a model) turns \
+an assignment into a run under the assignee's identity. You never spawn agents or workers.
+- Teammates: send ONE teammate a message with society_message_agent (kinds: say, query, \
+answer, propose). Compose it yourself. When you finish work for someone, end with a handoff: \
+what is done, where the output is, what evidence you used, what remains open, who owns the \
+next step.
+- Memory: the user's Obsidian wiki is the shared memory. Read it with wiki-recall and \
+wiki-page-read (pages marked unreviewed came from agents or the web — verify before relying \
+on them). Write only into your own folder with society_wiki_note (kind note for findings, \
+kind memory for durable facts about your role). Never edit the user's own pages.
+- Routines: recurring work runs from the Automations section as tasks tagged with your name; \
+their results arrive in this chat.
+- Approvals: actions above your permission ceiling queue for the user (chat card, Jarvis bar, \
+voice). A queued action is not refused — say what you are waiting for and continue with what \
+you can. Secrets are never typed into a chat; credentials come from the keyring.
+- Language: answer in the language of the message you received."""
+
+
+def agent_id_of(session_id: str) -> str | None:
+ """``society:<agent_id>`` → ``agent_id``; ``None`` for any other session."""
+ if not session_id.startswith(_PREFIX):
+ return None
+ agent_id = session_id[len(_PREFIX) :].strip()
+ return agent_id or None
+
+
+def _vault_root(cfg: Any) -> Path:
+ from jarvis.memory.wiki.vault_root import last_resolution, resolve_vault_root
+
+ known = last_resolution()
+ if known is not None:
+ return known.path
+ raw = None
+ for holder in (getattr(cfg, "wiki", None), getattr(cfg, "memory", None)):
+ raw = getattr(holder, "vault_root", None)
+ if raw:
+ break
+ return resolve_vault_root(raw).path
+
+
+def capability_epoch(catalog: list[CapabilityRow]) -> str:
+ """A fingerprint of the capability surface — changes when hands change."""
+ digest = hashlib.sha256("\n".join(sorted(r.id for r in catalog)).encode()).hexdigest()
+ return digest[:12]
+
+
+# ------------------------------------------------------------------ builders
+
+
+def society_tools(cfg: Any, brain: Any, session: Any) -> dict[str, Tool]:
+ rt = current_runtime()
+ agent_id = agent_id_of(getattr(session, "session_id", "") or "")
+ if rt is None or agent_id is None:
+ return {}
+ return {
+ MessageAgentTool.name: cast(Tool, MessageAgentTool(rt, agent_id)),
+ WikiNoteTool.name: cast(Tool, WikiNoteTool(rt, agent_id, vault_root=_vault_root(cfg))),
+ }
+
+
+def society_tool_filter(session: Any) -> Callable[[dict[str, Tool]], dict[str, Tool]] | None:
+ rt = current_runtime()
+ agent_id = agent_id_of(getattr(session, "session_id", "") or "")
+ if rt is None or agent_id is None:
+ return None
+ agent = 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
+ }
+
+ def _apply(tools: dict[str, Tool]) -> dict[str, Tool]:
+ own = {n: t for n, t in tools.items() if n.startswith(_OWN_PREFIX)}
+ rest = {
+ n: t
+ for n, t in tools.items()
+ if not n.startswith(_OWN_PREFIX) and n not in _SOCIETY_DENIED
+ }
+ picked = select_tools(
+ rest,
+ grant_mode=str(agent.grant_mode),
+ grants=agent.grants,
+ focus=agent.focus,
+ denies=agent.denies,
+ )
+ ordered: dict[str, Tool] = {}
+ ordered.update(own)
+ ordered.update(picked)
+ return ordered
+
+ return _apply
+
+
+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 "")
+ if rt is None or agent_id is None:
+ return ""
+ agent = await rt.roster.get(agent_id)
+ if agent is None:
+ return ""
+ rt.cache_agent(agent)
+ catalog = rt.catalog()
+ roster = await rt.roster.list()
+ return build_briefing(agent, catalog, roster)
+
+
+# ------------------------------------------------------------------ briefing
+
+
+def _kind_label(kind: CapabilityKind) -> str:
+ return {
+ CapabilityKind.PLUGIN: "plugins",
+ CapabilityKind.CLI: "CLIs",
+ CapabilityKind.MCP: "MCP tools",
+ CapabilityKind.SKILL: "skills",
+ CapabilityKind.CORE: "built-in",
+ }[kind]
+
+
+def build_briefing(
+ agent: AgentRecord, catalog: list[CapabilityRow], roster: list[AgentRecord]
+) -> str:
+ """The per-agent system-prompt addendum (agent-definition §3.3).
+
+ Pure and deterministic: same roster row + same catalog + same roster →
+ the same bytes, so the provider prompt cache stays warm across turns.
+ """
+ by_id = {row.id: row for row in catalog if row.connected}
+ granted = set(agent.grants)
+ denied = set(agent.denies)
+
+ def _allowed(cap_id: str) -> bool:
+ if cap_id in denied:
+ return False
+ if str(agent.grant_mode) == "allowlist":
+ return cap_id in granted
+ return True
+
+ parts: list[str] = []
+ head = f"## You are {agent.name}"
+ if agent.title:
+ head += f" — {agent.title}"
+ parts.append(head)
+ parts.append(
+ f"Tier: {agent.tier}. Permission ceiling: {agent.permission_ceiling}. "
+ + (
+ "You may assign work to teammates through Jarvis' scheduler."
+ if agent.may_assign
+ else "You do not assign work; ask Jarvis or an orchestrator."
+ )
+ )
+ if agent.description.strip():
+ parts.append("## Standing instructions\n" + agent.description.strip())
+
+ focus_rows = [by_id[c] for c in agent.focus if c in by_id and _allowed(c)]
+ others = [r for r in catalog if r.connected and _allowed(r.id) and r.id not in agent.focus]
+ hands: list[str] = ["## Your hands"]
+ if focus_rows:
+ hands.append("Reach for these first:")
+ for row in focus_rows:
+ line = f"- {row.label} ({row.id})"
+ if row.one_liner:
+ line += f": {row.one_liner}"
+ hands.append(line)
+ if others:
+ grouped: dict[CapabilityKind, list[str]] = {}
+ for row in others:
+ grouped.setdefault(row.kind, []).append(row.label)
+ also = "; ".join(
+ f"{_kind_label(kind)}: {', '.join(sorted(names))}" for kind, names in grouped.items()
+ )
+ hands.append("Also available — " + also + ".")
+ if not focus_rows and not others:
+ hands.append("No connected capabilities beyond your society tools right now.")
+ hands.append(f"Capability epoch: {capability_epoch(catalog)}")
+ parts.append("\n".join(hands))
+
+ parts.append(_ECOSYSTEM_CARD)
+
+ mates = [a for a in roster if a.agent_id != agent.agent_id and str(a.state) == "active"]
+ if mates:
+ lines = ["## Teammates"]
+ for mate in mates:
+ line = f"- {mate.name}"
+ if mate.title:
+ line += f" — {mate.title}"
+ line += f" ({mate.tier})"
+ lines.append(line)
+ parts.append("\n".join(lines))
+ return "\n\n".join(parts)
+
+
+def session_id_for(agent_id: str) -> str:
+ return canonical_session_id(agent_id)
diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.py
index ffd881e757..278eff2ba8 100644
--- a/jarvis/ui/web/agent_chat_routes.py
+++ b/jarvis/ui/web/agent_chat_routes.py
@@ -73,12 +73,17 @@ log = logging.getLogger(__name__)
#: The Pydantic twin of ``jarvis.agent_chat.store.SURFACES`` (AP-4; the parity
#: test in tests/unit/agent_chat/test_agent_chat_surface_parity.py pins it).
-SurfaceName = Literal["jarvis", "agent", "local-models"]
+SurfaceName = Literal["jarvis", "agent", "local-models", "society"]
#: The same names, as data — a multipart form field cannot be typed by a
#: ``Literal`` without turning an unknown surface into a 422 on a file the
#: person just dropped.
-SURFACE_NAMES: frozenset[str] = frozenset({"jarvis", "agent", "local-models"})
+SURFACE_NAMES: frozenset[str] = frozenset({"jarvis", "agent", "local-models", "society"})
+
+#: Surfaces that never appear in an unfiltered session list: an agent's
+#: canonical chat belongs to its model card, not to the IDE's or the front
+#: page's history.
+HIDDEN_SURFACES: frozenset[str] = frozenset({"society"})
router = APIRouter(prefix="/api/agent-chat", tags=["agent-chat"])
@@ -526,6 +531,8 @@ async def list_sessions(
svc = _service(request)
out = []
for s in svc.store.list_sessions(limit=limit, surface=surface):
+ if surface is None and s.surface in HIDDEN_SURFACES:
+ continue
d = s.to_dict()
d["running"] = svc.is_running(s.session_id)
out.append(d)
diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
index 8a6a52550b..fdd358a2f8 100644
--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
@@ -81,7 +81,7 @@ export interface AgentChatCatalog {
* (``jarvis/agent_chat/surface_kits.py``): the front page, the coding
* agents, and the Local models section's setup assistant.
*/
-export type AgentChatSurface = "jarvis" | "agent" | "local-models";
+export type AgentChatSurface = "jarvis" | "agent" | "local-models" | "society";
export interface AgentChatSession {
session_id: string;
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index b0a89bbe66..5341102e7c 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -3546,6 +3546,16 @@ class WebServer:
except Exception: # noqa: BLE001 — the catalog then shows no skills
return None
+ from jarvis.society.chat_binding import make_deliver_hook
+
+ from .agent_chat_routes import _service_from_state
+
+ # Board messages addressed to an agent wake its canonical chat on the
+ # agent-chat service (built lazily by its own factory).
+ deliver = make_deliver_hook(
+ lambda: _service_from_state(state),
+ lambda: self.cfg,
+ )
return SocietyRuntime(
data_dir,
mission_manager=_manager,
@@ -3553,6 +3563,7 @@ class WebServer:
budget_tracker=_budget,
brain_tools=_tools,
skills=_skills,
+ deliver=deliver,
)
def _build_agent_chat_service(self) -> Any:
diff --git a/tests/unit/society/test_agent_tools.py b/tests/unit/society/test_agent_tools.py
new file mode 100644
index 0000000000..3746fc3d34
--- /dev/null
+++ b/tests/unit/society/test_agent_tools.py
@@ -0,0 +1,101 @@
+"""The agent's two hands: one send path with both gates, a namespaced wiki note."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+from uuid import uuid4
+
+import pytest
+
+from jarvis.society.agent_tools import MessageAgentTool, WikiNoteTool
+from jarvis.society.capabilities import NEVER_GRANTED, build_catalog
+from jarvis.society.events import MsgType
+from jarvis.society.runtime import SocietyRuntime
+
+
+async def rt(tmp_path: Path):
+ runtime = SocietyRuntime(tmp_path)
+ await runtime.ensure_started()
+ await runtime.roster.create(name="Scout")
+ await runtime.roster.create(name="Archivist")
+ try:
+ yield runtime
+ finally:
+ await runtime.close()
+
+
+CTX = SimpleNamespace(trace_id=uuid4(), user_utterance="", config={}, memory_read=None)
+
+
+async def test_message_appends_one_typed_envelope(rt: SocietyRuntime):
+ tool = MessageAgentTool(rt, "scout")
+ res = await tool.execute({"target": "Archivist", "text": "hi", "kind": "query"}, CTX)
+ assert res.success, res.error
+ assert res.output["delivered_to"] == "Archivist"
+ inbox = await rt.store.inbox_for("archivist")
+ assert [(e.msg_type, e.from_agent) for e in inbox] == [(MsgType.QUERY, "scout")]
+
+
+async def test_message_gates(rt: SocietyRuntime):
+ tool = MessageAgentTool(rt, "scout")
+ assert (await tool.execute({"target": "nobody", "text": "x"}, CTX)).output["reason"] == (
+ "target_unknown"
+ )
+ assert (await tool.execute({"target": "scout", "text": "x"}, CTX)).success is False
+ assert (await tool.execute({"target": "archivist", "text": ""}, CTX)).success is False
+ bad_kind = await tool.execute({"target": "archivist", "text": "x", "kind": "assign"}, CTX)
+ assert bad_kind.success is False
+ await rt.roster.update("archivist", {"state": "paused"})
+ paused = await tool.execute({"target": "archivist", "text": "x"}, CTX)
+ assert paused.output["reason"] == "target_paused"
+ await rt.store.set_kill_switch(True)
+ halted = await tool.execute({"target": "archivist", "text": "x"}, CTX)
+ assert halted.output["reason"] == "kill_switch"
+ ghost = MessageAgentTool(rt, "ghost")
+ await rt.store.set_kill_switch(False)
+ assert (await ghost.execute({"target": "scout", "text": "x"}, CTX)).success is False
+
+
+def test_message_tool_is_never_in_the_catalog():
+ """Gate 1: no other surface can grant the society tools through the catalog."""
+ assert "society_message_agent" in NEVER_GRANTED
+ fake = {"society_message_agent": SimpleNamespace(description="", risk_tier="monitor")}
+ assert build_catalog(fake) == []
+
+
+async def test_wiki_note_writes_into_the_namespace_only(rt: SocietyRuntime, tmp_path: Path):
+ vault = tmp_path / "vault"
+ tool = WikiNoteTool(rt, "scout", vault_root=vault)
+ res = await tool.execute(
+ {"title": "VPS providers", "text": "Hetzner wins.", "origin": "web"}, CTX
+ )
+ assert res.success, res.error
+ path = vault / res.output["path"]
+ assert path.parent == vault / "society" / "scout"
+ body = path.read_text(encoding="utf-8")
+ assert body.startswith("---\n") and "author: agent:scout" in body and "origin: web" in body
+ assert "reviewed: false" in body and "# VPS providers" in body
+ rows = await rt.store.list_knowledge_rows(agent_id="scout")
+ assert len(rows) == 1 and rows[0]["reviewed"] == 0 and rows[0]["origin"] == "web"
+
+ # Same title twice never overwrites.
+ again = await tool.execute({"title": "VPS providers", "text": "Update."}, CTX)
+ assert again.output["path"] != res.output["path"]
+
+ # Memory appends to one page.
+ m1 = await tool.execute({"kind": "memory", "text": "The user prefers Hetzner."}, CTX)
+ m2 = await tool.execute({"kind": "memory", "text": "Budget is 5 EUR/month."}, CTX)
+ assert m1.output["path"] == m2.output["path"] == "society/scout/memory.md"
+ memory = (vault / "society" / "scout" / "memory.md").read_text(encoding="utf-8")
+ assert "Hetzner" in memory and "5 EUR" in memory and memory.count("## ") == 2
+ assert not any(p.is_file() for p in vault.iterdir() if p.suffix == ".md")
+
+
+async def test_wiki_note_refuses_inactive_caller(rt: SocietyRuntime, tmp_path: Path):
+ await rt.roster.update("scout", {"state": "paused"})
+ tool = WikiNoteTool(rt, "scout", vault_root=tmp_path / "vault")
+ res = await tool.execute({"text": "x"}, CTX)
+ assert res.success is False
+ assert not (tmp_path / "vault").exists()
diff --git a/tests/unit/society/test_chat_binding.py b/tests/unit/society/test_chat_binding.py
new file mode 100644
index 0000000000..15f742e6fc
--- /dev/null
+++ b/tests/unit/society/test_chat_binding.py
@@ -0,0 +1,172 @@
+"""Binding an agent to its canonical chat; delivering board envelopes into it."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.agent_chat.store import SURFACES, AgentChatStore
+from jarvis.society.chat_binding import ensure_session, frame_incoming, make_deliver_hook
+from jarvis.society.events import MsgType, SocietyEnvelope
+from jarvis.society.runtime import SocietyRuntime
+
+
+class FakeService:
+ def __init__(self, store: AgentChatStore) -> None:
+ self.store = store
+ self.sent: list[tuple[str, str]] = []
+ self.busy: set[str] = set()
+
+ def is_running(self, session_id: str) -> bool:
+ return session_id in self.busy
+
+ async def send(self, session_id: str, text: str, attachments=None) -> str:
+ self.sent.append((session_id, text))
+ return "turn-1"
+
+
+async def world(tmp_path: Path):
+ runtime = SocietyRuntime(tmp_path)
+ await runtime.ensure_started()
+ svc = FakeService(AgentChatStore(tmp_path / "agent_chat.db"))
+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path / "data")))
+ try:
+ yield runtime, svc, cfg
+ finally:
+ await runtime.close()
+
+
+def test_society_is_a_surface():
+ assert "society" in SURFACES
+
+
+async def test_ensure_session_is_deterministic_and_reseats(world):
+ rt, svc, cfg = world
+ scout, _ = await rt.roster.create(name="Scout", provider="openai", model="gpt-5.2")
+ first = ensure_session(svc, cfg, scout)
+ 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"
+ assert first.title == "Scout"
+ assert Path(first.cwd).name == "workspace" and os.path.isdir(first.cwd) # noqa: ASYNC240
+
+ again = ensure_session(svc, cfg, scout)
+ assert again.session_id == first.session_id
+ assert len(svc.store.list_sessions(surface="society")) == 1
+
+ moved = await rt.roster.update("scout", {"provider": "gemini", "model": "gemini-3-pro"})
+ reseated = ensure_session(svc, cfg, moved)
+ assert reseated.provider == "gemini" and reseated.model == "gemini-3-pro"
+ assert reseated.session_id == "society:scout"
+
+
+async def test_ceiling_maps_to_stance(world):
+ rt, svc, cfg = world
+ safe, _ = await rt.roster.create(name="Reader", provider="openai", permission_ceiling="safe")
+ ask, _ = await rt.roster.create(name="Asker", provider="openai", permission_ceiling="ask")
+ assert ensure_session(svc, cfg, safe).permission_mode == "plan"
+ assert ensure_session(svc, cfg, ask).permission_mode == "ask"
+
+
+async def test_without_provider_the_agents_tier_answers(world, monkeypatch):
+ rt, svc, cfg = world
+ import jarvis.local_models.assistant_session as tier_mod
+
+ monkeypatch.setattr(
+ tier_mod,
+ "agents_tier",
+ lambda cfg, **kw: SimpleNamespace(provider="grok", model="grok-5", ready=True, reason=""),
+ )
+ scout, _ = await rt.roster.create(name="Scout")
+ session = ensure_session(svc, cfg, scout)
+ assert session.provider == "grok" and session.model == "grok-5"
+
+ monkeypatch.setattr(
+ tier_mod,
+ "agents_tier",
+ lambda cfg, **kw: SimpleNamespace(provider="", model="", ready=False, reason="no key"),
+ )
+ quill, _ = await rt.roster.create(name="Quill")
+ with pytest.raises(PermissionError):
+ ensure_session(svc, cfg, quill)
+
+
+async def test_deliver_hook_frames_and_sends(world):
+ rt, svc, cfg = world
+ scout, _ = await rt.roster.create(name="Scout", provider="openai")
+ deliver = make_deliver_hook(lambda: svc, lambda: cfg, resolve_name=lambda a: a.title())
+ env = SocietyEnvelope(
+ msg_type=MsgType.QUERY,
+ from_agent="archivist",
+ to_agent="scout",
+ trace_id="t",
+ payload={"text": "Where is the VPS note?", "refs": ["wiki:society/archivist/vps.md"]},
+ )
+ await deliver(scout, env)
+ assert svc.sent == [
+ (
+ "society:scout",
+ "[query from Archivist]\nWhere is the VPS note?\nRefs: wiki:society/archivist/vps.md",
+ )
+ ]
+ svc.busy.add("society:scout")
+ with pytest.raises(RuntimeError, match="target busy"):
+ await deliver(scout, env)
+
+
+def test_result_frame_carries_the_handoff():
+ env = SocietyEnvelope(
+ msg_type=MsgType.RESULT,
+ from_agent="scout",
+ to_agent="archivist",
+ trace_id="t",
+ payload={
+ "status": "partial",
+ "done": "Found three providers.",
+ "output": ["wiki:society/scout/vps.md"],
+ "open": ["pricing for the 4 GB tier"],
+ },
+ )
+ text = frame_incoming(env, "Scout")
+ assert text.splitlines() == [
+ "[result from Scout]",
+ "Status: partial",
+ "Done: Found three providers.",
+ "Output: wiki:society/scout/vps.md",
+ "Open: pricing for the 4 GB tier",
+ ]
+
+
+async def test_scheduler_delivers_through_the_hook(world):
+ rt, svc, cfg = world
+ await rt.roster.create(name="Scout", provider="openai")
+ await rt.roster.create(name="Archivist", provider="openai")
+ rt.set_deliver(make_deliver_hook(lambda: svc, lambda: cfg))
+ await rt.say(from_agent="scout", to_agent="archivist", text="ping")
+ assert [s[0] for s in svc.sent] == ["society:archivist"]
+ assert svc.sent[0][1].startswith("[say from scout]")
+
+
+def test_unfiltered_session_list_hides_society_sessions(tmp_path: Path):
+ from jarvis.ui.web.agent_chat_routes import router
+
+ store = AgentChatStore(tmp_path / "agent_chat.db")
+ store.create_session(provider="openai", model="m", effort="", cwd="", surface="agent")
+ store.create_session(
+ provider="openai", model="m", effort="", cwd="", surface="society", session_id="society:x"
+ )
+ app = FastAPI()
+ app.include_router(router)
+ app.state.agent_chat = SimpleNamespace(store=store, is_running=lambda sid: False)
+ with TestClient(app) as c:
+ everything = c.get("/api/agent-chat/sessions").json()["sessions"]
+ assert [s["surface"] for s in everything] == ["agent"]
+ only = c.get("/api/agent-chat/sessions", params={"surface": "society"}).json()["sessions"]
+ assert [s["session_id"] for s in only] == ["society:x"]
diff --git a/tests/unit/society/test_surface.py b/tests/unit/society/test_surface.py
new file mode 100644
index 0000000000..279ba1c59f
--- /dev/null
+++ b/tests/unit/society/test_surface.py
@@ -0,0 +1,132 @@
+"""The society surface: per-session hands, the grant filter and the briefing."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.society import runtime as runtime_mod
+from jarvis.society.agent_tools import MESSAGE_TOOL_NAME, WIKI_NOTE_TOOL_NAME
+from jarvis.society.runtime import SocietyRuntime
+from jarvis.society.surface import (
+ agent_id_of,
+ build_briefing,
+ capability_epoch,
+ society_system_extra,
+ society_tool_filter,
+ society_tools,
+)
+
+
+def _tool(name: str, desc: str = "x.") -> SimpleNamespace:
+ return SimpleNamespace(name=name, description=desc, risk_tier="monitor", schema={})
+
+
+TOOLS = {
+ "gmail": _tool("gmail", "Read and send mail."),
+ "search-web": _tool("search-web", "Search the web."),
+ "wiki-recall": _tool("wiki-recall", "Search the wiki."),
+ "wiki-ingest": _tool("wiki-ingest", "Write the wiki."),
+ "spawn-worker": _tool("spawn-worker", "Spawn."),
+ "cli_gh": _tool("cli_gh", "GitHub."),
+}
+
+
+async def rt(tmp_path: Path):
+ runtime = SocietyRuntime(tmp_path, brain_tools=lambda: TOOLS)
+ await runtime.ensure_started()
+ try:
+ yield runtime
+ finally:
+ await runtime.close()
+
+
+def test_agent_id_of():
+ assert agent_id_of("society:scout") == "scout"
+ assert agent_id_of("society:") is None
+ assert agent_id_of("abc123") is None
+
+
+def test_without_runtime_everything_is_empty():
+ assert runtime_mod.current_runtime() is None
+ session = SimpleNamespace(session_id="society:scout")
+ assert society_tools(None, None, session) == {}
+ assert society_tool_filter(session) is None
+
+
+async def test_tools_and_filter_follow_the_roster_row(rt: SocietyRuntime, tmp_path: Path):
+ await rt.roster.create(
+ name="Mailbox",
+ title="Gmail agent",
+ description="Handle my mail.",
+ focus=["plugin:gmail"],
+ denies=["cli:gh"],
+ )
+ cfg = SimpleNamespace(wiki=SimpleNamespace(vault_root=str(tmp_path / "vault")))
+ session = SimpleNamespace(session_id="society:mailbox")
+ own = society_tools(cfg, None, session)
+ assert set(own) == {MESSAGE_TOOL_NAME, WIKI_NOTE_TOOL_NAME}
+
+ # The briefing fills the cache the sync filter reads.
+ extra = await society_system_extra(cfg, None, session)
+ assert "## You are Mailbox — Gmail agent" in extra
+ merged = {**TOOLS, **own}
+ filt = society_tool_filter(session)
+ assert filt is not None
+ picked = list(filt(merged))
+ assert picked[:2] == [MESSAGE_TOOL_NAME, WIKI_NOTE_TOOL_NAME]
+ assert picked[2] == "gmail" # focus first
+ assert "spawn-worker" not in picked and "cli_gh" not in picked
+ assert "wiki-ingest" not in picked # writes go through the namespaced note tool
+ assert "wiki-recall" in picked
+
+
+async def test_allowlist_mode_keeps_only_grants(rt: SocietyRuntime, tmp_path: Path):
+ await rt.roster.create(
+ name="Narrow", grant_mode="allowlist", grants=["core:search-web"], focus=[]
+ )
+ cfg = SimpleNamespace(wiki=SimpleNamespace(vault_root=str(tmp_path / "vault")))
+ session = SimpleNamespace(session_id="society:narrow")
+ await society_system_extra(cfg, None, session)
+ filt = society_tool_filter(session)
+ assert filt is not None
+ picked = list(filt({**TOOLS, **society_tools(cfg, None, session)}))
+ assert picked == [MESSAGE_TOOL_NAME, WIKI_NOTE_TOOL_NAME, "search-web"]
+
+
+async def test_unknown_agent_gets_no_briefing(rt: SocietyRuntime):
+ session = SimpleNamespace(session_id="society:ghost")
+ assert await society_system_extra(None, None, session) == ""
+
+
+async def test_briefing_is_deterministic_and_complete(rt: SocietyRuntime):
+ await rt.roster.create(name="Scout", title="Research scout", tier="orchestrator")
+ mailbox, _ = await rt.roster.create(
+ name="Mailbox",
+ title="Gmail agent",
+ description="Read and answer mail; external mail only after approval.",
+ focus=["plugin:gmail"],
+ )
+ catalog = rt.catalog()
+ roster = await rt.roster.list()
+ a = build_briefing(mailbox, catalog, roster)
+ b = build_briefing(mailbox, catalog, roster)
+ assert a == b
+ assert "## Standing instructions" in a and "external mail only after approval" in a
+ assert "Reach for these first:\n- gmail (plugin:gmail): Read and send mail." in a
+ assert "Also available" in a and "built-in: search-web, wiki-ingest, wiki-recall" in a
+ assert "spawn-worker" not in a
+ assert f"Capability epoch: {capability_epoch(catalog)}" in a
+ assert "## The Jarvis ecosystem" in a and "society_message_agent" in a
+ assert "## Teammates\n- Jarvis — Lead (lead)\n- Scout — Research scout (orchestrator)" in a
+ assert "Mailbox" not in a.split("## Teammates")[1]
+ assert "You do not assign work" in a
+
+
+async def test_capability_epoch_changes_when_hands_change(rt: SocietyRuntime):
+ before = capability_epoch(rt.catalog())
+ rt._get_tools = lambda: {**TOOLS, "spotify": _tool("spotify")} # noqa: SLF001 — test seam
+ assert capability_epoch(rt.catalog()) != before