Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor(plugin-extraction): L -- PollingTriggerNode template-method base
trohitg312b319a139f
diff --git a/server/nodes/email/email_receive.py b/server/nodes/email/email_receive.pyindex 28be37fb..4236f5d7 100644--- a/server/nodes/email/email_receive.py+++ b/server/nodes/email/email_receive.py@@ -6,11 +6,13 @@ IMAP polling for new mail via Himalaya CLI. Thin delegation tofrom __future__ import annotations-from typing import Any, Dict, Literal, Optional+from typing import Any, Dict, Literal, Optional, Setfrom pydantic import BaseModel, ConfigDict, Field-from services.plugin import NodeContext, Operation, TaskQueue, TriggerNode+from services.plugin import (+ NodeContext, Operation, PollingTriggerNode, TaskQueue,+)class EmailReceiveParams(BaseModel):@@ -35,7 +37,7 @@ class EmailReceiveOutput(BaseModel):model_config = ConfigDict(extra="allow")-class EmailReceiveNode(TriggerNode):+class EmailReceiveNode(PollingTriggerNode):type = "emailReceive"display_name = "Email Receive"subtitle = "IMAP Polling"@@ -51,11 +53,54 @@ class EmailReceiveNode(TriggerNode):"label": "Output", "role": "main"},)task_queue = TaskQueue.TRIGGERS_POLL- mode = "polling"+ # Email keeps its 30s lower bound (legacy floor in+ # config/email_providers.json). Gmail uses the default (10, 3600).+ poll_interval_clamp = (30, 3600)Params = EmailReceiveParamsOutput = EmailReceiveOutput+ # ---- PollingTriggerNode hooks (deployment-mode loop) -------------+ #+ # The Run-button path lives in ``execute()`` below and stays+ # bespoke: it broadcasts ``waiting`` status, dispatches via+ # event_waiter, and returns after the first new email. The+ # deployment loop owned by ``PollingTriggerNode`` drains+ # continuously via the deployment manager's queue and uses the+ # four hooks below.++ async def setup_service(self, params: Dict[str, Any]) -> Any:+ from ._service import get_email_service++ svc = get_email_service()+ creds = await svc.resolve_credentials(params)+ cfg = svc.resolve_poll_params(params)+ return svc, creds, cfg["folder"], cfg.get("mark_as_read", False)++ async def fetch_ids(self, service: Any, params: Dict[str, Any]) -> Set[str]:+ svc, creds, folder, _mark = service+ return await svc.poll_ids(creds, folder)++ async def fetch_detail(+ self, service: Any, msg_id: str, params: Dict[str, Any]+ ) -> Dict[str, Any]:+ svc, creds, folder, _mark = service+ return await svc.fetch_detail(creds, msg_id, folder)++ async def post_emit(+ self, service: Any, msg_id: str, params: Dict[str, Any]+ ) -> None:+ svc, creds, folder, mark = service+ if not mark:+ return+ try:+ d = svc.defaults+ await svc.himalaya.flag_message(+ creds, msg_id, d.get("flag"), d.get("flag_action"), folder,+ )+ except Exception:+ pass+async def execute(self,node_id: str,diff --git a/server/nodes/google/gmail_receive.py b/server/nodes/google/gmail_receive.pyindex 73518a25..319fff5b 100644--- a/server/nodes/google/gmail_receive.py+++ b/server/nodes/google/gmail_receive.py@@ -10,7 +10,9 @@ from typing import Any, Dict, Literal, Optional, Setfrom pydantic import BaseModel, ConfigDict, Fieldfrom core.logging import get_logger-from services.plugin import NodeContext, Operation, TaskQueue, TriggerNode+from services.plugin import (+ NodeContext, Operation, PollingTriggerNode, TaskQueue,+)from ._credentials import GoogleCredential@@ -52,8 +54,12 @@ class GmailReceiveOutput(BaseModel):model_config = ConfigDict(extra="allow")-class GmailReceiveNode(TriggerNode):+class GmailReceiveNode(PollingTriggerNode):type = "googleGmailReceive"+ # Pre-existing alias used by deployment manager + POLLING_TRIGGER_TYPES;+ # registers the deployment-mode poll factory under both names so the+ # mismatch can be retired in a separate rename commit.+ type_alias = "gmailReceive"display_name = "Gmail Receive"subtitle = "Inbound Email"group = ("google", "trigger")@@ -65,12 +71,39 @@ class GmailReceiveNode(TriggerNode):)credentials = (GoogleCredential,)task_queue = TaskQueue.TRIGGERS_POLL- mode = "polling"default_poll_interval = 60Params = GmailReceiveParamsOutput = GmailReceiveOutput+ # ---- PollingTriggerNode hooks (deployment-mode loop) -------------++ @staticmethod+ def _build_query(parameters: Dict[str, Any]) -> str:+ query = parameters.get("filter_query", "is:unread")+ label = parameters.get("label_filter", "INBOX")+ return f"label:{label} {query}" if label and label != "all" else query++ async def setup_service(self, params: Dict[str, Any]) -> Any:+ return await build_google_service("gmail", "v1", params, {})++ async def fetch_ids(self, service: Any, params: Dict[str, Any]) -> Set[str]:+ return await poll_gmail_ids(service, self._build_query(params))++ async def fetch_detail(+ self, service: Any, msg_id: str, params: Dict[str, Any]+ ) -> Dict[str, Any]:+ return await fetch_email_details(service, msg_id)++ async def post_emit(+ self, service: Any, msg_id: str, params: Dict[str, Any]+ ) -> None:+ if params.get("mark_as_read"):+ try:+ await mark_email_as_read(service, msg_id)+ except Exception as exc: # noqa: BLE001+ logger.warning(f"[GmailReceive] Failed to mark as read: {exc}")+async def execute(self,node_id: str,diff --git a/server/services/deployment/manager.py b/server/services/deployment/manager.pyindex fc28f795..5f1a8e50 100644--- a/server/services/deployment/manager.py+++ b/server/services/deployment/manager.py@@ -418,17 +418,25 @@ class DeploymentManager:if not trigger_manager:raise RuntimeError(f"No trigger manager for workflow {workflow_id}")- # Polling triggers need active API polling instead of event_waiter+ # Polling triggers need active API polling instead of event_waiter.+ # Plugins register a factory via+ # ``services.plugin.PollingTriggerNode.__init_subclass__`` →+ # ``services.deployment.poll_registry.register_poll_coroutine_factory``.if node_type in POLLING_TRIGGER_TYPES:- poll_coroutine = self._create_poll_coroutine(node_type, node_id, params)- if poll_coroutine:+ from services.deployment.poll_registry import (+ get_poll_coroutine_factory,+ )++ factory = get_poll_coroutine_factory(node_type)+ if factory is not None:+ poll_coroutine = factory(node_id, params)await trigger_manager.setup_polling_trigger(node_id, node_type, params, poll_coroutine, on_event,self._broadcaster, workflow_id=workflow_id)return TriggerInfo(node_id, node_type)- # Fall through to event_waiter if no polling implementation available- logger.warning("No polling implementation for trigger", node_type=node_type)+ # Fall through to event_waiter if no polling factory registered+ logger.warning("No polling factory registered for trigger", node_type=node_type)await trigger_manager.setup_event_trigger(node_id, node_type, params, on_event, self._broadcaster,@@ -677,141 +685,12 @@ class DeploymentManager:# POLLING TRIGGER FACTORIES# =========================================================================- def _create_poll_coroutine(self, node_type: str, node_id: str,- params: Dict[str, Any]) -> Optional[Callable]:- """Create a polling coroutine for polling-based triggers.-- Returns an async function(queue, is_running_fn) or None if not supported.- """- if node_type == 'gmailReceive':- return self._create_gmail_poll_coroutine(node_id, params)- elif node_type == 'emailReceive':- return self._create_email_poll_coroutine(node_id, params)- elif node_type == 'twitterReceive':- logger.warning("Twitter polling trigger not yet implemented for deployment")- return None- return None-- def _create_gmail_poll_coroutine(self, node_id: str,- params: Dict[str, Any]) -> Callable:- """Create Gmail API polling coroutine for deployment mode.-- Polls Gmail API at configured intervals for new emails matching the filter.- Establishes a baseline of existing emails to avoid triggering on old messages.- """- async def poll(queue: asyncio.Queue, is_running_fn: Callable):- from nodes.google._base import build_google_service- from nodes.google._gmail import (- poll_gmail_ids as _poll_gmail_ids,- fetch_email_details as _fetch_email_details,- mark_email_as_read as _mark_email_as_read,- )-- # Authenticate with Gmail API- service = await build_google_service("gmail", "v1", params, {})-- poll_interval = max(10, min(3600, params.get('poll_interval', 60)))- filter_query = params.get('filter_query', 'is:unread')- label_filter = params.get('label_filter', 'INBOX')- mark_as_read = params.get('mark_as_read', False)-- # Build Gmail query- query = filter_query- if label_filter and label_filter != 'all':- query = f"label:{label_filter} {query}"-- logger.info("Gmail poller starting",- node_id=node_id, query=query,- poll_interval=poll_interval)-- # Establish baseline (avoid triggering on existing emails)- seen_ids: set = set()- try:- baseline = await _poll_gmail_ids(service, query)- seen_ids.update(baseline)- logger.info("Gmail poller baseline established",- node_id=node_id, count=len(seen_ids))- except Exception as e:- logger.warning("Gmail poller baseline failed",- node_id=node_id, error=str(e))-- # Poll loop- poll_count = 0- while is_running_fn():- await asyncio.sleep(poll_interval)- if not is_running_fn():- break-- poll_count += 1- try:- current_ids = await _poll_gmail_ids(service, query)- new_ids = current_ids - seen_ids- logger.debug("Gmail poll cycle",- node_id=node_id, cycle=poll_count,- current=len(current_ids),- seen=len(seen_ids),- new=len(new_ids))-- for msg_id in new_ids:- seen_ids.add(msg_id)- email_data = await _fetch_email_details(service, msg_id)-- if mark_as_read:- try:- await _mark_email_as_read(service, msg_id)- except Exception:- pass-- await queue.put(email_data)- logger.info("Gmail poller: new email queued",- node_id=node_id,- subject=email_data.get('subject', ''))-- except asyncio.CancelledError:- break- except Exception as e:- logger.error("Gmail poll error",- node_id=node_id, error=str(e))-- return poll-- def _create_email_poll_coroutine(self, node_id: str,- params: Dict[str, Any]) -> Callable:- """Create Himalaya email polling coroutine for deployment mode."""- async def poll(queue: asyncio.Queue, is_running_fn: Callable):- from nodes.email._service import get_email_service-- svc = get_email_service()- creds = await svc.resolve_credentials(params)- cfg = svc.resolve_poll_params(params)-- seen = await svc.poll_ids(creds, cfg["folder"])- logger.info("Email poller starting",- node_id=node_id, folder=cfg["folder"], seen=len(seen))-- while is_running_fn():- await asyncio.sleep(cfg["interval"])- if not is_running_fn():- break- try:- for msg_id in await svc.poll_ids(creds, cfg["folder"]) - seen:- seen.add(msg_id)- email_data = await svc.fetch_detail(creds, msg_id, cfg["folder"])- if cfg["mark_as_read"]:- try:- d = svc.defaults- await svc.himalaya.flag_message(- creds, msg_id, d.get("flag"), d.get("flag_action"), cfg["folder"])- except Exception:- pass- await queue.put(email_data)- except asyncio.CancelledError:- break- except Exception as e:- logger.error("Email poll error",- node_id=node_id, error=str(e))-- return poll+ # _create_poll_coroutine + _create_gmail_poll_coroutine ++ # _create_email_poll_coroutine REMOVED in Wave 11.I, milestone L.+ # Polling-coroutine factories now self-register from each plugin's+ # PollingTriggerNode subclass (services.plugin.PollingTriggerNode)+ # via services.deployment.poll_registry.register_poll_coroutine_factory.+ # The dispatch path lives ~140 lines up in _setup_event_trigger.async def _load_settings(self):"""Load deployment settings from database."""diff --git a/server/services/deployment/poll_registry.py b/server/services/deployment/poll_registry.pynew file mode 100644index 00000000..c80661eb--- /dev/null+++ b/server/services/deployment/poll_registry.py@@ -0,0 +1,59 @@+"""Polling-coroutine factory registry (Wave 11.I, milestone L).++Plugin packages register a factory that produces an async polling+coroutine for a given trigger node type. ``DeploymentManager`` looks+up the factory at deploy time and hands the produced coroutine to+``TriggerManager.setup_polling_trigger`` -- the deployment manager no+longer hardcodes per-plugin polling switches.++Mirror of :func:`services.event_waiter.register_filter_builder`:+same idempotency contract, same audience (plugin ``__init__.py``+modules), built on the shared :class:`IdempotentRegistry`.++Factory signature+-----------------++ factory(node_id: str, params: Dict[str, Any]) -> async (+ queue: asyncio.Queue, is_running_fn: Callable[[], bool]+ ) -> None++The factory closes over node-specific config (auth, query, poll+interval); the returned coroutine drains until ``is_running_fn()``+returns False or the task is cancelled. New events go on ``queue``.+"""++from __future__ import annotations++import asyncio+from typing import Any, Awaitable, Callable, Dict, Optional++from services.plugin.registry import IdempotentRegistry+++# (queue, is_running) -> awaitable. The poll coroutine itself.+PollCoroutine = Callable[[asyncio.Queue, Callable[[], bool]], Awaitable[None]]++# (node_id, params) -> the bound poll coroutine.+PollCoroutineFactory = Callable[[str, Dict[str, Any]], PollCoroutine]+++_REGISTRY: IdempotentRegistry[str, PollCoroutineFactory] = IdempotentRegistry(+ "poll_coroutine_factory"+)+++def register_poll_coroutine_factory(+ node_type: str, factory: PollCoroutineFactory+) -> None:+ """Publish a polling-coroutine factory for a trigger node type.++ Idempotent on re-import (same callable for the same key is a+ no-op). A different callable for an existing key raises+ ``ValueError`` to surface plugin namespace collisions early.+ """+ _REGISTRY.register(node_type, factory)+++def get_poll_coroutine_factory(node_type: str) -> Optional[PollCoroutineFactory]:+ """Return the factory for ``node_type``, or ``None`` if unregistered."""+ return _REGISTRY.get(node_type)diff --git a/server/services/plugin/__init__.py b/server/services/plugin/__init__.pyindex acf48e36..6fa0d640 100644--- a/server/services/plugin/__init__.py+++ b/server/services/plugin/__init__.py@@ -28,6 +28,7 @@ from __future__ import annotationsfrom services.plugin.base import BaseNode, NodeUserErrorfrom services.plugin.action import ActionNodefrom services.plugin.trigger import TriggerNode+from services.plugin.polling import PollingTriggerNodefrom services.plugin.tool import ToolNodefrom services.plugin.operation import Operation, OperationSpecfrom services.plugin.routing import Routing, RoutingRequest, RoutingOutput, execute_routing@@ -52,6 +53,7 @@ __all__ = ["NodeUserError","ActionNode","TriggerNode",+ "PollingTriggerNode","ToolNode","Operation","OperationSpec",diff --git a/server/services/plugin/polling.py b/server/services/plugin/polling.pynew file mode 100644index 00000000..327f704f--- /dev/null+++ b/server/services/plugin/polling.py@@ -0,0 +1,247 @@+"""PollingTriggerNode -- template-method polling-trigger base class.++Wave 11.I, milestone L. Subclass owns the four divergence points+(``setup_service``, ``fetch_ids``, ``fetch_detail``, optional+``post_emit``); the base owns the loop body, the seen-id baseline,+the cancellation surface, and per-cycle error isolation.++Auto-registers a poll-coroutine factory in+:mod:`services.deployment.poll_registry` so+``DeploymentManager._setup_event_trigger`` looks the plugin up by+node type instead of branching on a hardcoded list.++Design choice (over lift-and-shift): the gmail and email pollers in+``services/deployment/manager.py`` had identical structure -- 80 LOC+vs 37 LOC, only the four seams differed. Pulling the loop into a+mixin collapses ~120 LOC of duplicated polling control flow into one+~40 LOC body, plus ~15 LOC per concrete poller.++Cancellation contract+---------------------+Mirrors the existing ``setup_polling_trigger`` consumer in+``services/deployment/triggers.py``:++- The deployment manager passes ``is_running_fn``; the loop checks+ it before every sleep and after wake.+- ``asyncio.CancelledError`` is re-raised, never swallowed (per+ https://docs.python.org/3/library/asyncio-task.html#task-cancellation).++Per-cycle error isolation: a transient ``Exception`` from+``fetch_ids`` or ``fetch_detail`` logs at ERROR and the loop sleeps+to the next interval. Permanent errors (auth revoked, account+deleted) currently keep retrying indefinitely with the same log+line; ``tenacity``-backed classification is a follow-up extension+point documented inline.++Out of scope (commit-stage)+---------------------------+- ``WorkflowEvent.message(...)`` envelope wrapping: ``setup_polling_trigger``+ consumes raw dicts today; envelope adoption is the U milestone test pass.+- Persistent watermark cursor: ``seen_ids`` is in-memory and resets+ on restart. Backlog dropped on restart -- existing behaviour.+- Twitter polling: ``twitterReceive`` declares ``mode="polling"`` but+ has no concrete subclass. Subclassing this base is the conversion path.+"""++from __future__ import annotations++import asyncio+from typing import Any, Callable, ClassVar, Dict, Optional, Set, Tuple++from core.logging import get_logger+from services.plugin.trigger import TriggerNode++logger = get_logger(__name__)+++class PollingTriggerNode(TriggerNode, abstract=True):+ """Polling trigger with a unified loop body.++ Subclass MUST override:++ - :meth:`setup_service` -- build the auth client / SDK handle.+ - :meth:`fetch_ids` -- return the current visible IDs (set[str]).+ - :meth:`fetch_detail` -- return the event payload for one ID.++ Subclass MAY override:++ - :meth:`post_emit` -- side effect after enqueue (e.g. mark-as-read).+ - :attr:`poll_interval_clamp` -- (min, max) seconds for the+ ``poll_interval`` param. Default (10, 3600).+ - :attr:`type_alias` -- a second registration key for plugins+ that want to be reachable by a legacy type name without+ changing the plugin's primary ``type``. Today's only use case+ is gmail (``type = "googleGmailReceive"`` but downstream+ callers key by ``"gmailReceive"``).+ """++ mode: ClassVar[str] = "polling"++ # (min_seconds, max_seconds) for the user-supplied poll_interval.+ poll_interval_clamp: ClassVar[Tuple[int, int]] = (10, 3600)++ # Optional secondary registration key. Registers under both+ # ``cls.type`` and ``cls.type_alias`` for plugins with a legacy+ # alias.+ type_alias: ClassVar[str] = ""++ # ---- subclass hooks ------------------------------------------------++ async def setup_service(self, params: Dict[str, Any]) -> Any:+ """Build the auth client / service handle that ``fetch_ids`` and+ ``fetch_detail`` will close over.++ Plugins that don't need a long-lived handle can return any+ opaque value (or the ``params`` dict itself). The returned+ value is passed unchanged to the other hooks.+ """+ raise NotImplementedError++ async def fetch_ids(+ self, service: Any, params: Dict[str, Any]+ ) -> Set[str]:+ """Return the current set of visible IDs for one poll cycle.++ Called once for the baseline pass at loop start, then once per+ ``poll_interval`` thereafter. The diff against the previous+ ``seen`` set is the source of truth for "what's new".+ """+ raise NotImplementedError++ async def fetch_detail(+ self, service: Any, msg_id: str, params: Dict[str, Any]+ ) -> Dict[str, Any]:+ """Fetch the full event payload for one ID.++ Called once per new ID per cycle. The returned dict goes+ directly onto the deployment manager's queue (no envelope+ wrapping in this commit -- see milestone U / module docstring).+ """+ raise NotImplementedError++ async def post_emit(+ self, service: Any, msg_id: str, params: Dict[str, Any]+ ) -> None:+ """Optional side effect AFTER the payload was enqueued.++ Default no-op. Override for "mark-as-read" or similar+ post-processing that should not block the emit and whose+ failure shouldn't kill the loop.+ """+ return None++ # ---- registration --------------------------------------------------++ def __init_subclass__(cls, abstract: bool = False, **kwargs):+ super().__init_subclass__(abstract=abstract, **kwargs)+ if abstract or not cls.type:+ return++ # Auto-register a poll-coroutine factory for the deployment+ # manager (the in-process Run-button path uses :meth:`execute`+ # which we override below). Idempotent on re-import via+ # IdempotentRegistry.+ from services.deployment.poll_registry import (+ register_poll_coroutine_factory,+ )++ def factory(node_id: str, params: Dict[str, Any]) -> Callable:+ instance = cls()+ return instance._build_poll_coroutine(node_id, params)++ register_poll_coroutine_factory(cls.type, factory)+ if cls.type_alias:+ # Same factory under the legacy alias so consumers that+ # key by the alias (manager.py POLLING_TRIGGER_TYPES) still+ # find the factory until the rename lands.+ register_poll_coroutine_factory(cls.type_alias, factory)++ # ---- shared loop ---------------------------------------------------++ def _clamp_interval(self, raw: Any) -> int:+ lo, hi = self.poll_interval_clamp+ try:+ value = int(raw)+ except (TypeError, ValueError):+ value = self.default_poll_interval+ return max(lo, min(hi, value))++ def _build_poll_coroutine(+ self, node_id: str, params: Dict[str, Any]+ ) -> Callable[[asyncio.Queue, Callable[[], bool]], Any]:+ """Return the bound poll coroutine the deployment manager+ consumes. Closes over ``self``, ``node_id``, and ``params``.+ """++ async def poll(+ queue: asyncio.Queue, is_running_fn: Callable[[], bool]+ ) -> None:+ try:+ service = await self.setup_service(params)+ except Exception as exc: # noqa: BLE001 -- single setup failure+ logger.error(+ "Polling trigger setup failed",+ node_id=node_id, node_type=self.type, error=str(exc),+ )+ return++ interval = self._clamp_interval(params.get("poll_interval"))++ # Baseline -- avoid re-emitting items the user has had since+ # before the deployment was live. On baseline failure, fall+ # through with an empty set: the next cycle will emit+ # everything currently visible (matches pre-migration gmail+ # behaviour at line 728-736 of services/deployment/manager.py).+ seen: Set[str] = set()+ try:+ seen = await self.fetch_ids(service, params)+ logger.info(+ "Polling trigger baseline established",+ node_id=node_id, node_type=self.type, seen=len(seen),+ )+ except Exception as exc: # noqa: BLE001+ logger.warning(+ "Polling trigger baseline failed; treating all as new",+ node_id=node_id, node_type=self.type, error=str(exc),+ )++ cycle = 0+ while is_running_fn():+ await asyncio.sleep(interval)+ if not is_running_fn():+ break+ cycle += 1+ try:+ current = await self.fetch_ids(service, params)+ new_ids = current - seen+ if not new_ids:+ continue+ logger.debug(+ "Polling trigger cycle",+ node_id=node_id, node_type=self.type, cycle=cycle,+ current=len(current), seen=len(seen),+ new=len(new_ids),+ )+ for msg_id in new_ids:+ seen.add(msg_id)+ payload = await self.fetch_detail(+ service, msg_id, params+ )+ await queue.put(payload)+ # post_emit failure must NOT block the next emit+ # nor kill the loop; mirrors pre-migration+ # try/except at gmail :760-763 / email :799-806.+ try:+ await self.post_emit(service, msg_id, params)+ except Exception:+ pass+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 -- per-cycle isolation+ logger.error(+ "Polling trigger cycle error; retrying next interval",+ node_id=node_id, node_type=self.type,+ error=str(exc),+ )++ return poll