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): runtime, /api/society routes and the M1 contract test

rubenluetke10-beepd2511d16dc81
diff --git a/docs/os-parity.md b/docs/os-parity.md
index d2d1d4081a..f7fa334b3f 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -210,6 +210,7 @@ implementations, not stubs.
| Voice / audio (capture, playback, VAD, wake, STT, TTS, realtime) | Clean; headless disables voice honestly; WASAPI logic is inert-by-data off Windows |
| Core (launcher, config, keyring, restart, autostart, tray, elevation, paths) | Clean; per-OS autostart (Registry / LaunchAgent / XDG `.desktop`), keyring falls back to a 0600 file on headless hosts |
| Data / agents (wiki, contacts, telephony, sessions, missions, skills, self-mod, channels, MCP) | Clean; mission workers run on POSIX with a real process-group reaper |
+| Agent society substrate (roster, typed board, scheduler, rooms, mission bridge, `/api/society`) | Clean; pure asyncio + SQLite (`data/society.db`, WAL) and FastAPI, no OS API, no GPU, no audio. Full REST parity from a headless `python:3.11-slim` (`tests/contract/test_society_substrate.py` seeds two agents and exchanges typed messages with fakes only); the dynamic `jarvis api society …` CLI layer covers every route. FTS5 over knowledge summaries is optional — a SQLite without it degrades to plain reads (same class as P-05). Per-agent screens (`agent_screen`) are M6 and keep their own per-OS probes |
| Typed chat on the Jarvis surface (brain runner, folder tools, approval card, CLI seats as Jarvis) | Clean; pure asyncio + SQLite, no OS API. Every CLI spawn keeps `NO_WINDOW_CREATIONFLAGS` and UTF-8 stdio. The identity for a Claude Code seat travels as a FILE under the app data dir (`jarvis_harness.write_identity_file`, removed after the turn) because Windows caps a command line at 32 767 characters; Codex and agy take it on stdin (no limit), Grok Build a compact cut on argv (`COMPACT_MAX_CHARS`). The MCP session header and the approval bridge are transport-level and OS-neutral |
## Open parity gaps
diff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.py
new file mode 100644
index 0000000000..98bc746164
--- /dev/null
+++ b/jarvis/society/runtime.py
@@ -0,0 +1,233 @@
+"""The society runtime — one lazily built object wiring store, roster, rooms,
+scheduler and the mission bridge together.
+
+Built on the first REST call (``app.state.society_factory``), never at boot
+(AP-26). Every collaborator is reached through a getter so the runtime can
+be constructed in a test with fakes and in the server with the live
+mission manager, budget tracker, brain tool registry and skill registry.
+
+Dispatch (M1): an ``ASSIGN`` becomes a mission through the existing
+``MissionManager.dispatch`` — the worker runs under the agent's identity by
+prompt framing (name, title, standing instructions), and the ownership map
+lets the bridge attribute every mission event back to the agent. Per-agent
+model and tool grants ride the canonical chat (M2); missions inherit the
+global worker configuration until the worker runtime learns a per-agent
+override.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Callable, Iterable, Mapping
+from pathlib import Path
+from typing import Any
+
+from .bridge import MissionBridge
+from .capabilities import CapabilityRow, build_catalog
+from .events import MsgType, RoomState, SocietyEnvelope, Tier
+from .focus import derive_approval_rules, derive_focus
+from .rooms import Rooms
+from .roster import LEAD_AGENT_ID, AgentRecord, Roster
+from .scheduler import DeliverHook, SocietyScheduler
+from .store import SocietyStore
+
+log = logging.getLogger(__name__)
+
+__all__ = ["SocietyRuntime"]
+
+_DB_NAME = "society.db"
+
+
+def _agent_frame(agent: AgentRecord, task: str) -> str:
+ """The mission prompt that carries the agent's identity to a worker."""
+ lines = [
+ f"You are {agent.name}" + (f", {agent.title}" if agent.title else "") + ",",
+ f"a {agent.tier} agent in the user's agent society led by Jarvis.",
+ ]
+ if agent.description.strip():
+ lines += ["", "Standing instructions:", agent.description.strip()]
+ if agent.focus:
+ lines += ["", "Reach for these capabilities first: " + ", ".join(agent.focus)]
+ lines += ["", "Task:", task.strip()]
+ return "\n".join(lines)
+
+
+class SocietyRuntime:
+ def __init__(
+ self,
+ data_dir: Path,
+ *,
+ mission_manager: Callable[[], Any | None] | None = None,
+ mission_bus: Callable[[], Any | None] | None = None,
+ budget_tracker: Callable[[], Any | None] | None = None,
+ brain_tools: Callable[[], Mapping[str, Any] | None] | None = None,
+ skills: Callable[[], Iterable[Any] | None] | None = None,
+ deliver: DeliverHook | None = None,
+ ) -> None:
+ self._data_dir = Path(data_dir)
+ self._get_manager = mission_manager or (lambda: None)
+ self._get_mission_bus = mission_bus or (lambda: None)
+ self._get_budget = budget_tracker or (lambda: None)
+ self._get_tools = brain_tools or (lambda: None)
+ self._get_skills = skills or (lambda: None)
+ self._deliver = deliver
+ self.store = SocietyStore(self._data_dir / _DB_NAME)
+ self.roster = Roster(self.store)
+ self.rooms = Rooms(self.store)
+ self.scheduler = SocietyScheduler(
+ self.store,
+ self.roster,
+ dispatch=self._dispatch,
+ deliver=deliver,
+ budget_tracker=None,
+ )
+ self.bridge = MissionBridge(
+ self.store, owner_of=self.owner_of, on_run_ended=self.scheduler.note_run_ended
+ )
+ self._owners: dict[str, str] = {}
+ self._started = False
+
+ # ------------------------------------------------------------ lifecycle
+
+ async def ensure_started(self) -> SocietyRuntime:
+ if self._started:
+ return self
+ await self.store.open()
+ self.scheduler._budget = self._get_budget() # noqa: SLF001 — the runtime owns its scheduler
+ self.scheduler.attach()
+ bus = self._get_mission_bus()
+ if bus is not None:
+ self.bridge.attach(bus)
+ await self.seed_lead()
+ self._started = True
+ log.info("society runtime started (%s)", self.store.path)
+ return self
+
+ async def close(self) -> None:
+ self.scheduler.detach()
+ self.bridge.detach()
+ await self.store.close()
+ self._started = False
+
+ def set_deliver(self, deliver: DeliverHook | None) -> None:
+ """The chat binding (M2) installs the canonical-chat deliverer here."""
+ self._deliver = deliver
+ self.scheduler._deliver = deliver # noqa: SLF001 — the runtime owns its scheduler
+
+ async def seed_lead(self) -> AgentRecord:
+ """Jarvis is always on the roster as the one lead."""
+ lead, _ = await self.roster.create(
+ name="Jarvis",
+ title="Lead",
+ description=(
+ "The voice-steered lead of the society. Delegates, never does the work itself."
+ ),
+ tier=Tier.LEAD,
+ )
+ return lead
+
+ # ------------------------------------------------------------ catalog
+
+ def catalog(self) -> list[CapabilityRow]:
+ tools = self._get_tools() or {}
+ try:
+ skills = list(self._get_skills() or [])
+ except Exception: # noqa: BLE001 — a broken skill registry costs the skill rows only
+ log.warning("society: skill registry unavailable for the catalog", exc_info=True)
+ skills = []
+ return build_catalog(tools, skills)
+
+ def derive(self, title: str, description: str) -> tuple[list[str], dict[str, list[str]]]:
+ """``(focus, approval_rules)`` for a title/description pair."""
+ focus = derive_focus(title, description, self.catalog())
+ return focus, derive_approval_rules(description, focus)
+
+ # ------------------------------------------------------------ dispatch
+
+ def owner_of(self, mission_id: str) -> str | None:
+ return self._owners.get(mission_id)
+
+ async def _dispatch(self, target: AgentRecord, env: SocietyEnvelope) -> str:
+ manager = self._get_manager()
+ if manager is None:
+ raise RuntimeError("mission manager unavailable: the society cannot start work")
+ task = env.text or str(env.payload.get("task", "")) or "(no task text)"
+ language = env.payload.get("lang")
+ kwargs: dict[str, Any] = {
+ "prompt": _agent_frame(target, task),
+ "source_actor": "hauptjarvis",
+ }
+ if language in ("de", "en"):
+ kwargs["language"] = language
+ mission_id = await manager.dispatch(**kwargs)
+ self._owners[str(mission_id)] = target.agent_id
+ return str(mission_id)
+
+ # ------------------------------------------------------------ controls
+
+ async def engage_kill_switch(self) -> dict[str, Any]:
+ await self.store.set_kill_switch(True)
+ halted = await self.scheduler.halt_all()
+ settled = 0
+ for room in await self.rooms.list(state=RoomState.RUNNING):
+ await self.rooms.settle(room.room_id, reason="kill_switch")
+ settled += 1
+ manager = self._get_manager()
+ killed = 0
+ if manager is not None and hasattr(manager, "cancel"):
+ for mission_id in list(self._owners):
+ try:
+ await manager.cancel(mission_id)
+ killed += 1
+ except Exception: # noqa: BLE001 — a mission already gone is fine
+ log.debug("society kill switch: mission %s not cancellable", mission_id)
+ return {
+ "engaged": True,
+ "runs_halted": halted,
+ "rooms_settled": settled,
+ "missions_cancelled": killed,
+ }
+
+ async def release_kill_switch(self) -> dict[str, Any]:
+ await self.store.set_kill_switch(False)
+ return {"engaged": False}
+
+ async def status(self) -> dict[str, Any]:
+ agents = await self.roster.list()
+ running = self.scheduler.running
+ return {
+ "kill_switch": await self.store.kill_switch(),
+ "agents": len(agents),
+ "active_runs": len(running),
+ "running": running,
+ "last_seq": await self.store.last_seq(),
+ "rooms_running": len(await self.rooms.list(state=RoomState.RUNNING)),
+ "db_path": str(self.store.path),
+ }
+
+ async def say(
+ self,
+ *,
+ from_agent: str,
+ to_agent: str,
+ text: str,
+ trace_id: str | None = None,
+ msg_type: MsgType = MsgType.SAY,
+ payload: dict[str, Any] | None = None,
+ ) -> SocietyEnvelope:
+ """Append one envelope on behalf of ``from_agent`` (REST, user, tests)."""
+ body = dict(payload or {})
+ body["text"] = text
+ return await self.store.append_and_publish(
+ SocietyEnvelope(
+ msg_type=msg_type,
+ from_agent=from_agent,
+ to_agent=to_agent,
+ trace_id=trace_id or f"chat:{from_agent}:{to_agent}",
+ payload=body,
+ )
+ )
+
+ @property
+ def lead_id(self) -> str:
+ return LEAD_AGENT_ID
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 4b040e9433..b0a89bbe66 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -393,6 +393,7 @@ class WebServer:
from .setup_routes import router as setup_router
from .skills_routes import router as skills_router
from .socials_routes import router as socials_router
+ from .society_routes import router as society_router
from .starter_plan_routes import router as starter_plan_router
from .sub_agents_routes import router as sub_agents_router
from .tasks_routes import router as tasks_router
@@ -560,6 +561,13 @@ class WebServer:
app.state.agent_chat = None
app.state.agent_chat_factory = self._build_agent_chat_service
app.include_router(agent_chat_router)
+ # Agent society (jarvis/society) — the roster, the typed board, the
+ # scheduler and the mission bridge. Built on the first /api/society
+ # call from the factory (store = data/society.db); nothing opens on
+ # the boot path (AP-26).
+ app.state.society = None
+ app.state.society_factory = self._build_society_runtime
+ app.include_router(society_router)
app.include_router(drop_router)
# Default: no recorder wired up — _init_session_stack() in start()
# sets this once it succeeds.
@@ -3501,6 +3509,52 @@ class WebServer:
else:
logger.info("Friends-Stack live: Telegram-Channel disabled (config off)")
+ def _build_society_runtime(self) -> Any:
+ """Build the agent-society runtime on first use (see society_routes).
+
+ Every collaborator is a getter over ``app.state`` so the runtime
+ follows the live mission manager, budget tracker, brain tool surface
+ and skill registry — whichever of them exists at call time.
+ """
+ from jarvis.society.runtime import SocietyRuntime
+
+ data_dir = Path(getattr(getattr(self.cfg, "memory", None), "data_dir", None) or "data")
+ state = self.app.state
+
+ def _manager() -> Any | None:
+ return getattr(state, "mission_manager", None)
+
+ def _mission_bus() -> Any | None:
+ manager = getattr(state, "mission_manager", None)
+ return getattr(manager, "bus", None) if manager is not None else None
+
+ def _budget() -> Any | None:
+ return getattr(state, "missions_budget", None)
+
+ def _tools() -> Any | None:
+ brain = getattr(state, "brain", None)
+ tools = getattr(brain, "_tools", None)
+ return tools if tools is not None and hasattr(tools, "items") else None
+
+ def _skills() -> Any | None:
+ registry = getattr(state, "skill_registry", None)
+ if registry is None:
+ return None
+ lister = getattr(registry, "all", None) or getattr(registry, "list", None)
+ try:
+ return list(lister()) if callable(lister) else None
+ except Exception: # noqa: BLE001 — the catalog then shows no skills
+ return None
+
+ return SocietyRuntime(
+ data_dir,
+ mission_manager=_manager,
+ mission_bus=_mission_bus,
+ budget_tracker=_budget,
+ brain_tools=_tools,
+ skills=_skills,
+ )
+
def _build_agent_chat_service(self) -> Any:
"""Build the agent-chat service on first use (see agent_chat_routes)."""
from jarvis.agent_chat.service import AgentChatService
diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.py
new file mode 100644
index 0000000000..a8a26c4d7d
--- /dev/null
+++ b/jarvis/ui/web/society_routes.py
@@ -0,0 +1,408 @@
+"""REST surface of the agent society (``/api/society``).
+
+The runtime is built on first use from ``app.state.society_factory`` (set in
+``server.py``), so nothing opens on the boot path (AP-26). Every mutating
+route that starts spend or stops work carries ``x-jarvis-dangerous`` so the
+dynamic ``jarvis api society …`` CLI layer demands confirmation.
+
+The roster is user content: creating an agent executes nothing and is not
+dangerous; messaging one can trigger a turn (spend) and is; the kill switch
+is dangerous in both directions because releasing it resumes work.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from fastapi import APIRouter, HTTPException, Request
+from pydantic import BaseModel, Field
+
+from jarvis.society.events import MsgType
+from jarvis.society.failure_reasons import FailureReason, retry_action
+from jarvis.society.rooms import RoomError
+from jarvis.society.roster import RosterError
+from jarvis.society.runtime import SocietyRuntime
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/society", tags=["society"])
+
+
+# ------------------------------------------------------------------ runtime
+
+
+async def _runtime(request: Request) -> SocietyRuntime:
+ state = request.app.state
+ runtime = getattr(state, "society", None)
+ if runtime is None:
+ factory = getattr(state, "society_factory", None)
+ if factory is None:
+ raise HTTPException(503, "society runtime not configured")
+ try:
+ runtime = factory()
+ except Exception as exc: # noqa: BLE001 — surfaces as 503 with the reason in the log
+ log.warning("society: runtime could not be built: %s", exc)
+ raise HTTPException(503, "society runtime unavailable") from exc
+ state.society = runtime
+ await runtime.ensure_started()
+ return runtime
+
+
+def _typed_error(exc: RosterError | RoomError) -> HTTPException:
+ reason = exc.reason
+ status = 404 if reason is FailureReason.TARGET_UNKNOWN else 409
+ return HTTPException(
+ status,
+ {"reason": str(reason), "retry": str(retry_action(reason)), "detail": str(exc)},
+ )
+
+
+# ------------------------------------------------------------------- models
+
+
+class CreateAgentBody(BaseModel):
+ name: str = Field(min_length=1, max_length=40)
+ title: str = ""
+ description: str = ""
+ tier: str = "specialist"
+ parent_agent_id: str | None = None
+ provider: str = ""
+ model: str = ""
+ effort: str = ""
+ grant_mode: str | None = None
+ grants: list[str] | None = None
+ focus: list[str] | None = None
+ denies: list[str] | None = None
+ skills: list[str] | None = None
+ permission_ceiling: str | None = None
+ approval_rules: dict[str, list[str]] | None = None
+ daily_budget_usd: float | None = None
+ max_concurrent_runs: int | None = None
+ avatar: dict[str, Any] | None = None
+
+
+class PatchAgentBody(BaseModel):
+ title: str | None = None
+ description: str | None = None
+ tier: str | None = None
+ parent_agent_id: str | None = None
+ state: str | None = None
+ provider: str | None = None
+ model: str | None = None
+ effort: str | None = None
+ grant_mode: str | None = None
+ grants: list[str] | None = None
+ focus: list[str] | None = None
+ denies: list[str] | None = None
+ skills: list[str] | None = None
+ knowledge_scope: str | None = None
+ permission_ceiling: str | None = None
+ approval_rules: dict[str, list[str]] | None = None
+ daily_budget_usd: float | None = None
+ max_concurrent_runs: int | None = None
+ avatar: dict[str, Any] | None = None
+ checkpoint: str | None = None
+
+
+class MessageBody(BaseModel):
+ text: str = Field(min_length=1, max_length=20_000)
+ from_agent: str = "user"
+ msg_type: str = "SAY"
+ trace_id: str | None = None
+ payload: dict[str, Any] = Field(default_factory=dict)
+
+
+class AssignBody(BaseModel):
+ task: str = Field(min_length=1, max_length=20_000)
+ from_agent: str = "user"
+ trace_id: str | None = None
+ lang: str | None = None
+
+
+class OpenRoomBody(BaseModel):
+ members: list[str] = Field(min_length=2, max_length=6)
+ topic: str = ""
+ opened_by: str = "user"
+
+
+class RoomSayBody(BaseModel):
+ member: str
+ text: str = ""
+
+
+# ------------------------------------------------------------------- agents
+
+
+async def list_agents(request: Request, include_archived: bool = False) -> dict[str, Any]:
+ rt = await _runtime(request)
+ agents = await rt.roster.list(include_archived=include_archived)
+ running = rt.scheduler.running
+ rows = []
+ for agent in agents:
+ row = agent.to_dict()
+ if agent.state == "paused":
+ row["run_state"] = "paused"
+ elif agent.agent_id in running.values():
+ row["run_state"] = "working"
+ else:
+ row["run_state"] = "idle"
+ rows.append(row)
+ return {"agents": rows, "total": len(rows)}
+
+
+async def create_agent(body: CreateAgentBody, request: Request) -> dict[str, Any]:
+ rt = await _runtime(request)
+ fields = body.model_dump(exclude_none=True, exclude={"name", "title", "description", "tier"})
+ derived_focus, derived_rules = rt.derive(body.title, body.description)
+ if body.focus is None and derived_focus:
+ fields["focus"] = derived_focus
+ if body.approval_rules is None and derived_rules["require_approval"]:
+ fields["approval_rules"] = derived_rules
+ try:
+ agent, created = await rt.roster.create(
+ name=body.name,
+ title=body.title,
+ description=body.description,
+ tier=body.tier,
+ **fields,
+ )
+ except RosterError as exc:
+ raise _typed_error(exc) from exc
+ return {"agent": agent.to_dict(), "created": created}
+
+
[email protected]("/agents/{agent_id}")
+async def get_agent(agent_id: str, request: Request) -> dict[str, Any]:
+ rt = await _runtime(request)
+ agent = await rt.roster.resolve(agent_id)
+ if agent is None:
+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})
+ events = await rt.store.events_for_agent(agent.agent_id, limit=50)
+ return {
+ "agent": agent.to_dict(),
+ "recent_events": [e.model_dump() for e in events],
+ "active_runs": rt.scheduler.active_runs(agent.agent_id),
+ }
+
+
[email protected]("/agents/{agent_id}")
+async def patch_agent(agent_id: str, body: PatchAgentBody, request: Request) -> dict[str, Any]:
+ rt = await _runtime(request)
+ agent = await rt.roster.resolve(agent_id)
+ if agent is None:
+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})
+ fields = body.model_dump(exclude_none=True)
+ if ("title" in fields or "description" in fields) and "focus" not in fields:
+ title = fields.get("title", agent.title)
+ description = fields.get("description", agent.description)
+ derived_focus, derived_rules = rt.derive(title, description)
+ fields["focus"] = derived_focus
+ if "approval_rules" not in fields and derived_rules["require_approval"]:
+ fields["approval_rules"] = derived_rules
+ try:
+ updated = await rt.roster.update(agent.agent_id, fields)
+ except RosterError as exc:
+ raise _typed_error(exc) from exc
+ return {"agent": updated.to_dict()}
+
+
[email protected]("/agents/{agent_id}")
+async def archive_agent(agent_id: str, request: Request) -> dict[str, Any]:
+ rt = await _runtime(request)
+ agent = await rt.roster.resolve(agent_id)
+ if agent is None:
+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})
+ try:
+ archived = await rt.roster.archive(agent.agent_id)
+ except RosterError as exc:
+ raise _typed_error(exc) from exc
+ return {"agent": archived.to_dict()}
+
+
[email protected]("/agents/{agent_id}/message", openapi_extra={"x-jarvis-dangerous": True})
+async def message_agent(agent_id: str, body: MessageBody, request: Request) -> dict[str, Any]:
+ """Append a message to the agent (user → agent by default). May start a turn."""
+ rt = await _runtime(request)
+ agent = await rt.roster.resolve(agent_id)
+ if agent is None:
+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})
+ try:
+ msg_type = MsgType(body.msg_type)
+ except ValueError as exc:
+ raise HTTPException(422, f"msg_type must be one of {[str(m) for m in MsgType]}") from exc
+ if msg_type in (MsgType.ASSIGN, MsgType.ROOM_OPEN, MsgType.ROOM_SETTLE, MsgType.VETO):
+ raise HTTPException(422, "use /assign or /rooms for that message type")
+ env = await rt.say(
+ from_agent=body.from_agent,
+ to_agent=agent.agent_id,
+ text=body.text,
+ trace_id=body.trace_id,
+ msg_type=msg_type,
+ payload=body.payload,
+ )
+ return {"event": env.model_dump()}
+
+
[email protected]("/agents/{agent_id}/assign", openapi_extra={"x-jarvis-dangerous": True})
+async def assign_agent(agent_id: str, body: AssignBody, request: Request) -> dict[str, Any]:
+ """Give the agent a task: an ASSIGN the scheduler turns into real work."""
+ rt = await _runtime(request)
+ agent = await rt.roster.resolve(agent_id)
+ if agent is None:
+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})
+ payload: dict[str, Any] = {"text": body.task}
+ if body.lang:
+ payload["lang"] = body.lang
+ env = await rt.say(
+ from_agent=body.from_agent,
+ to_agent=agent.agent_id,
+ text=body.task,
+ trace_id=body.trace_id or f"task:{env_trace_seed()}",
+ msg_type=MsgType.ASSIGN,
+ payload=payload,
+ )
+ outcome = await rt.store.events_for_trace(env.trace_id)
+ verdict = next((e for e in outcome if e.seq and env.seq and e.seq > env.seq), None)
+ return {
+ "event": env.model_dump(),
+ "outcome": verdict.model_dump() if verdict else None,
+ }
+
+
+def env_trace_seed() -> str:
+ from jarvis.missions.ids import uuid7_str
+
+ return uuid7_str()
+
+
[email protected]("/agents/{agent_id}/kill", openapi_extra={"x-jarvis-dangerous": True})
+async def kill_agent(agent_id: str, request: Request) -> dict[str, Any]:
+ """Pause the agent and drop its run slots (its missions are cancelled when possible)."""
+ rt = await _runtime(request)
+ agent = await rt.roster.resolve(agent_id)
+ if agent is None:
+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})
+ dropped = 0
+ manager = rt._get_manager() # noqa: SLF001 — the route is the runtime's operator
+ for run_id, owner in list(rt.scheduler.running.items()):
+ if owner != agent.agent_id:
+ continue
+ rt.scheduler.note_run_ended(run_id)
+ dropped += 1
+ if manager is not None and hasattr(manager, "cancel"):
+ try:
+ await manager.cancel(run_id)
+ except Exception: # noqa: BLE001 — already gone is fine
+ log.debug("society kill: mission %s not cancellable", run_id)
+ paused = await rt.roster.update(agent.agent_id, {"state": "paused"})
+ return {"agent": paused.to_dict(), "runs_dropped": dropped}
+
+
+# ------------------------------------------------------------------- board
+
+
+async def list_events(
+ request: Request,
+ after_seq: int = 0,
+ trace_id: str | None = None,
+ agent_id: str | None = None,
+ limit: int = 200,
+) -> dict[str, Any]:
+ rt = await _runtime(request)
+ limit = max(1, min(int(limit), 1000))
+ if trace_id:
+ events = await rt.store.events_for_trace(trace_id)
+ elif agent_id:
+ events = await rt.store.events_for_agent(agent_id, after_seq=after_seq, limit=limit)
+ else:
+ events = await rt.store.events_since(after_seq, limit=limit)
+ return {"events": [e.model_dump() for e in events], "last_seq": await rt.store.last_seq()}
+
+
[email protected]("/agents/{agent_id}/inbox")
+async def agent_inbox(agent_id: str, request: Request, after_seq: int = 0) -> dict[str, Any]:
+ rt = await _runtime(request)
+ agent = await rt.roster.resolve(agent_id)
+ if agent is None:
+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})
+ events = await rt.store.inbox_for(agent.agent_id, after_seq=after_seq)
+ return {"events": [e.model_dump() for e in events]}
+
+
+# ----------------------------------------------------------------- catalog
+
+
[email protected]("/capabilities")
+async def list_capabilities(request: Request) -> dict[str, Any]:
+ rt = await _runtime(request)
+ rows = rt.catalog()
+ return {"capabilities": [r.to_dict() for r in rows], "total": len(rows)}
+
+
+# ------------------------------------------------------------------- rooms
+
+
+async def list_rooms(request: Request) -> dict[str, Any]:
+ rt = await _runtime(request)
+ return {"rooms": [r.to_dict() for r in await rt.rooms.list()]}
+
+
+async def open_room(body: OpenRoomBody, request: Request) -> dict[str, Any]:
+ rt = await _runtime(request)
+ for member in body.members:
+ if await rt.roster.resolve(member) is None:
+ raise HTTPException(
+ 404, {"reason": str(FailureReason.TARGET_UNKNOWN), "member": member}
+ )
+ try:
+ room = await rt.rooms.open(opened_by=body.opened_by, members=body.members, topic=body.topic)
+ except RoomError as exc:
+ raise _typed_error(exc) from exc
+ return {"room": room.to_dict()}
+
+
[email protected]("/rooms/{room_id}/say", openapi_extra={"x-jarvis-dangerous": True})
+async def room_say(room_id: str, body: RoomSayBody, request: Request) -> dict[str, Any]:
+ rt = await _runtime(request)
+ try:
+ room = await rt.rooms.say(room_id, body.member, body.text)
+ except RoomError as exc:
+ raise _typed_error(exc) from exc
+ return {"room": room.to_dict()}
+
+
[email protected]("/rooms/{room_id}/settle", openapi_extra={"x-jarvis-dangerous": True})
+async def room_settle(room_id: str, request: Request) -> dict[str, Any]:
+ rt = await _runtime(request)
+ try:
+ room = await rt.rooms.settle(room_id, reason="user", by="user")
+ except RoomError as exc:
+ raise _typed_error(exc) from exc
+ return {"room": room.to_dict()}
+
+
+# ----------------------------------------------------------------- controls
+
+
+async def society_status(request: Request) -> dict[str, Any]:
+ rt = await _runtime(request)
+ return await rt.status()
+
+
[email protected]("/kill-switch", openapi_extra={"x-jarvis-dangerous": True})
+async def engage_kill_switch(request: Request) -> dict[str, Any]:
+ rt = await _runtime(request)
+ return await rt.engage_kill_switch()
+
+
[email protected]("/kill-switch/release", openapi_extra={"x-jarvis-dangerous": True})
+async def release_kill_switch(request: Request) -> dict[str, Any]:
+ rt = await _runtime(request)
+ return await rt.release_kill_switch()
diff --git a/tests/contract/test_society_substrate.py b/tests/contract/test_society_substrate.py
new file mode 100644
index 0000000000..e64e89a9a0
--- /dev/null
+++ b/tests/contract/test_society_substrate.py
@@ -0,0 +1,92 @@
+"""M1 exit criterion (MASTERPLAN §8): two seeded agents exchange typed messages
+end to end on a headless box — REST in, board out, no GPU, no audio, no LLM,
+fakes only.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.society.runtime import SocietyRuntime
+from jarvis.ui.web.society_routes import router
+
+
+class FakeManager:
+ async def dispatch(self, *, prompt: str, **kwargs) -> str:
+ return "m-1"
+
+
+def test_two_agents_exchange_typed_messages_headless(tmp_path: Path) -> None:
+ manager = FakeManager()
+ runtime = SocietyRuntime(tmp_path, mission_manager=lambda: manager)
+ app = FastAPI()
+ app.include_router(router)
+ app.state.society_factory = lambda: runtime
+
+ with TestClient(app) as c:
+ # Seed.
+ scout = c.post(
+ "/api/society/agents",
+ json={"name": "Scout", "title": "Research scout", "tier": "orchestrator"},
+ ).json()["agent"]
+ archivist = c.post(
+ "/api/society/agents",
+ json={"name": "Archivist", "title": "Knowledge curator"},
+ ).json()["agent"]
+ assert scout["tier"] == "orchestrator" and archivist["tier"] == "specialist"
+
+ # Scout asks Archivist a typed QUERY; the scheduler routes it into the inbox.
+ query = c.post(
+ "/api/society/agents/archivist/message",
+ json={
+ "text": "Do we know the VPS provider?",
+ "from_agent": "scout",
+ "msg_type": "QUERY",
+ },
+ ).json()["event"]
+ assert query["msg_type"] == "QUERY" and query["seq"] == 1
+
+ inbox = c.get("/api/society/agents/archivist/inbox").json()["events"]
+ assert [e["msg_type"] for e in inbox] == ["QUERY"]
+
+ # Archivist answers on the same trace.
+ answer = c.post(
+ "/api/society/agents/scout/message",
+ json={
+ "text": "Yes: Hetzner, see the wiki.",
+ "from_agent": "archivist",
+ "msg_type": "ANSWER",
+ "trace_id": query["trace_id"],
+ "payload": {"refs": ["wiki:society/archivist/vps.md"]},
+ },
+ ).json()["event"]
+ assert answer["parent_event_id"] is None and answer["trace_id"] == query["trace_id"]
+
+ # The board shows the exchange in order, typed, attributed.
+ thread = c.get("/api/society/events", params={"trace_id": query["trace_id"]}).json()[
+ "events"
+ ]
+ assert [(e["from_agent"], e["to_agent"], e["msg_type"]) for e in thread] == [
+ ("scout", "archivist", "QUERY"),
+ ("archivist", "scout", "ANSWER"),
+ ]
+ assert thread[1]["payload"]["refs"] == ["wiki:society/archivist/vps.md"]
+
+ # An orchestrator may assign; a specialist may not — both visible on the board.
+ ok = c.post(
+ "/api/society/agents/archivist/assign",
+ json={"task": "Curate it.", "from_agent": "scout"},
+ ).json()
+ assert ok["outcome"]["msg_type"] == "CLAIM"
+ no = c.post(
+ "/api/society/agents/scout/assign", json={"task": "Nope.", "from_agent": "archivist"}
+ ).json()
+ assert no["outcome"]["msg_type"] == "VETO"
+ assert no["outcome"]["payload"]["reason"] == "tier_not_allowed"
+
+ status = c.get("/api/society/status").json()
+ assert status["agents"] == 3 # jarvis + scout + archivist
+ assert status["kill_switch"] is False
diff --git a/tests/unit/ui/web/test_society_routes.py b/tests/unit/ui/web/test_society_routes.py
new file mode 100644
index 0000000000..8f9207143e
--- /dev/null
+++ b/tests/unit/ui/web/test_society_routes.py
@@ -0,0 +1,209 @@
+"""/api/society: roster CRUD with derived focus, messaging, assign, board, controls."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.society.runtime import SocietyRuntime
+from jarvis.ui.web.society_routes import router
+
+
+class FakeManager:
+ def __init__(self) -> None:
+ self.prompts: list[str] = []
+ self.cancelled: list[str] = []
+ self.bus = SimpleNamespace(subscribe_all=lambda h: lambda: None)
+
+ async def dispatch(self, *, prompt: str, **kwargs) -> str:
+ self.prompts.append(prompt)
+ return f"m-{len(self.prompts)}"
+
+ async def cancel(self, mission_id: str) -> None:
+ self.cancelled.append(mission_id)
+
+
+def _tool(name: str, desc: str) -> 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."),
+ "spawn-worker": _tool("spawn-worker", "Spawn."),
+}
+
+
+def client(tmp_path: Path):
+ manager = FakeManager()
+ runtime = SocietyRuntime(
+ tmp_path,
+ mission_manager=lambda: manager,
+ mission_bus=lambda: manager.bus,
+ brain_tools=lambda: TOOLS,
+ )
+ app = FastAPI()
+ app.include_router(router)
+ app.state.society = None
+ app.state.society_factory = lambda: runtime
+ with TestClient(app) as c:
+ yield c, manager
+
+
+def test_lead_is_seeded_and_listed(client):
+ c, _ = client
+ body = c.get("/api/society/agents").json()
+ assert [a["agent_id"] for a in body["agents"]] == ["jarvis"]
+ assert body["agents"][0]["tier"] == "lead"
+ assert body["agents"][0]["run_state"] == "idle"
+
+
+def test_create_derives_focus_and_rules(client):
+ c, _ = client
+ res = c.post(
+ "/api/society/agents",
+ json={
+ "name": "Mailbox",
+ "title": "Gmail agent",
+ "description": "You read and answer my mail; external mail only after approval.",
+ },
+ )
+ assert res.status_code == 200, res.text
+ agent = res.json()["agent"]
+ assert res.json()["created"] is True
+ assert agent["focus"] == ["plugin:gmail"]
+ assert agent["approval_rules"]["require_approval"] == ["plugin:gmail:send"]
+ assert agent["session_id"] == "society:mailbox"
+ # Adopt-before-mint through REST.
+ again = c.post("/api/society/agents", json={"name": "mailbox"}).json()
+ assert again["created"] is False
+
+
+def test_patch_rederives_focus_on_description_change(client):
+ c, _ = client
+ c.post("/api/society/agents", json={"name": "Scout", "description": "Research on the web."})
+ first = c.get("/api/society/agents/scout").json()["agent"]
+ assert first["focus"] == ["core:search-web"]
+ patched = c.patch(
+ "/api/society/agents/scout", json={"description": "Handle my mail inbox."}
+ ).json()["agent"]
+ assert patched["focus"] == ["plugin:gmail"]
+ explicit = c.patch("/api/society/agents/scout", json={"focus": []}).json()["agent"]
+ assert explicit["focus"] == []
+
+
+def test_typed_errors(client):
+ c, _ = client
+ assert c.get("/api/society/agents/ghost").status_code == 404
+ bad = c.post("/api/society/agents", json={"name": "Boss", "tier": "lead"})
+ assert bad.status_code == 409
+ assert bad.json()["detail"]["reason"] == "tier_not_allowed"
+ assert c.delete("/api/society/agents/jarvis").status_code == 409
+ c.post("/api/society/agents", json={"name": "Scout"})
+ worse = c.patch("/api/society/agents/scout", json={"permission_ceiling": "block"})
+ assert worse.status_code == 409
+
+
+def test_message_lands_in_inbox_and_board(client):
+ c, _ = client
+ c.post("/api/society/agents", json={"name": "Scout"})
+ res = c.post("/api/society/agents/scout/message", json={"text": "hello"})
+ assert res.status_code == 200
+ event = res.json()["event"]
+ assert event["msg_type"] == "SAY" and event["from_agent"] == "user"
+ inbox = c.get("/api/society/agents/scout/inbox").json()["events"]
+ assert [e["payload"]["text"] for e in inbox] == ["hello"]
+ board = c.get("/api/society/events").json()
+ assert board["last_seq"] == 1
+ assert c.get("/api/society/events", params={"trace_id": event["trace_id"]}).json()["events"]
+
+
+def test_assign_dispatches_a_framed_mission(client):
+ c, manager = client
+ c.post(
+ "/api/society/agents",
+ json={"name": "Scout", "title": "Research scout", "description": "Find things on the web."},
+ )
+ res = c.post("/api/society/agents/scout/assign", json={"task": "Find the best VPS."})
+ assert res.status_code == 200, res.text
+ body = res.json()
+ assert body["outcome"]["msg_type"] == "CLAIM"
+ assert body["outcome"]["payload"]["run_id"] == "m-1"
+ prompt = manager.prompts[0]
+ assert prompt.startswith("You are Scout, Research scout,")
+ assert "Find things on the web." in prompt and "Find the best VPS." in prompt
+ assert "core:search-web" in prompt
+ status = c.get("/api/society/status").json()
+ assert status["active_runs"] == 1 and status["running"] == {"m-1": "scout"}
+ listed = c.get("/api/society/agents").json()["agents"]
+ assert next(a for a in listed if a["agent_id"] == "scout")["run_state"] == "working"
+
+
+def test_assign_from_specialist_is_vetoed(client):
+ c, manager = client
+ c.post("/api/society/agents", json={"name": "Scout"})
+ c.post("/api/society/agents", json={"name": "Quill"})
+ res = c.post("/api/society/agents/quill/assign", json={"task": "x", "from_agent": "scout"})
+ assert res.json()["outcome"]["msg_type"] == "VETO"
+ assert res.json()["outcome"]["payload"]["reason"] == "tier_not_allowed"
+ assert manager.prompts == []
+
+
+def test_kill_agent_drops_runs_and_pauses(client):
+ c, manager = client
+ c.post("/api/society/agents", json={"name": "Scout"})
+ c.post("/api/society/agents/scout/assign", json={"task": "go"})
+ res = c.post("/api/society/agents/scout/kill")
+ assert res.json()["runs_dropped"] == 1
+ assert res.json()["agent"]["state"] == "paused"
+ assert manager.cancelled == ["m-1"]
+
+
+def test_kill_switch_round_trip(client):
+ c, _ = client
+ c.post("/api/society/agents", json={"name": "Scout"})
+ on = c.post("/api/society/kill-switch").json()
+ assert on["engaged"] is True
+ assert c.get("/api/society/status").json()["kill_switch"] is True
+ vetoed = c.post("/api/society/agents/scout/assign", json={"task": "x"}).json()
+ assert vetoed["outcome"]["payload"]["reason"] == "kill_switch"
+ assert c.post("/api/society/kill-switch/release").json()["engaged"] is False
+
+
+def test_capabilities_catalog_hides_dispatch(client):
+ c, _ = client
+ ids = [r["id"] for r in c.get("/api/society/capabilities").json()["capabilities"]]
+ assert ids == ["plugin:gmail", "core:search-web"]
+
+
+def test_rooms_over_rest(client):
+ c, _ = client
+ c.post("/api/society/agents", json={"name": "Scout"})
+ c.post("/api/society/agents", json={"name": "Quill"})
+ missing = c.post("/api/society/rooms", json={"members": ["scout", "ghost"]})
+ assert missing.status_code == 404
+ room = c.post("/api/society/rooms", json={"members": ["scout", "quill"], "topic": "t"}).json()[
+ "room"
+ ]
+ assert room["next_speaker"] == "scout"
+ wrong = c.post(
+ f"/api/society/rooms/{room['room_id']}/say", json={"member": "quill", "text": "me"}
+ )
+ assert wrong.status_code == 409
+ ok = c.post(f"/api/society/rooms/{room['room_id']}/say", json={"member": "scout", "text": "hi"})
+ assert ok.json()["room"]["message_count"] == 1
+ settled = c.post(f"/api/society/rooms/{room['room_id']}/settle").json()["room"]
+ assert settled["state"] == "settled"
+ assert c.get("/api/society/rooms").json()["rooms"][0]["room_id"] == room["room_id"]
+
+
+def test_missing_factory_is_503():
+ app = FastAPI()
+ app.include_router(router)
+ with TestClient(app) as c:
+ assert c.get("/api/society/status").status_code == 503