Skip to content

Self-improving AI Employees for everyone

refactor(plugin-extraction): V + Q + T -- lazy broadcasts, CloudEvents builders, ServiceSingleton

trohitgc0d935713c85
diff --git a/server/main.py b/server/main.py
index db08e326..459b2cb3 100644
--- a/server/main.py
+++ b/server/main.py
@@ -309,6 +309,20 @@ async def lifespan(app: FastAPI):
except Exception as exc:
logger.warning("[CLI MCP] lifespan init failed: %s", exc)
+ # One-time status-broadcaster refresh: populates the cache and runs
+ # the load-bearing auto-reconnects (Telegram bot via stored token,
+ # Android relay via stored pairing). Per-WS-client refresh used to
+ # do this on every connect, which produced an M-by-N storm under
+ # PartySocket's auto-reconnect on every page nav / network blip --
+ # the refresh now runs ONCE at startup, and state changes after
+ # that flow through the originating code path's event-driven
+ # broadcasts (whatsapp `_handle_event`, telegram `_broadcast_status`,
+ # OAuth callbacks, android relay broadcaster).
+ #
+ # Spawned as a background task so a slow upstream (Telegram getMe,
+ # Twitter token validation) doesn't block lifespan startup.
+ asyncio.create_task(get_status_broadcaster()._refresh_all_services())
+
_startup_log("All services initialized")
print("Application startup complete", flush=True)
yield
diff --git a/server/nodes/email/_himalaya.py b/server/nodes/email/_himalaya.py
index 33b2de9c..3be85e8b 100644
--- a/server/nodes/email/_himalaya.py
+++ b/server/nodes/email/_himalaya.py
@@ -14,24 +14,20 @@ from pathlib import Path
from typing import Any, Dict, List, Optional
from core.logging import get_logger
+from services.plugin.singleton import ServiceSingleton
logger = get_logger(__name__)
-class HimalayaService:
- """Manages Himalaya CLI configuration and execution."""
+class HimalayaService(ServiceSingleton):
+ """Manages Himalaya CLI configuration and execution.
- _instance: Optional["HimalayaService"] = None
+ Inherits ``instance`` / ``reset_instance`` from
+ :class:`ServiceSingleton`."""
def __init__(self):
self._binary_path: Optional[str] = None
- @classmethod
- def get_instance(cls) -> "HimalayaService":
- if cls._instance is None:
- cls._instance = cls()
- return cls._instance
-
async def ensure_binary(self) -> str:
"""Detect himalaya binary in PATH. Returns path or raises."""
if self._binary_path:
@@ -265,4 +261,4 @@ class HimalayaService:
def get_himalaya_service() -> HimalayaService:
"""Get singleton instance."""
- return HimalayaService.get_instance()
+ return HimalayaService.instance()
diff --git a/server/nodes/email/_service.py b/server/nodes/email/_service.py
index 3d271589..c63a1a0b 100644
--- a/server/nodes/email/_service.py
+++ b/server/nodes/email/_service.py
@@ -8,6 +8,7 @@ from pathlib import Path
from typing import Any, Dict, Optional, Set
from core.logging import get_logger
+from services.plugin.singleton import ServiceSingleton
logger = get_logger(__name__)
@@ -23,14 +24,9 @@ def _load_config() -> Dict:
return _CONFIG
-class EmailService:
- _instance: Optional["EmailService"] = None
-
- @classmethod
- def get_instance(cls) -> "EmailService":
- if cls._instance is None:
- cls._instance = cls()
- return cls._instance
+class EmailService(ServiceSingleton):
+ """Plugin-owned email orchestrator. Inherits ``instance`` /
+ ``reset_instance`` from :class:`ServiceSingleton`."""
@property
def config(self) -> Dict:
@@ -184,4 +180,4 @@ class EmailService:
def get_email_service() -> EmailService:
- return EmailService.get_instance()
+ return EmailService.instance()
diff --git a/server/nodes/telegram/_service.py b/server/nodes/telegram/_service.py
index 4176b7cd..6c0c2120 100644
--- a/server/nodes/telegram/_service.py
+++ b/server/nodes/telegram/_service.py
@@ -49,6 +49,8 @@ from telegram.error import BadRequest, NetworkError
from telegram.ext import Application, ContextTypes, MessageHandler, filters
from telegram.helpers import escape_markdown
+from services.plugin.singleton import ServiceSingleton
+
from ._credentials import TelegramCredential
logger = logging.getLogger(__name__)
@@ -99,10 +101,14 @@ def _split_text(text: str, limit: int) -> list[str]:
return chunks
-class TelegramService:
- """Singleton service for Telegram bot operations."""
+class TelegramService(ServiceSingleton):
+ """Singleton service for Telegram bot operations.
+
+ Inherits :meth:`ServiceSingleton.instance` for the lazy accessor.
+ Overrides :meth:`reset_instance` because telegram has a side effect
+ on reset — it must drain the bot's polling task before clearing.
+ """
- _instance: Optional["TelegramService"] = None
_lock = asyncio.Lock()
def __init__(self):
@@ -115,15 +121,10 @@ class TelegramService:
self._owner_chat_id: Optional[int] = None
@classmethod
- def get_instance(cls) -> "TelegramService":
- if cls._instance is None:
- cls._instance = cls()
- return cls._instance
-
- @classmethod
- async def reset_instance(cls):
- if cls._instance:
- await cls._instance.disconnect()
+ async def reset_instance(cls): # type: ignore[override]
+ existing = cls.__dict__.get("_instance")
+ if existing is not None:
+ await existing.disconnect()
cls._instance = None
@property
@@ -727,4 +728,4 @@ class TelegramService:
def get_telegram_service() -> TelegramService:
"""Get TelegramService singleton instance."""
- return TelegramService.get_instance()
+ return TelegramService.instance()
diff --git a/server/services/event_waiter.py b/server/services/event_waiter.py
index 58c846ce..11c140b8 100644
--- a/server/services/event_waiter.py
+++ b/server/services/event_waiter.py
@@ -825,43 +825,83 @@ def _cleanup_waiter(waiter_id: str) -> None:
# EVENT DISPATCH
# =============================================================================
-async def dispatch_async(event_type: str, data: Dict) -> int:
+def _unpack_event(
+ event: "Any",
+ data: Optional[Dict] = None,
+) -> tuple[str, Dict]:
+ """Normalise either ``(WorkflowEvent,)`` or ``(event_type, data)`` to
+ the underlying ``(event_type, data)`` pair the dispatcher uses.
+
+ Wave 11.I, milestone Q: ``dispatch`` and ``dispatch_async`` accept a
+ ``WorkflowEvent`` directly so the ``WorkflowEvent(**event)`` rewrap
+ in ``events/triggers.py`` becomes a no-op. The legacy
+ ``(event_type, data)`` shape stays supported via
+ :meth:`WorkflowEvent.from_legacy` upstream of the dispatcher (the
+ public API just forwards either form).
+ """
+ # Lazy import: services.events imports event_waiter for trigger
+ # adaptation, so a top-level import would be circular.
+ from services.events.envelope import WorkflowEvent
+
+ if isinstance(event, WorkflowEvent):
+ return event.type, event.data if isinstance(event.data, dict) else {"data": event.data}
+ if isinstance(event, str):
+ return event, data or {}
+ raise TypeError(
+ f"dispatch expects a WorkflowEvent or (event_type: str, data: Dict); "
+ f"got {type(event).__name__}"
+ )
+
+
+async def dispatch_async(
+ event: "Any",
+ data: Optional[Dict] = None,
+) -> int:
"""Dispatch event asynchronously (for Redis mode).
Args:
- event_type: Type of event (e.g., 'whatsapp_message_received')
- data: Event data
+ event: Either a :class:`WorkflowEvent` (preferred, Wave 11.I) or
+ an event-type string. The legacy ``(event_type, data)`` form
+ stays supported.
+ data: Event payload (when ``event`` is a string).
Returns:
1 if event was added to stream, 0 otherwise
"""
+ event_type, payload = _unpack_event(event, data)
logger.debug(f"[EventWaiter] dispatch_async: event_type='{event_type}'")
if is_redis_mode():
cache = get_cache_service()
stream_name = _get_stream_name(event_type)
- msg_id = await cache.stream_add(stream_name, data)
+ msg_id = await cache.stream_add(stream_name, payload)
if msg_id:
logger.debug(f"[EventWaiter] Added event to stream {stream_name}: {msg_id}")
return 1
return 0
else:
# Fall back to sync dispatch for memory mode
- return dispatch(event_type, data)
+ return dispatch(event_type, payload)
-def dispatch(event_type: str, data: Dict) -> int:
+def dispatch(
+ event: "Any",
+ data: Optional[Dict] = None,
+) -> int:
"""Dispatch event to matching waiters (synchronous, memory mode).
Thread-safe: Can be called from APScheduler threads or async context.
Args:
- event_type: Type of event (e.g., 'whatsapp_message_received')
- data: Event data
+ event: Either a :class:`WorkflowEvent` (preferred, Wave 11.I) or
+ an event-type string. The legacy ``(event_type, data)`` form
+ stays supported.
+ data: Event payload (when ``event`` is a string).
Returns:
Number of waiters resolved
"""
+ event_type, data = _unpack_event(event, data)
if is_redis_mode():
# In Redis mode, use async dispatch
# Handle both async context and thread context (e.g., APScheduler callbacks)
diff --git a/server/services/events/envelope.py b/server/services/events/envelope.py
index e4a42b56..d6a298e4 100644
--- a/server/services/events/envelope.py
+++ b/server/services/events/envelope.py
@@ -9,7 +9,7 @@ ride as CloudEvents extension attributes — fully compliant with the spec.
from __future__ import annotations
from datetime import datetime, timezone
-from typing import Any, Optional
+from typing import Any, Literal, Mapping, Optional
from uuid import uuid4
from pydantic import BaseModel, ConfigDict, Field
@@ -48,6 +48,156 @@ class WorkflowEvent(BaseModel):
data=payload,
)
+ # ---- Typed factory classmethods (Wave 11.I, milestone Q) -----------
+ #
+ # Mirrors the official `cloudevents` Python SDK's `from_http` /
+ # `to_http` convenience pattern. Each factory enforces the same
+ # source/type/subject conventions across the codebase so callers
+ # don't hand-construct envelopes with drifting URI shapes.
+
+ @classmethod
+ def credential(
+ cls,
+ provider: str,
+ action: Literal[
+ "api_key.saved",
+ "api_key.deleted",
+ "api_key.validated",
+ "oauth.connected",
+ "oauth.disconnected",
+ "oauth.validated",
+ ],
+ **extra: Any,
+ ) -> "WorkflowEvent":
+ """Credential mutation event (matches the existing
+ ``broadcast_credential_event`` contract locked by
+ ``test_credential_broadcasts.py``)."""
+ return cls(
+ source="machinaos://services/credentials",
+ type=f"credential.{action}",
+ subject=provider,
+ data={"provider": provider, **extra} if extra else {"provider": provider},
+ )
+
+ @classmethod
+ def connection_status(
+ cls,
+ plugin: str,
+ *,
+ connected: bool,
+ subject: Optional[str] = None,
+ data: Optional[Mapping[str, Any]] = None,
+ ) -> "WorkflowEvent":
+ """Plugin connection-state event (whatsapp / telegram / android-relay
+ / twitter / google connect-disconnect)."""
+ return cls(
+ source=f"machinaos://nodes/{plugin}",
+ type=f"{plugin}.connection.{'opened' if connected else 'closed'}",
+ subject=subject,
+ data=dict(data) if data else {},
+ )
+
+ @classmethod
+ def oauth_completed(
+ cls,
+ provider: str,
+ *,
+ identifier: str,
+ data: Optional[Mapping[str, Any]] = None,
+ ) -> "WorkflowEvent":
+ """OAuth callback completion. ``identifier`` is the user-facing
+ handle (email / username) used as ``subject``."""
+ return cls(
+ source=f"machinaos://nodes/{provider}",
+ type=f"{provider}.oauth.completed",
+ subject=identifier,
+ data=dict(data) if data else {"identifier": identifier},
+ )
+
+ @classmethod
+ def message(
+ cls,
+ plugin: str,
+ direction: Literal["sent", "received"],
+ data: Mapping[str, Any],
+ ) -> "WorkflowEvent":
+ """Plugin-emitted message event (whatsapp / telegram / email
+ send + receive). ``subject`` defaults to the chat / sender id
+ in the payload (cast to str — Telegram uses numeric chat ids),
+ falling back to None."""
+ payload = dict(data)
+ raw_subject = (
+ payload.get("chat_id") or payload.get("from_id") or payload.get("sender")
+ )
+ return cls(
+ source=f"machinaos://nodes/{plugin}",
+ type=f"{plugin}.message.{direction}",
+ subject=str(raw_subject) if raw_subject is not None else None,
+ data=payload,
+ )
+
+ @classmethod
+ def team_event(
+ cls,
+ team_id: str,
+ kind: str,
+ data: Mapping[str, Any],
+ ) -> "WorkflowEvent":
+ """Agent-team lifecycle / task event (created / dissolved /
+ task.added / task.claimed / task.completed / task.failed /
+ message.sent)."""
+ return cls(
+ source="machinaos://services/agent_team",
+ type=f"team.{kind}",
+ subject=team_id,
+ data=dict(data),
+ )
+
+ @classmethod
+ def workflow_lifecycle(
+ cls,
+ stage: Literal[
+ "deployment.started",
+ "deployment.stopped",
+ "lock.acquired",
+ "lock.released",
+ "execution.started",
+ "execution.stopped",
+ ],
+ *,
+ workflow_id: str,
+ data: Optional[Mapping[str, Any]] = None,
+ ) -> "WorkflowEvent":
+ """Workflow lifecycle event. Carries ``workflow_id`` both as
+ ``subject`` (CloudEvents convention) and as the
+ ``workflow_id`` extension attribute (existing reader
+ contract)."""
+ return cls(
+ source="machinaos://services/workflow",
+ type=f"workflow.{stage}",
+ subject=workflow_id,
+ workflow_id=workflow_id,
+ data=dict(data) if data else {},
+ )
+
+ @classmethod
+ def task_completed(
+ cls,
+ task_id: str,
+ *,
+ status: Literal["completed", "error"],
+ agent: str,
+ data: Optional[Mapping[str, Any]] = None,
+ ) -> "WorkflowEvent":
+ """Delegated child-agent completion. Type discriminates on
+ succeeded vs failed; ``taskTrigger`` filters by both."""
+ return cls(
+ source="machinaos://services/agent",
+ type=f"agent.task.{'succeeded' if status == 'completed' else 'failed'}",
+ subject=task_id,
+ data=dict(data) if data else {"task_id": task_id, "agent": agent, "status": status},
+ )
+
def matches_type(self, pattern: str) -> bool:
"""Glob-style match on event type. ``"all"``/empty matches any.
diff --git a/server/services/plugin/singleton.py b/server/services/plugin/singleton.py
new file mode 100644
index 00000000..04f5280c
--- /dev/null
+++ b/server/services/plugin/singleton.py
@@ -0,0 +1,65 @@
+"""Service-singleton mixin for plugin-owned long-lived services.
+
+Replaces the per-plugin ``_instance`` + ``get_instance()`` boilerplate
+that each ``nodes/<plugin>/_service.py`` currently re-implements.
+Pre-T inventory (Wave 11.I plan):
+
+- ``nodes/telegram/_service.py:TelegramService`` -- ``_instance`` + sync
+ ``get_instance`` + async ``reset_instance`` (custom — disconnects).
+- ``nodes/email/_service.py:EmailService`` -- ``_instance`` + sync
+ ``get_instance``, no reset.
+- ``nodes/browser/_service.py`` -- module-level ``_instance`` global,
+ no class-level state (different shape, kept bespoke).
+- ``nodes/whatsapp/_service.py`` -- supervisor-aware singleton via
+ ``BaseProcessSupervisor``, kept bespoke (different lifecycle).
+
+Subclasses get :meth:`instance` for free. They override
+:meth:`reset_instance` only if there's a side effect on reset
+(Telegram disconnects the bot poll loop; that stays per-plugin).
+"""
+
+from __future__ import annotations
+
+from typing import ClassVar, Optional, TypeVar
+
+T = TypeVar("T", bound="ServiceSingleton")
+
+
+class ServiceSingleton:
+ """Mixin: per-class lazy singleton.
+
+ Each subclass that opts in gets its own ``_instance`` slot lazily
+ populated on first :meth:`instance` call. The Python attribute
+ rules guarantee per-class isolation (read climbs MRO, write goes
+ to the immediate class), so ``A.instance()`` and ``B.instance()``
+ return distinct singletons even though both inherit the same
+ declaration here.
+
+ Usage::
+
+ class TelegramService(ServiceSingleton):
+ ...
+
+ # module-level helper consumed by handler files:
+ def get_telegram_service() -> TelegramService:
+ return TelegramService.instance()
+
+ Subclasses may also override :meth:`reset_instance` to add side
+ effects (e.g. tear down a bot polling loop) before clearing.
+ """
+
+ _instance: ClassVar[Optional["ServiceSingleton"]] = None
+
+ @classmethod
+ def instance(cls: type[T]) -> T:
+ """Return the per-class singleton, constructing it on first call."""
+ if cls.__dict__.get("_instance") is None:
+ cls._instance = cls()
+ return cls._instance # type: ignore[return-value]
+
+ @classmethod
+ def reset_instance(cls) -> None:
+ """Drop the cached singleton. Override for async / cleanup
+ flows; the default is a sync no-side-effect clear."""
+ if cls.__dict__.get("_instance") is not None:
+ cls._instance = None
diff --git a/server/services/status_broadcaster.py b/server/services/status_broadcaster.py
index b8704c2e..7db5ceed 100644
--- a/server/services/status_broadcaster.py
+++ b/server/services/status_broadcaster.py
@@ -96,15 +96,22 @@ class StatusBroadcaster:
async def connect(self, websocket: WebSocket):
"""Accept a new WebSocket connection.
- Sends cached status immediately so the client is unblocked,
- then refreshes service statuses in a background task.
+ Sends the cached status snapshot immediately. Status changes
+ flow in via the originating code path (WhatsApp Go-service
+ events, Telegram bot connect/disconnect, OAuth callbacks,
+ Android relay events) -- the cache is kept fresh by those
+ event-driven broadcasts, so the connecting client doesn't need
+ a per-connect refresh-all storm.
+
+ Initial cache population (and load-bearing auto-reconnects for
+ Telegram + Android relay) happens in a one-time lifespan-startup
+ invocation of :meth:`_refresh_all_services` from ``main.py``.
"""
await websocket.accept()
async with self._lock:
self._connections.add(websocket)
logger.info(f"[StatusBroadcaster] Client connected. Total: {len(self._connections)}")
- # Send cached status immediately -- don't block on service refreshes
try:
await websocket.send_json({
"type": "initial_status",
@@ -113,9 +120,6 @@ class StatusBroadcaster:
except Exception as e:
logger.error(f"[StatusBroadcaster] Failed to send initial status: {e}")
- # Refresh service statuses in background -- updates broadcast when ready
- asyncio.create_task(self._refresh_all_services())
-
async def disconnect(self, websocket: WebSocket):
"""Remove a WebSocket connection."""
async with self._lock: