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): a message between two agents reaches the island

rubenluetke10-beepef4be3081e14
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index d6b7a80e42..670e227500 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -2164,6 +2164,72 @@ class SocietyQuestChanged(Event):
title: str = ""
+@dataclass(frozen=True, slots=True)
+class SocietyMessageSent(Event):
+ """One agent said something to another, or into a room.
+
+ The island's only source for the talk/call animation: two figures turn to
+ each other and speak, or a signal arcs across the map between them.
+ Published by :class:`jarvis.society.world_feed.WorldFeed` after the
+ envelope is on disk; the WebSocket forwards it like every other bus event.
+
+ ``text`` is a BUBBLE-SIZED PREVIEW, never the body. The record stays behind
+ ``GET /api/society/events?trace_id=...`` and in the receiver's own chat --
+ a message body is not broadcast to every open window.
+
+ The board's own trace rides as ``society_trace``: ``Event.trace_id`` is a
+ UUID and the WS sanitizer lifts it out of the payload, so a field of that
+ name here would silently vanish.
+ """
+
+ #: The board envelope's uuid7 -- a stable key for dedupe and deep links.
+ event_id: str = ""
+ #: Server-assigned board sequence, monotonic. The client drops anything
+ #: it has already drawn, so an overlapping subscription is harmless.
+ seq: int = 0
+ #: ``MsgType``: SAY | QUERY | ANSWER | PROPOSE.
+ msg_type: str = ""
+ from_agent: str = ""
+ #: "" means the line went into a room rather than to one teammate.
+ to_agent: str = ""
+ #: "" means a direct message.
+ room_id: str = ""
+ #: Named for the builtin it would otherwise shadow (``round``).
+ room_round: int = 0
+ #: ``chat:<a>:<b>`` or ``room:<id>``.
+ society_trace: str = ""
+ #: Whitespace-collapsed preview, cut on a word boundary.
+ text: str = ""
+ #: Length of the original, so the bubble can offer "read the rest".
+ text_chars: int = 0
+ truncated: bool = False
+
+
+@dataclass(frozen=True, slots=True)
+class SocietyRoomChanged(Event):
+ """A bounded group discussion opened or settled (``jarvis/society/rooms.py``).
+
+ The members are already standing at the Town Hall -- the checkpoint engine
+ put them there. This only tells the island that the table is in session,
+ which round it is on, and why it broke up.
+ """
+
+ room_id: str = ""
+ #: "open" | "settle".
+ phase: str = ""
+ opened_by: str = ""
+ members: tuple[str, ...] = ()
+ #: Preview of the room's topic (``ROOM_OPEN`` only).
+ topic: str = ""
+ #: message_cap | round_cap | silence | user | kill_switch (``settle`` only).
+ reason: str = ""
+ rounds: int = 0
+ messages: int = 0
+ max_rounds: int = 0
+ max_messages: int = 0
+ society_trace: str = ""
+
+
# ----------------------------------------------------------------------
# Visible-Feedback Contract (ADR-0016)
# ----------------------------------------------------------------------
diff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.py
index f91896c952..c2d4892852 100644
--- a/jarvis/society/runtime.py
+++ b/jarvis/society/runtime.py
@@ -38,6 +38,7 @@ from .roster import LEAD_AGENT_ID, AgentRecord, Roster
from .scheduler import DeliverHook, SocietyScheduler
from .seeds import seed_first_run
from .store import SocietyStore
+from .world_feed import WorldFeed
log = logging.getLogger(__name__)
@@ -140,6 +141,9 @@ class SocietyRuntime:
self.memory = SocietyMemory(self, on_activity=self.checkpoints.note_memory_activity)
#: The Quest Board: the person's jobs, routed to one taker, read back off the board.
self.quests = Quests(self)
+ #: Speech on the board, projected onto the island: two agents talking
+ #: turn to each other, two agents apart call across the map.
+ self.world_feed = WorldFeed(self, publish=event_publish)
#: 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] = {}
@@ -164,6 +168,7 @@ class SocietyRuntime:
self.bridge.attach(bus)
self.checkpoints.attach()
self.quests.attach()
+ self.world_feed.attach()
await self.seed_lead()
if self._seed_starter_team:
created = await seed_first_run(self.roster, self.store)
@@ -199,6 +204,7 @@ class SocietyRuntime:
self.bridge.detach()
self.checkpoints.detach()
self.quests.detach()
+ self.world_feed.detach()
await self.store.close()
self._started = False
if current_runtime() is self:
diff --git a/jarvis/society/world_feed.py b/jarvis/society/world_feed.py
new file mode 100644
index 0000000000..70364eb65b
--- /dev/null
+++ b/jarvis/society/world_feed.py
@@ -0,0 +1,160 @@
+"""Speech on the board, projected onto the island.
+
+The society bus carries every envelope. The island only cares about the six
+that are somebody TALKING -- ``SAY | QUERY | ANSWER | PROPOSE`` and the two
+room brackets. Everything else already reaches the world through the
+checkpoint engine, and pushing it twice would tell the same story in two
+voices.
+
+This is a projection, not a second truth (MASTERPLAN 2.7): it derives nothing,
+stores nothing and can refuse nothing. A failure here loses one animation and
+never touches the append path (AP-18) -- and it is logged rather than
+swallowed (AP-30).
+
+What crosses the wire is a PREVIEW. ``MessageAgentTool`` allows 8 000
+characters; a bubble over a figure's head holds about four short lines, every
+window keeps the last 500 events in memory, and a body is already readable in
+the receiver's chat and behind ``GET /api/society/events``. So the world gets
+``_BUBBLE_CHARS`` characters and a flag saying there is more.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Callable
+from typing import Any, Final
+
+from .events import MsgType, SocietyEnvelope
+
+log = logging.getLogger(__name__)
+
+__all__ = ["ROOM_TYPES", "VISIBLE_TYPES", "WorldFeed", "preview"]
+
+#: A line one agent addressed to another; the island draws a bubble for each.
+VISIBLE_TYPES: Final[frozenset[MsgType]] = frozenset(
+ {MsgType.SAY, MsgType.QUERY, MsgType.ANSWER, MsgType.PROPOSE}
+)
+#: The brackets around a bounded room (rooms.py).
+ROOM_TYPES: Final[frozenset[MsgType]] = frozenset({MsgType.ROOM_OPEN, MsgType.ROOM_SETTLE})
+
+#: How much of a message reaches the island. Four short lines in a bubble at
+#: the default zoom; past that nobody reads the map, they read the feed.
+_BUBBLE_CHARS: Final[int] = 180
+#: A room's topic sits on a banner over the Town Hall -- one line, not four.
+_TOPIC_CHARS: Final[int] = 80
+
+
+def preview(text: str, limit: int = _BUBBLE_CHARS) -> tuple[str, int, bool]:
+ """Bubble-sized ``text``: ``(preview, original_length, truncated)``.
+
+ Whitespace is collapsed so a Markdown block does not become a twenty-line
+ bubble, and the cut lands on a word boundary so no word is sliced in half.
+ """
+ original = len(text)
+ flat = " ".join(text.split())
+ if len(flat) <= limit:
+ return flat, original, False
+ cut = flat[:limit]
+ space = cut.rfind(" ")
+ # A single word longer than the limit has no boundary to cut on; take it
+ # whole rather than returning an ellipsis and nothing else.
+ if space > limit // 2:
+ cut = cut[:space]
+ return cut.rstrip() + "…", original, True
+
+
+class WorldFeed:
+ """The society bus subscriber that puts speech on the app bus.
+
+ Same shape as :class:`jarvis.society.quests.Quests` -- ``attach`` /
+ ``detach`` around one ``subscribe_all``, and a guarded publish that falls
+ back to the process default bus when the app did not inject one.
+ """
+
+ def __init__(self, runtime: Any, *, publish: Callable[[Any], Any] | None = None) -> None:
+ self._runtime = runtime
+ self._publish = publish
+ self._unsubscribe: Callable[[], None] | None = None
+
+ # ------------------------------------------------------------ wiring
+
+ def attach(self) -> None:
+ if self._unsubscribe is None:
+ self._unsubscribe = self._runtime.store.bus.subscribe_all(self._on_envelope)
+
+ def detach(self) -> None:
+ if self._unsubscribe is not None:
+ self._unsubscribe()
+ self._unsubscribe = None
+
+ # ------------------------------------------------------------ the feed
+
+ async def _on_envelope(self, env: SocietyEnvelope) -> None:
+ if env.msg_type in VISIBLE_TYPES:
+ await self._announce(self._message_event(env))
+ elif env.msg_type in ROOM_TYPES:
+ await self._announce(self._room_event(env))
+
+ @staticmethod
+ def _room_of(env: SocietyEnvelope) -> str:
+ room = env.payload.get("room_id")
+ if isinstance(room, str) and room:
+ return room
+ if env.trace_id.startswith("room:"):
+ return env.trace_id[len("room:") :]
+ return ""
+
+ def _message_event(self, env: SocietyEnvelope) -> Any:
+ from jarvis.core.events import SocietyMessageSent
+
+ text, chars, truncated = preview(env.text)
+ room_round = env.payload.get("round")
+ return SocietyMessageSent(
+ source_layer="society",
+ event_id=env.event_id,
+ seq=env.seq or 0,
+ msg_type=str(env.msg_type),
+ from_agent=env.from_agent,
+ to_agent=env.to_agent or "",
+ room_id=self._room_of(env),
+ room_round=room_round if isinstance(room_round, int) else 0,
+ society_trace=env.trace_id,
+ text=text,
+ text_chars=chars,
+ truncated=truncated,
+ )
+
+ def _room_event(self, env: SocietyEnvelope) -> Any:
+ from jarvis.core.events import SocietyRoomChanged
+
+ payload = env.payload
+ opening = env.msg_type is MsgType.ROOM_OPEN
+ members = payload.get("members")
+ topic, _, _ = preview(env.text, _TOPIC_CHARS) if opening else ("", 0, False)
+ return SocietyRoomChanged(
+ source_layer="society",
+ room_id=self._room_of(env),
+ phase="open" if opening else "settle",
+ opened_by=env.from_agent,
+ members=tuple(str(m) for m in members) if isinstance(members, list) else (),
+ topic=topic,
+ reason=str(payload.get("reason") or ""),
+ rounds=int(payload.get("rounds") or 0),
+ messages=int(payload.get("messages") or 0),
+ max_rounds=int(payload.get("max_rounds") or 0),
+ max_messages=int(payload.get("max_messages") or 0),
+ society_trace=env.trace_id,
+ )
+
+ async def _announce(self, event: Any) -> None:
+ try:
+ if self._publish is not None:
+ maybe = self._publish(event)
+ else:
+ from jarvis.core.bus import get_default_bus
+
+ maybe = get_default_bus().publish(event)
+ if hasattr(maybe, "__await__"):
+ await maybe
+ except Exception: # noqa: BLE001 — a missed push costs one animation, never an append
+ log.debug("society world feed: speech not pushed", exc_info=True)
diff --git a/tests/unit/society/test_world_feed.py b/tests/unit/society/test_world_feed.py
new file mode 100644
index 0000000000..575be4095d
--- /dev/null
+++ b/tests/unit/society/test_world_feed.py
@@ -0,0 +1,220 @@
+"""Speech on the board reaches the island -- and nothing else does."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.core.events import SocietyMessageSent, SocietyRoomChanged
+from jarvis.society.events import MsgType
+from jarvis.society.runtime import SocietyRuntime
+from jarvis.society.world_feed import ROOM_TYPES, VISIBLE_TYPES, WorldFeed, preview
+from jarvis.ui.web.schema import event_to_ws_envelope
+
+_REPO = Path(__file__).resolve().parents[3]
+_CONVERSATION_TS = _REPO / "jarvis/ui/web/frontend/src/components/society/world/conversation.ts"
+
+
+async def rt(tmp_path: Path):
+ pushed: list[Any] = []
+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False, event_publish=pushed.append)
+ await runtime.ensure_started()
+ await runtime.roster.create(name="Scout")
+ await runtime.roster.create(name="Archivist")
+ pushed.clear()
+ try:
+ yield runtime, pushed
+ finally:
+ await runtime.close()
+
+
+def _messages(pushed: list[Any]) -> list[SocietyMessageSent]:
+ return [e for e in pushed if isinstance(e, SocietyMessageSent)]
+
+
+def _rooms(pushed: list[Any]) -> list[SocietyRoomChanged]:
+ return [e for e in pushed if isinstance(e, SocietyRoomChanged)]
+
+
+# --------------------------------------------------------------- preview
+
+
+def test_preview_collapses_whitespace_and_keeps_short_text_whole():
+ text, chars, cut = preview(" hello\n\n world ")
+ assert (text, chars, cut) == ("hello world", 18, False)
+
+
+def test_preview_cuts_on_a_word_boundary_and_reports_the_original():
+ body = "word " * 200
+ text, chars, cut = preview(body)
+ assert cut is True
+ assert chars == len(body)
+ assert len(text) <= 181 # the limit plus the ellipsis
+ assert text.endswith("…")
+ assert not text.rstrip("…").endswith("wor") # never sliced mid-word
+
+
+def test_preview_takes_one_very_long_word_whole_rather_than_only_an_ellipsis():
+ text, _, cut = preview("x" * 400)
+ assert cut is True
+ assert len(text.rstrip("…")) == 180
+
+
+# --------------------------------------------------------- direct messages
+
+
+async def test_a_message_between_two_agents_reaches_the_island_once(rt):
+ runtime, pushed = rt
+ await runtime.say(from_agent="scout", to_agent="archivist", text="Found the manifest.")
+
+ sent = _messages(pushed)
+ assert len(sent) == 1
+ event = sent[0]
+ assert event.from_agent == "scout"
+ assert event.to_agent == "archivist"
+ assert event.msg_type == "SAY"
+ assert event.society_trace == "chat:scout:archivist"
+ assert event.text == "Found the manifest."
+ assert event.truncated is False
+ assert event.seq > 0
+ assert event.event_id
+ assert event.room_id == ""
+ assert event.source_layer == "society"
+
+
+async def test_every_talking_type_is_forwarded(rt):
+ runtime, pushed = rt
+ for kind in (MsgType.QUERY, MsgType.ANSWER, MsgType.PROPOSE):
+ await runtime.say(from_agent="scout", to_agent="archivist", text="ping", msg_type=kind)
+ assert [e.msg_type for e in _messages(pushed)] == ["QUERY", "ANSWER", "PROPOSE"]
+
+
+async def test_a_body_is_never_broadcast_in_full(rt):
+ runtime, pushed = rt
+ body = "sentence. " * 400
+ await runtime.say(from_agent="scout", to_agent="archivist", text=body)
+
+ event = _messages(pushed)[0]
+ assert event.truncated is True
+ assert len(event.text) <= 181
+ assert event.text_chars == len(body)
+
+
+async def test_the_plumbing_types_stay_off_the_island(rt):
+ runtime, pushed = rt
+ for kind in (MsgType.CLAIM, MsgType.RESULT, MsgType.HOLD, MsgType.VETO, MsgType.DIGEST):
+ await runtime.say(from_agent="scheduler", to_agent="scout", text="internal", msg_type=kind)
+ assert _messages(pushed) == []
+ assert _rooms(pushed) == []
+
+
+# ------------------------------------------------------------------ rooms
+
+
+async def test_a_room_opens_speaks_and_settles(rt):
+ runtime, pushed = rt
+ room = await runtime.rooms.open(
+ opened_by="jarvis", members=["scout", "archivist"], topic="Plan the week"
+ )
+ await runtime.rooms.say(room.room_id, "scout", "I will take the mail.")
+ await runtime.rooms.settle(room.room_id, reason="user", by="user")
+
+ opened, settled = _rooms(pushed)
+ assert opened.phase == "open"
+ assert opened.members == ("scout", "archivist")
+ assert opened.topic == "Plan the week"
+ assert (opened.max_rounds, opened.max_messages) == (3, 10)
+ assert opened.society_trace == f"room:{room.room_id}"
+
+ said = _messages(pushed)
+ assert len(said) == 1
+ assert said[0].room_id == room.room_id
+ assert said[0].to_agent == ""
+ assert said[0].room_round == 1
+ assert said[0].from_agent == "scout"
+
+ assert settled.phase == "settle"
+ assert settled.reason == "user"
+ assert settled.messages == 1
+
+
+# ------------------------------------------------------------- resilience
+
+
+async def test_attaching_twice_subscribes_once(rt):
+ runtime, pushed = rt
+ before = runtime.store.bus.active_subs
+ runtime.world_feed.attach()
+ assert runtime.store.bus.active_subs == before
+
+ await runtime.say(from_agent="scout", to_agent="archivist", text="once")
+ assert len(_messages(pushed)) == 1
+
+
+async def test_a_failing_publisher_never_breaks_the_append(tmp_path: Path):
+ def boom(_event: Any) -> None:
+ raise RuntimeError("no bus today")
+
+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False, event_publish=boom)
+ await runtime.ensure_started()
+ try:
+ await runtime.roster.create(name="Scout")
+ await runtime.roster.create(name="Archivist")
+ env = await runtime.say(from_agent="scout", to_agent="archivist", text="still lands")
+ assert env.seq is not None
+ assert len(await runtime.store.events_for_trace("chat:scout:archivist")) == 1
+ finally:
+ await runtime.close()
+
+
+async def test_detach_stops_the_feed(rt):
+ runtime, pushed = rt
+ runtime.world_feed.detach()
+ await runtime.say(from_agent="scout", to_agent="archivist", text="into the void")
+ assert _messages(pushed) == []
+
+
+# ------------------------------------------------------------ the wire
+
+
+async def test_the_event_survives_the_websocket_sanitizer(rt):
+ runtime, pushed = rt
+ room = await runtime.rooms.open(opened_by="jarvis", members=["scout", "archivist"])
+ await runtime.say(from_agent="scout", to_agent="archivist", text="hello")
+
+ message = event_to_ws_envelope(_messages(pushed)[0])
+ assert message["event_name"] == "SocietyMessageSent"
+ assert message["payload"]["society_trace"] == "chat:scout:archivist"
+ # The base UUID owns `trace_id`; ours must not have been shadowed away.
+ assert "trace_id" not in message["payload"]
+
+ opened = event_to_ws_envelope(_rooms(pushed)[0])
+ assert opened["event_name"] == "SocietyRoomChanged"
+ assert opened["payload"]["members"] == ["scout", "archivist"]
+ assert opened["payload"]["room_id"] == room.room_id
+
+
+# ------------------------------------------------------------- drift guard
+
+
+def test_the_world_only_reacts_to_types_the_board_can_produce():
+ assert (VISIBLE_TYPES | ROOM_TYPES) <= set(MsgType)
+ assert VISIBLE_TYPES.isdisjoint(ROOM_TYPES)
+
+
[email protected](not _CONVERSATION_TS.exists(), reason="the world layer is not built yet")
+def test_the_typescript_half_lists_the_same_types():
+ source = _CONVERSATION_TS.read_text(encoding="utf-8")
+ match = re.search(r"WORLD_MSG_TYPES[^=]*=\s*\[(.*?)\]", source, re.S)
+ assert match, "conversation.ts must export WORLD_MSG_TYPES"
+ listed = set(re.findall(r'"([A-Z_]+)"', match.group(1)))
+ assert listed == {str(t) for t in VISIBLE_TYPES | ROOM_TYPES}
+
+
+def test_the_relay_is_wired_into_the_runtime(tmp_path: Path):
+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False)
+ assert isinstance(runtime.world_feed, WorldFeed)