Skip to content

Self-improving AI Employees for everyone

feat(plugin): Wave 11.A — BaseNode + declarative plugin-first foundation

trohitg573f6e85db06
diff --git a/server/services/node_registry.py b/server/services/node_registry.py
index 32f84beb..cb7adf77 100644
--- a/server/services/node_registry.py
+++ b/server/services/node_registry.py
@@ -35,6 +35,11 @@ from services.node_output_schemas import NODE_OUTPUT_SCHEMAS
_HANDLER_REGISTRY: dict[str, Callable] = {}
+# Plugin-class registry populated by :class:`BaseNode.__init_subclass__`.
+# Separate from _HANDLER_REGISTRY so the Temporal worker (11.F) can walk
+# plugin classes directly without re-discovering them.
+_NODE_CLASS_REGISTRY: dict[str, type] = {}
+
def register_node(
*,
@@ -85,6 +90,31 @@ def registered_node_types() -> frozenset[str]:
return frozenset(_HANDLER_REGISTRY.keys())
+def register_node_class(node_cls: type) -> None:
+ """Store a :class:`services.plugin.BaseNode` subclass reference.
+
+ Called from ``BaseNode.__init_subclass__`` after the eager
+ ``register_node(...)`` write. Lets Wave 11.F's Temporal worker walk
+ ``_NODE_CLASS_REGISTRY.values()`` to collect ``cls.as_activity()``
+ for registration, without re-discovering via the filesystem.
+ """
+ if not getattr(node_cls, "type", ""):
+ return
+ _NODE_CLASS_REGISTRY[node_cls.type] = node_cls
+
+
+def get_node_class(node_type: str) -> Optional[type]:
+ """Return the :class:`BaseNode` subclass for ``node_type``, or None
+ if this type was registered via the legacy metadata-only form."""
+ return _NODE_CLASS_REGISTRY.get(node_type)
+
+
+def registered_node_classes() -> dict[str, type]:
+ """Snapshot of the plugin-class registry. Used by the Temporal
+ worker to register one activity per plugin."""
+ return dict(_NODE_CLASS_REGISTRY)
+
+
def register_group(*, key: str, metadata: GroupMetadata) -> None:
"""Register a component-palette group's metadata.
diff --git a/server/services/plugin/__init__.py b/server/services/plugin/__init__.py
new file mode 100644
index 00000000..124b052e
--- /dev/null
+++ b/server/services/plugin/__init__.py
@@ -0,0 +1,73 @@
+"""Wave 11 plugin-first node system.
+
+One class per node. Inherit from :class:`ActionNode`,
+:class:`TriggerNode`, or :class:`ToolNode`, declare metadata + Pydantic
+``Params`` / ``Output``, and decorate operation methods with
+``@Operation``. :func:`services.node_registry.register_node` accepts the
+class directly and writes into the existing four registries.
+
+Public API (re-exported here):
+
+- :class:`BaseNode` — invariants + lifecycle (broadcast, track, wrap)
+- :class:`ActionNode` / :class:`TriggerNode` / :class:`ToolNode` — kinds
+- :class:`Operation` — decorator; declarative routing optional
+- :class:`Routing` — pure-declarative REST DSL
+- :class:`Credential` / :class:`OAuth2Credential` / :class:`ApiKeyCredential`
+- :class:`Connection` — auth-aware HTTP facade (Nango pattern)
+- :class:`NodeContext` — typed execution context
+- :class:`Interceptor` — cross-cutting concerns (Temporal pattern)
+- :class:`RetryPolicy` — per-node Temporal retry knobs
+
+Temporal integration (11.F): every subclass exposes
+:meth:`BaseNode.as_activity` to produce an ``@activity.defn`` wrapper.
+``task_queue`` class attribute routes to a specialised worker pool.
+"""
+
+from __future__ import annotations
+
+from services.plugin.base import BaseNode
+from services.plugin.action import ActionNode
+from services.plugin.trigger import TriggerNode
+from services.plugin.tool import ToolNode
+from services.plugin.operation import Operation, OperationSpec
+from services.plugin.routing import Routing, RoutingRequest, RoutingOutput, execute_routing
+from services.plugin.credential import (
+ Credential,
+ OAuth2Credential,
+ ApiKeyCredential,
+ CREDENTIAL_REGISTRY,
+)
+from services.plugin.connection import Connection
+from services.plugin.context import NodeContext
+from services.plugin.scaling import (
+ RetryPolicy,
+ TaskQueue,
+ DEFAULT_START_TO_CLOSE,
+ DEFAULT_HEARTBEAT,
+)
+from services.plugin.interceptor import Interceptor, InterceptorChain
+
+__all__ = [
+ "BaseNode",
+ "ActionNode",
+ "TriggerNode",
+ "ToolNode",
+ "Operation",
+ "OperationSpec",
+ "Routing",
+ "RoutingRequest",
+ "RoutingOutput",
+ "execute_routing",
+ "Credential",
+ "OAuth2Credential",
+ "ApiKeyCredential",
+ "CREDENTIAL_REGISTRY",
+ "Connection",
+ "NodeContext",
+ "RetryPolicy",
+ "TaskQueue",
+ "DEFAULT_START_TO_CLOSE",
+ "DEFAULT_HEARTBEAT",
+ "Interceptor",
+ "InterceptorChain",
+]
diff --git a/server/services/plugin/action.py b/server/services/plugin/action.py
new file mode 100644
index 00000000..c9d204fa
--- /dev/null
+++ b/server/services/plugin/action.py
@@ -0,0 +1,21 @@
+"""ActionNode — fire-once node (gmail send, httpRequest, whatsappSend).
+
+Inherits :class:`BaseNode` semantics unchanged: validate params,
+dispatch op, wrap result. Exists as a distinct class so contract
+invariants and the executor can distinguish kinds.
+"""
+
+from __future__ import annotations
+
+from typing import ClassVar
+
+from services.plugin.base import BaseNode
+from services.plugin.scaling import ACTION_START_TO_CLOSE, TaskQueue
+
+
+class ActionNode(BaseNode, abstract=True):
+ """Base class for fire-once action nodes."""
+
+ component_kind: ClassVar[str] = "generic"
+ task_queue: ClassVar[str] = TaskQueue.REST_API
+ start_to_close_timeout = ACTION_START_TO_CLOSE
diff --git a/server/services/plugin/base.py b/server/services/plugin/base.py
new file mode 100644
index 00000000..d8d1225e
--- /dev/null
+++ b/server/services/plugin/base.py
@@ -0,0 +1,363 @@
+"""BaseNode — foundation for Wave 11 plugin-first nodes.
+
+Every ActionNode / TriggerNode / ToolNode inherits from here. Invariants:
+
+- ``__init_subclass__`` collects ``@Operation`` methods into ``_operations``
+ and registers the class into the four legacy registries via
+ ``services.node_registry.register_node``.
+- :meth:`execute` enforces the universal handler signature
+ ``(node_id, parameters, context) -> Dict[str, Any]`` and orchestrates:
+ parameter validation → credential resolve → operation dispatch
+ (with optional declarative routing) → result wrap → usage track.
+- :meth:`as_activity` produces a Temporal-compatible callable for 11.F.
+
+Subclasses set class attributes rather than pass constructor args —
+the class itself *is* the declaration. This keeps node modules flat
+and lets the class object function as the plugin manifest.
+"""
+
+from __future__ import annotations
+
+import time
+from datetime import datetime, timezone
+from typing import Any, Awaitable, Callable, ClassVar, Dict, List, Optional, Sequence, Type
+
+from pydantic import BaseModel, ValidationError
+
+from core.logging import get_logger
+from services.plugin.connection import Connection
+from services.plugin.context import NodeContext
+from services.plugin.credential import Credential
+from services.plugin.operation import OperationSpec, collect_operations
+from services.plugin.routing import execute_routing
+from services.plugin.scaling import (
+ ACTION_START_TO_CLOSE,
+ DEFAULT_HEARTBEAT,
+ DEFAULT_RETRY,
+ RetryPolicy,
+ TaskQueue,
+)
+
+logger = get_logger(__name__)
+
+
+# Sentinel used by Params-less nodes so .model_validate({}) works.
+class _EmptyParams(BaseModel):
+ pass
+
+
+class _EmptyOutput(BaseModel):
+ pass
+
+
+class BaseNode:
+ """Abstract plugin node. Do not instantiate directly — subclass
+ :class:`ActionNode`, :class:`TriggerNode`, or :class:`ToolNode`.
+
+ ===== Declaration (class attributes) =====
+
+ ``type`` node type string, matches workflow JSON / registry key
+ ``version`` integer, bumped for breaking changes
+ ``display_name`` shown in palette + parameter panel header
+ ``subtitle`` shown under display_name in the node header
+ ``icon`` Wave 10.B wire format: "asset:k" / "lobehub:b" / emoji
+ ``color`` hex or dracula token, e.g. "#bd93f9"
+ ``group`` palette groupings, e.g. ["search", "tool"]
+ ``description`` one-line help
+ ``handles`` NodeHandle[] — React Flow topology
+ ``visibility`` "all" / "normal" / "dev"
+ ``hide_output_handle`` bool — replaces NO_OUTPUT_NODE_TYPES
+ ``ui_hints`` dict of flags consumed by parameter panel
+ ``annotations`` Pipedream-style: destructive / readonly / open_world
+
+ ``Params`` Pydantic model — user-facing parameters
+ ``Output`` Pydantic model — runtime output schema
+ ``credentials`` tuple of :class:`Credential` subclasses this node uses
+
+ ``task_queue`` Temporal worker pool (see :class:`TaskQueue`)
+ ``retry_policy`` per-node retry knobs
+ ``start_to_close_timeout`` / ``heartbeat_timeout``
+
+ ``component_kind`` frontend dispatch key — set by subclass
+ ``usable_as_tool`` ActionNode-only — mints a ToolNode adapter
+
+ Operations: methods decorated with ``@Operation("name")``. The
+ multi-op dispatcher reads ``parameters.operation``. Single-op nodes
+ call the sole operation regardless of the ``operation`` field.
+ """
+
+ # ---- declaration (override in subclass) -------------------------------
+ type: ClassVar[str] = ""
+ version: ClassVar[int] = 1
+ display_name: ClassVar[str] = ""
+ subtitle: ClassVar[str] = ""
+ icon: ClassVar[str] = ""
+ color: ClassVar[str] = ""
+ group: ClassVar[Sequence[str]] = ()
+ description: ClassVar[str] = ""
+ handles: ClassVar[Sequence[Dict[str, Any]]] = ()
+ visibility: ClassVar[str] = "all"
+ hide_output_handle: ClassVar[bool] = False
+ ui_hints: ClassVar[Dict[str, Any]] = {}
+ annotations: ClassVar[Dict[str, Any]] = {}
+
+ Params: ClassVar[Type[BaseModel]] = _EmptyParams
+ Output: ClassVar[Type[BaseModel]] = _EmptyOutput
+ credentials: ClassVar[Sequence[Type[Credential]]] = ()
+
+ task_queue: ClassVar[str] = TaskQueue.DEFAULT
+ retry_policy: ClassVar[RetryPolicy] = DEFAULT_RETRY
+ start_to_close_timeout = ACTION_START_TO_CLOSE
+ heartbeat_timeout = DEFAULT_HEARTBEAT
+ max_concurrent: ClassVar[Optional[int]] = None
+
+ component_kind: ClassVar[str] = "generic"
+ usable_as_tool: ClassVar[bool] = False
+
+ # Set by __init_subclass__: {op_name: OperationSpec}
+ _operations: ClassVar[Dict[str, OperationSpec]] = {}
+ # Flag so concrete subclasses auto-register; abstract kinds don't.
+ _abstract: ClassVar[bool] = True
+
+ # ---- subclass hook ----------------------------------------------------
+
+ def __init_subclass__(cls, abstract: bool = False, **kwargs):
+ super().__init_subclass__(**kwargs)
+ cls._abstract = abstract
+ cls._operations = collect_operations(cls)
+ if abstract or not cls.type:
+ return
+ # Eager registry write — same four registries as @register_node.
+ from services.node_registry import register_node, register_node_class
+ register_node(
+ type=cls.type,
+ metadata=cls._metadata_dict(),
+ input_model=cls.Params if cls.Params is not _EmptyParams else None,
+ output_model=cls.Output if cls.Output is not _EmptyOutput else None,
+ handler=cls._make_legacy_handler(),
+ )
+ register_node_class(cls)
+
+ # ---- metadata projection ---------------------------------------------
+
+ @classmethod
+ def _metadata_dict(cls) -> Dict[str, Any]:
+ """Project class attributes onto the :data:`NodeMetadata` TypedDict
+ expected by the existing node_spec emitter."""
+ meta: Dict[str, Any] = {
+ "displayName": cls.display_name or cls.type,
+ "icon": cls.icon,
+ "group": list(cls.group),
+ "description": cls.description,
+ "version": cls.version,
+ "componentKind": cls.component_kind,
+ }
+ if cls.subtitle:
+ meta["subtitle"] = cls.subtitle
+ if cls.color:
+ meta["color"] = cls.color
+ if cls.handles:
+ meta["handles"] = list(cls.handles)
+ if cls.credentials:
+ meta["credentials"] = [c.id for c in cls.credentials]
+ if cls.hide_output_handle:
+ meta["hideOutputHandle"] = True
+ if cls.visibility != "all":
+ meta["visibility"] = cls.visibility
+ if cls.ui_hints:
+ meta["uiHints"] = dict(cls.ui_hints)
+ return meta
+
+ # ---- legacy handler adapter ------------------------------------------
+
+ @classmethod
+ def _make_legacy_handler(cls) -> Callable[..., Awaitable[Dict[str, Any]]]:
+ """Produce a ``(node_id, node_type, parameters, context) -> dict``
+ callable for the existing executor registry. Discard node_type
+ (redundant — class is already the dispatch target) and route
+ through :meth:`execute`.
+ """
+ async def _legacy(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any],
+ ) -> Dict[str, Any]:
+ instance = cls()
+ ctx = NodeContext.from_legacy(
+ node_id=node_id,
+ node_type=node_type,
+ context=context,
+ connection_factory=_make_connection_factory(cls, context),
+ )
+ return await instance.execute(node_id, parameters, ctx)
+ _legacy.__node_class__ = cls # type: ignore[attr-defined]
+ _legacy.__qualname__ = f"{cls.__qualname__}._legacy_handler"
+ return _legacy
+
+ # ---- lifecycle --------------------------------------------------------
+
+ async def execute(
+ self,
+ node_id: str,
+ parameters: Dict[str, Any],
+ context: NodeContext,
+ ) -> Dict[str, Any]:
+ """Universal entry point. Validate params → dispatch op →
+ wrap result. Subclasses (TriggerNode, ToolNode) override to
+ change the return shape or lifetime.
+ """
+ start_time = time.time()
+
+ try:
+ params_obj = self._validate_params(parameters)
+ except ValidationError as e:
+ return self._wrap_error(
+ start_time=start_time,
+ error=f"Invalid parameters: {e.errors()[0].get('msg', str(e))}",
+ error_type="ValidationError",
+ )
+
+ op_name = self._pick_operation(parameters)
+ op_spec = self._operations.get(op_name)
+ if op_spec is None:
+ return self._wrap_error(
+ start_time=start_time,
+ error=f"Unknown operation '{op_name}' for node {self.type}",
+ error_type="InvalidParametersError",
+ )
+
+ try:
+ result = await self._run_operation(op_spec, params_obj, context)
+ except PermissionError as e:
+ return self._wrap_error(
+ start_time=start_time, error=str(e), error_type="PermissionDeniedError"
+ )
+ except Exception as e:
+ logger.exception("[%s] operation %s failed", self.type, op_name)
+ return self._wrap_error(start_time=start_time, error=str(e), error_type=type(e).__name__)
+
+ return self._wrap_success(start_time=start_time, result=result)
+
+ # ---- internals --------------------------------------------------------
+
+ def _validate_params(self, parameters: Dict[str, Any]) -> BaseModel:
+ return self.Params.model_validate(parameters)
+
+ def _pick_operation(self, parameters: Dict[str, Any]) -> str:
+ """Multi-op nodes read ``parameters['operation']``. Single-op
+ nodes return the one registered name regardless."""
+ if not self._operations:
+ return ""
+ if len(self._operations) == 1:
+ return next(iter(self._operations))
+ return str(parameters.get("operation", ""))
+
+ async def _run_operation(
+ self,
+ spec: OperationSpec,
+ params_obj: BaseModel,
+ ctx: NodeContext,
+ ) -> Any:
+ """Execute either declarative routing or the method body."""
+ if spec.routing is not None:
+ # Pure-declarative: routing handles everything, method body
+ # is expected to be empty.
+ if not self.credentials:
+ raise RuntimeError(
+ f"Node {self.type} op {spec.name} has routing but no "
+ "credentials declared — routing needs a Connection."
+ )
+ cred = self.credentials[0]
+ conn = ctx.connection(cred.id)
+ try:
+ return await execute_routing(
+ spec.routing, params=params_obj.model_dump(), connection=conn,
+ )
+ finally:
+ await conn.aclose()
+
+ # Imperative: invoke the method body (bound via descriptor).
+ method = spec.method.__get__(self, type(self))
+ return await method(ctx, params_obj)
+
+ def _wrap_success(self, *, start_time: float, result: Any) -> Dict[str, Any]:
+ """95%-universal return shape. Subclasses (ToolNode) override."""
+ if isinstance(result, BaseModel):
+ result_data: Any = result.model_dump()
+ else:
+ result_data = result
+ return {
+ "success": True,
+ "result": result_data,
+ "execution_time": round(time.time() - start_time, 3),
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ }
+
+ def _wrap_error(
+ self, *, start_time: float, error: str, error_type: str = "Error"
+ ) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "error": error,
+ "error_type": error_type,
+ "execution_time": round(time.time() - start_time, 3),
+ "timestamp": datetime.now(timezone.utc).isoformat(),
+ }
+
+ # ---- Temporal ---------------------------------------------------------
+
+ @classmethod
+ def as_activity(cls):
+ """Wrap this node as a ``@activity.defn`` callable for Temporal
+ worker registration (11.F). Uses a stable activity name:
+ ``node.{type}.v{version}``.
+
+ Returns the decorated async function; the worker collects these
+ into ``activities=[...]``.
+ """
+ from temporalio import activity
+
+ activity_name = f"node.{cls.type}.v{cls.version}"
+
+ @activity.defn(name=activity_name)
+ async def _node_activity(payload: Dict[str, Any]) -> Dict[str, Any]:
+ # Temporal lives in another process — rebuild NodeContext.
+ context_dict = payload.get("context", {})
+ instance = cls()
+ ctx = NodeContext.from_legacy(
+ node_id=payload["node_id"],
+ node_type=cls.type,
+ context=context_dict,
+ connection_factory=_make_connection_factory(cls, context_dict),
+ )
+ return await instance.execute(payload["node_id"], payload["parameters"], ctx)
+
+ return _node_activity
+
+
+# ---------------------------------------------------------------------------
+# Connection factory — avoids circular import with NodeContext.
+
+def _make_connection_factory(
+ node_cls: Type[BaseNode],
+ context: Dict[str, Any],
+) -> Callable[[str], Connection]:
+ user_id = context.get("user_id", "owner")
+ session_id = context.get("session_id", "default")
+ node_id = context.get("node_id")
+ # Precompute credential lookup once.
+ creds_by_id: Dict[str, Type[Credential]] = {c.id: c for c in node_cls.credentials}
+
+ def factory(credential_id: str) -> Connection:
+ cred_cls = creds_by_id.get(credential_id)
+ if cred_cls is None:
+ raise RuntimeError(
+ f"Node {node_cls.type} did not declare credential '{credential_id}' "
+ f"but tried to use it. Add it to the `credentials` class attribute."
+ )
+ return Connection(
+ cred_cls, user_id=user_id, session_id=session_id, node_id=node_id,
+ )
+
+ return factory
diff --git a/server/services/plugin/connection.py b/server/services/plugin/connection.py
new file mode 100644
index 00000000..7cfacbd3
--- /dev/null
+++ b/server/services/plugin/connection.py
@@ -0,0 +1,136 @@
+"""Authed HTTP facade (Nango pattern).
+
+Handlers never see tokens. They call ``await ctx.connection(id).get(url)``
+and the Connection resolves credentials, injects auth into the request,
+handles retry on auth failure, and tracks usage for cost attribution.
+
+Only HTTP-bearing credentials use this — an LLM API key inside a
+native SDK call still goes through ``cred_class.resolve()`` directly.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, Optional
+
+import httpx
+
+from core.logging import get_logger
+from services.plugin.credential import Credential
+
+logger = get_logger(__name__)
+
+
+class Connection:
+ """Lazy, per-call authed httpx wrapper bound to a credential class.
+
+ One instance per (credential_id, user_id, session_id) per node call.
+ Created by :meth:`NodeContext.connection`. Not thread-safe — each
+ concurrent node call should get its own.
+ """
+
+ def __init__(
+ self,
+ credential_cls: type[Credential],
+ *,
+ user_id: str = "owner",
+ timeout: float = 30.0,
+ session_id: str = "default",
+ node_id: Optional[str] = None,
+ ):
+ self._cred_cls = credential_cls
+ self._user_id = user_id
+ self._timeout = timeout
+ self._session_id = session_id
+ self._node_id = node_id
+ self._secrets: Optional[Dict[str, Any]] = None
+ self._client: Optional[httpx.AsyncClient] = None
+
+ @property
+ def credential_id(self) -> str:
+ return self._cred_cls.id
+
+ async def credentials(self) -> Dict[str, Any]:
+ """Resolved secret dict (cached). Raises ``PermissionError`` if
+ the user hasn't connected this provider."""
+ if self._secrets is None:
+ self._secrets = await self._cred_cls.resolve(user_id=self._user_id)
+ return self._secrets
+
+ async def refresh(self) -> Dict[str, Any]:
+ """Force a re-resolve (after a 401/403). The auth service is
+ responsible for actually rotating the token."""
+ self._secrets = None
+ return await self.credentials()
+
+ def _get_client(self) -> httpx.AsyncClient:
+ if self._client is None:
+ self._client = httpx.AsyncClient(timeout=self._timeout)
+ return self._client
+
+ async def aclose(self) -> None:
+ if self._client is not None:
+ await self._client.aclose()
+ self._client = None
+
+ async def __aenter__(self) -> "Connection":
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb) -> None:
+ await self.aclose()
+
+ async def request(
+ self,
+ method: str,
+ url: str,
+ *,
+ headers: Optional[Dict[str, str]] = None,
+ params: Optional[Dict[str, Any]] = None,
+ json: Optional[Any] = None,
+ data: Optional[Any] = None,
+ _retry_on_auth: bool = True,
+ ) -> httpx.Response:
+ secrets = await self.credentials()
+ req: Dict[str, Any] = {
+ "headers": dict(headers or {}),
+ "params": dict(params or {}),
+ }
+ if json is not None:
+ req["json"] = json
+ if data is not None:
+ req["data"] = data
+ req = self._cred_cls.inject(secrets, req)
+
+ client = self._get_client()
+ response = await client.request(method, url, **req)
+
+ if _retry_on_auth and response.status_code in (401, 403):
+ logger.debug(
+ "[Connection] auth retry for %s (%s) status=%s",
+ self.credential_id, method, response.status_code,
+ )
+ await self.refresh()
+ secrets = await self.credentials()
+ req_retry = self._cred_cls.inject(secrets, {
+ "headers": dict(headers or {}),
+ "params": dict(params or {}),
+ **({"json": json} if json is not None else {}),
+ **({"data": data} if data is not None else {}),
+ })
+ response = await client.request(method, url, **req_retry)
+
+ return response
+
+ async def get(self, url: str, **kwargs) -> httpx.Response:
+ return await self.request("GET", url, **kwargs)
+
+ async def post(self, url: str, **kwargs) -> httpx.Response:
+ return await self.request("POST", url, **kwargs)
+
+ async def put(self, url: str, **kwargs) -> httpx.Response:
+ return await self.request("PUT", url, **kwargs)
+
+ async def delete(self, url: str, **kwargs) -> httpx.Response:
+ return await self.request("DELETE", url, **kwargs)
+
+ async def patch(self, url: str, **kwargs) -> httpx.Response:
+ return await self.request("PATCH", url, **kwargs)
diff --git a/server/services/plugin/context.py b/server/services/plugin/context.py
new file mode 100644
index 00000000..85817fc8
--- /dev/null
+++ b/server/services/plugin/context.py
@@ -0,0 +1,80 @@
+"""Typed execution context passed to every plugin method.
+
+Replaces the raw ``context: Dict[str, Any]`` that every legacy handler
+receives. Keeps the dict for backwards-compat (``ctx.raw``) while
+exposing typed accessors for the common cases and a Connection factory
+for credential-backed calls.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any, Callable, Dict, Optional
+
+if TYPE_CHECKING:
+ from services.plugin.connection import Connection
+
+
+@dataclass
+class NodeContext:
+ """Execution context passed to every :meth:`BaseNode.execute` call.
+
+ Construct via :meth:`from_legacy` to wrap the existing ``Dict``
+ shape used by ``node_executor.dispatch``.
+ """
+
+ node_id: str
+ node_type: str
+ workflow_id: Optional[str] = None
+ session_id: str = "default"
+ execution_id: Optional[str] = None
+ user_id: str = "owner"
+ workspace_dir: Optional[str] = None
+ # Original outputs/nodes/edges for graph-aware nodes (console, pythonExecutor, …)
+ outputs: Dict[str, Any] = field(default_factory=dict)
+ nodes: list = field(default_factory=list)
+ edges: list = field(default_factory=list)
+ # Raw context dict — escape hatch for nodes that need extra fields
+ # we haven't typed yet. Prefer typed access when possible.
+ raw: Dict[str, Any] = field(default_factory=dict)
+ # Connection factory injected by the executor; default stub so
+ # pure-Pydantic tests work without auth_service wiring.
+ _connection_factory: Optional[Callable[[str], "Connection"]] = None
+
+ @classmethod
+ def from_legacy(
+ cls,
+ node_id: str,
+ node_type: str,
+ context: Dict[str, Any],
+ *,
+ connection_factory: Optional[Callable[[str], "Connection"]] = None,
+ ) -> "NodeContext":
+ return cls(
+ node_id=node_id,
+ node_type=node_type,
+ workflow_id=context.get("workflow_id"),
+ session_id=context.get("session_id", "default"),
+ execution_id=context.get("execution_id"),
+ user_id=context.get("user_id", "owner"),
+ workspace_dir=context.get("workspace_dir"),
+ outputs=context.get("outputs", {}) or {},
+ nodes=context.get("nodes", []) or [],
+ edges=context.get("edges", []) or [],
+ raw=context,
+ _connection_factory=connection_factory,
+ )
+
+ def connection(self, credential_id: str) -> "Connection":
+ """Return an authed :class:`Connection` for ``credential_id``.
+
+ The factory is injected by the executor; raising here (instead
+ of returning a stub) surfaces missing-credential errors at the
+ first call site rather than deep inside an API request.
+ """
+ if self._connection_factory is None:
+ raise RuntimeError(
+ f"No connection factory wired for credential '{credential_id}'. "
+ "NodeContext must be constructed via the executor, not directly."
+ )
+ return self._connection_factory(credential_id)
diff --git a/server/services/plugin/credential.py b/server/services/plugin/credential.py
new file mode 100644
index 00000000..eec9f361
--- /dev/null
+++ b/server/services/plugin/credential.py
@@ -0,0 +1,175 @@
+"""Declarative credential types (n8n + Pipedream pattern).
+
+A :class:`Credential` subclass describes how a provider is authenticated
+and how its secret is stored. One Google credential is shared across
+gmail / calendar / drive / sheets / tasks / contacts — nodes just
+reference the class. The :class:`Connection` facade resolves secrets at
+call time; handlers never see tokens.
+
+Two concrete bases:
+
+- :class:`OAuth2Credential` — user-authorised tokens (refresh-capable)
+- :class:`ApiKeyCredential` — static secret (header / query injection)
+
+Both are discovered at import time via :data:`CREDENTIAL_REGISTRY`
+(populated by ``__init_subclass__``). Nothing else needs to wire them.
+"""
+
+from __future__ import annotations
+
+from typing import Any, ClassVar, Dict, Literal, Optional, Sequence
+
+
+CREDENTIAL_REGISTRY: Dict[str, type] = {}
+
+
+class Credential:
+ """Base class for provider credentials.
+
+ Subclasses set class attributes — the class itself is the
+ declaration. Never instantiate directly; use
+ :class:`OAuth2Credential` or :class:`ApiKeyCredential`.
+ """
+
+ id: ClassVar[str] = ""
+ display_name: ClassVar[str] = ""
+ auth: ClassVar[Literal["oauth2", "api_key", "basic", "custom"]] = "custom"
+ # Icon key for the credentials modal — follows node icon wire format
+ # ("lobehub:gmail", "asset:serper", "🔑", etc.)
+ icon: ClassVar[str] = ""
+ # UI grouping (e.g. "AI", "Search", "Communication")
+ category: ClassVar[str] = "Other"
+ # Scopes requested / required — OAuth only, but declared uniformly
+ scopes: ClassVar[Sequence[str]] = ()
+ # Documentation URL for the user (credentials modal link)
+ docs_url: ClassVar[Optional[str]] = None
+
+ def __init_subclass__(cls, **kwargs):
+ super().__init_subclass__(**kwargs)
+ if cls.id:
+ if cls.id in CREDENTIAL_REGISTRY and CREDENTIAL_REGISTRY[cls.id] is not cls:
+ # Idempotent on re-import — only warn on genuine conflict.
+ existing = CREDENTIAL_REGISTRY[cls.id]
+ if existing.__qualname__ != cls.__qualname__:
+ raise ValueError(
+ f"Credential id '{cls.id}' registered by "
+ f"{existing.__qualname__} and now by {cls.__qualname__}"
+ )
+ CREDENTIAL_REGISTRY[cls.id] = cls
+
+ @classmethod
+ async def resolve(cls, *, user_id: str = "owner") -> Dict[str, Any]:
+ """Fetch secrets from the auth service.
+
+ Default implementation is abstract — subclasses override.
+ """
+ raise NotImplementedError
+
+ @classmethod
+ def inject(cls, secrets: Dict[str, Any], request: Dict[str, Any]) -> Dict[str, Any]:
+ """Mutate an httpx request dict (headers / params / json / auth)
+ to carry authentication. Default is no-op — declarative subclasses
+ override to implement their auth scheme.
+ """
+ return request
+
+
+class OAuth2Credential(Credential):
+ """OAuth 2.0 with refresh-token support.
+
+ Tokens resolved via ``auth_service.get_oauth_tokens(id, user_id)``
+ which handles refresh transparently. The :class:`Connection` facade
+ retries on 401/403 by re-calling :meth:`resolve`.
+ """
+
+ auth: ClassVar[Literal["oauth2"]] = "oauth2"
+ authorization_url: ClassVar[str] = ""
+ token_url: ClassVar[str] = ""
+ # How the access token rides on requests
+ token_location: ClassVar[Literal["header", "query"]] = "header"
+ token_header: ClassVar[str] = "Authorization"
+ token_prefix: ClassVar[str] = "Bearer "
+ # Keys the user enters in credentials modal (API-key style rows)
+ client_id_api_key: ClassVar[str] = "" # e.g. "google_client_id"
+ client_secret_api_key: ClassVar[str] = "" # e.g. "google_client_secret"
+
+ @classmethod
+ async def resolve(cls, *, user_id: str = "owner") -> Dict[str, Any]:
+ from core.container import container
+
+ auth_service = container.auth_service()
+ tokens = await auth_service.get_oauth_tokens(cls.id, user_id)
+ if not tokens or not tokens.get("access_token"):
+ raise PermissionError(
+ f"No OAuth tokens for '{cls.id}'. Connect via Credentials modal."
+ )
+ return tokens
+
+ @classmethod
+ def inject(cls, secrets: Dict[str, Any], request: Dict[str, Any]) -> Dict[str, Any]:
+ token = secrets.get("access_token", "")
+ if cls.token_location == "header":
+ headers = dict(request.get("headers") or {})
+ headers[cls.token_header] = f"{cls.token_prefix}{token}"
+ request = {**request, "headers": headers}
+ else:
+ qs = dict(request.get("params") or {})
+ qs[cls.token_header] = token
+ request = {**request, "params": qs}
+ return request
+
+
+class ApiKeyCredential(Credential):
+ """Static API key with declarative injection into headers or query.
+
+ Example::
+
+ class BraveCredential(ApiKeyCredential):
+ id = "brave_search"
+ display_name = "Brave Search"
+ category = "Search"
+ key_name = "X-Subscription-Token"
+ key_location = "header"
+ """
+
+ auth: ClassVar[Literal["api_key"]] = "api_key"
+ # Where the key goes
+ key_name: ClassVar[str] = "" # header name or query-string key
+ key_location: ClassVar[Literal["header", "query", "bearer"]] = "header"
+ # Extra fields stored alongside (e.g. "apify_account_id" for Apify)
+ extra_fields: ClassVar[Sequence[str]] = ()
+
+ @classmethod
+ async def resolve(cls, *, user_id: str = "owner") -> Dict[str, Any]:
+ from core.container import container
+
+ auth_service = container.auth_service()
+ api_key = await auth_service.get_api_key(cls.id)
+ if not api_key:
+ raise PermissionError(
+ f"No API key for '{cls.id}'. Add via Credentials modal."
+ )
+ secrets: Dict[str, Any] = {"api_key": api_key}
+ for field in cls.extra_fields:
+ value = await auth_service.get_api_key(field)
+ if value:
+ secrets[field] = value
+ return secrets
+
+ @classmethod
+ def inject(cls, secrets: Dict[str, Any], request: Dict[str, Any]) -> Dict[str, Any]:
+ api_key = secrets.get("api_key", "")
+ name = cls.key_name or "Authorization"
+ if cls.key_location == "header":
+ headers = dict(request.get("headers") or {})
+ headers[name] = api_key
+ request = {**request, "headers": headers}
+ elif cls.key_location == "bearer":
+ headers = dict(request.get("headers") or {})
+ headers["Authorization"] = f"Bearer {api_key}"
+ request = {**request, "headers": headers}
+ else: # "query"
+ qs = dict(request.get("params") or {})
+ qs[name] = api_key
+ request = {**request, "params": qs}
+ return request
diff --git a/server/services/plugin/interceptor.py b/server/services/plugin/interceptor.py
new file mode 100644
index 00000000..1352aea8
--- /dev/null
+++ b/server/services/plugin/interceptor.py
@@ -0,0 +1,70 @@
+"""Interceptor chain for cross-cutting concerns (Temporal pattern).
+
+Wrap every :meth:`BaseNode.execute` call in an ordered chain — logging,
+cost tracking, heartbeats, retry. Each interceptor calls ``next(input)``
+like middleware. Registered globally in ``services/plugin/base.py``;
+plugins don't need to know they exist.
+
+Keep the interface tiny on purpose — this is an extension point, not a
+framework. If you find yourself adding seven interceptors, something
+else is wrong.
+"""
+
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from dataclasses import dataclass
+from typing import Any, Awaitable, Callable, Dict, List, Optional
+
+
+@dataclass
+class InterceptorInput:
+ node_id: str
+ node_type: str
+ parameters: Dict[str, Any]
+ context: Any # NodeContext (avoid cycle in type hint)
+
+
+class Interceptor(ABC):
+ """Interceptor ABC — subclass and implement :meth:`intercept`."""
+
+ @abstractmethod
+ async def intercept(
+ self,
+ input: InterceptorInput,
+ next: Callable[[InterceptorInput], Awaitable[Dict[str, Any]]],
+ ) -> Dict[str, Any]:
+ """Wrap the call. Must call ``next(input)`` exactly once (unless
+ short-circuiting, e.g. for a cache hit)."""
+ ...
+
+
+class InterceptorChain:
+ """Compose interceptors into a single callable matching the
+ :meth:`BaseNode.execute` signature. Order matters — registered first
+ runs outermost.
+ """
+
+ def __init__(self, interceptors: Optional[List[Interceptor]] = None):
+ self._interceptors: List[Interceptor] = list(interceptors or [])
+
+ def add(self, interceptor: Interceptor) -> None:
+ self._interceptors.append(interceptor)
+
+ async def run(
+ self,
+ input: InterceptorInput,
+ terminal: Callable[[InterceptorInput], Awaitable[Dict[str, Any]]],
+ ) -> Dict[str, Any]:
+ """Invoke the chain, ending with ``terminal`` (the actual
+ plugin call). Each interceptor sees the same input."""
+ # Build nested call chain in reverse so interceptors[0] wraps outermost.
+ call = terminal
+ for interceptor in reversed(self._interceptors):
+ current_call = call
+
+ async def wrapped(inp, _intr=interceptor, _nxt=current_call):
+ return await _intr.intercept(inp, _nxt)
+
+ call = wrapped
+ return await call(input)
diff --git a/server/services/plugin/operation.py b/server/services/plugin/operation.py
new file mode 100644
index 00000000..0ce02183
--- /dev/null
+++ b/server/services/plugin/operation.py
@@ -0,0 +1,88 @@
+"""``@Operation`` decorator — the unit of work inside a multi-op node.
+
+A multi-op ``ActionNode`` (gmail send/search/read, whatsappDb's 18 ops,
+calendar CRUD) marks each method with ``@Operation("name")``. The base
+class dispatches on the ``operation`` Params field automatically.
+
+For single-op nodes, decorate the one method with
+``@Operation("default")`` (or ``@Operation("search")``, etc.) — the
+node's :class:`Params` doesn't need an ``operation`` field, and the
+lone op runs on every call.
+
+Declarative REST: pass ``routing=Routing(...)``, leave the method body
+empty (``pass``), and :func:`execute_routing` takes over.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Awaitable, Callable, Dict, Optional
+
+from services.plugin.routing import Routing
+
+
+@dataclass
+class OperationSpec:
+ """Metadata attached to a decorated method by :class:`Operation`.
+
+ ``method`` is the original async callable (bound later to the node
+ instance). Registry lookup: ``node_cls._operations[name] -> OperationSpec``.
+ """
+
+ name: str
+ method: Callable[..., Awaitable[Any]]
+ routing: Optional[Routing] = None
+ cost: Optional[Dict[str, Any]] = None # {"usage": "gmail_send", "count": 1}
+ annotations: Dict[str, Any] = field(default_factory=dict)
+
+
+class Operation:
+ """Decorator form — attaches an :class:`OperationSpec` to the method.
+
+ Usage::
+
+ @Operation("send", cost={"usage": "gmail_send", "count": 1})
+ async def send(self, ctx, params): ...
+
+ @Operation("search", routing=Routing(request=..., output=...))
+ async def search(self, ctx, params): pass
+ """
+
+ def __init__(
+ self,
+ name: str,
+ *,
+ routing: Optional[Routing] = None,
+ cost: Optional[Dict[str, Any]] = None,
+ annotations: Optional[Dict[str, Any]] = None,
+ ):
+ self.name = name
+ self.routing = routing
+ self.cost = cost
+ self.annotations = annotations or {}
+
+ def __call__(self, method):
+ spec = OperationSpec(
+ name=self.name,
+ method=method,
+ routing=self.routing,
+ cost=self.cost,
+ annotations=self.annotations,
+ )
+ # Tag the function; BaseNode's metaclass/__init_subclass__ collects.
+ method.__operation_spec__ = spec
+ return method
+
+
+def collect_operations(node_cls: type) -> Dict[str, OperationSpec]:
+ """Walk the class MRO, collect every method tagged with
+ ``__operation_spec__``. Subclass overrides win. Returns ``{name: spec}``.
+ """
+ ops: Dict[str, OperationSpec] = {}
+ # MRO reverse so subclass wins — iterate ancestors first, then subclass.
+ for klass in reversed(node_cls.__mro__):
+ for attr in klass.__dict__.values():
+ spec = getattr(attr, "__operation_spec__", None)
+ if spec is not None:
+ ops[spec.name] = spec
+ return ops
diff --git a/server/services/plugin/routing.py b/server/services/plugin/routing.py
new file mode 100644
index 00000000..4b06836a
--- /dev/null
+++ b/server/services/plugin/routing.py
@@ -0,0 +1,186 @@
+"""Declarative REST routing DSL (n8n + Nango pattern).
+
+Attach a :class:`Routing` to an :class:`Operation` and the node needs
+no handler body — :func:`execute_routing` walks the model, interpolates
+``={{params.x}}`` / ``={{credentials.y}}`` templates, dispatches via the
+:class:`Connection`, and runs ``post_receive`` transforms.
+
+Only covers straightforward REST. Escape hatch: leave ``routing=None``
+and write the operation method normally.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import Any, Dict, List, Literal, Optional
+
+from pydantic import BaseModel, Field
+
+_EXPR_RE = re.compile(r"=\{\{\s*(.+?)\s*\}\}")
+
+
+class RoutingRequest(BaseModel):
+ """Declarative HTTP request. String values may contain
+ ``={{params.foo}}`` / ``={{credentials.bar}}`` templates resolved at
+ call time.
+ """
+
+ method: Literal["GET", "POST", "PUT", "DELETE", "PATCH"] = "GET"
+ url: str
+ headers: Dict[str, str] = Field(default_factory=dict)
+ qs: Dict[str, Any] = Field(default_factory=dict)
+ body: Optional[Any] = None
+ # Body encoding — "json" (default) sends via httpx json=, "form" via data=
+ body_encoding: Literal["json", "form"] = "json"
+
+
+class PostReceiveAction(BaseModel):
+ """One transform in the ``post_receive`` chain. Named strategies live
+ in :data:`POST_RECEIVE_STRATEGIES` — ``type`` selects one.
+ """
+
+ type: Literal["root_property", "limit", "filter", "set"] = "root_property"
+ # Type-specific args (e.g. ``property="data"`` for root_property)
+ property: Optional[str] = None
+ max_items: Optional[int] = None
+ where: Optional[Dict[str, Any]] = None
+ set_fields: Optional[Dict[str, Any]] = None
+
+
+class RoutingOutput(BaseModel):
+ post_receive: List[PostReceiveAction] = Field(default_factory=list)
+
+
+class Routing(BaseModel):
+ """Full declarative routing spec attached to an ``@Operation``."""
+
+ request: RoutingRequest
+ output: RoutingOutput = Field(default_factory=RoutingOutput)
+
+
+# ---------------------------------------------------------------------------
+# Template interpolation
+
+def _resolve_template(value: Any, env: Dict[str, Any]) -> Any:
+ """Resolve ``={{expr}}`` templates against ``env``. Non-string values
+ pass through. Supports dotted paths — ``params.maxResults``."""
+ if not isinstance(value, str):
+ return value
+ if not value.startswith("="):
+ return value
+
+ def replace(match: re.Match) -> str:
+ expr = match.group(1).strip()
+ parts = expr.split(".")
+ current: Any = env
+ for part in parts:
+ if isinstance(current, dict):
+ current = current.get(part)
+ else:
+ current = getattr(current, part, None)
+ if current is None:
+ return ""
+ return str(current)
+
+ # Strip leading "=" marker then interpolate.
+ stripped = value[1:]
+ return _EXPR_RE.sub(replace, stripped)
+
+
+def _resolve_dict(d: Dict[str, Any], env: Dict[str, Any]) -> Dict[str, Any]:
+ return {k: _resolve_template(v, env) for k, v in d.items()}
+
+
+# ---------------------------------------------------------------------------
+# post_receive strategies
+
+def _strategy_root_property(data: Any, action: PostReceiveAction) -> Any:
+ if not action.property or not isinstance(data, dict):
+ return data
+ current: Any = data
+ for part in action.property.split("."):
+ if not isinstance(current, dict):
+ return current
+ current = current.get(part)
+ return current
+
+
+def _strategy_limit(data: Any, action: PostReceiveAction) -> Any:
+ if not isinstance(data, list) or action.max_items is None:
+ return data
+ return data[: action.max_items]
+
+
+def _strategy_filter(data: Any, action: PostReceiveAction) -> Any:
+ if not isinstance(data, list) or not action.where:
+ return data
+ return [item for item in data if all(
+ isinstance(item, dict) and item.get(k) == v for k, v in action.where.items()
+ )]
+
+
+def _strategy_set(data: Any, action: PostReceiveAction) -> Any:
+ if not action.set_fields:
+ return data
+ if isinstance(data, dict):
+ return {**data, **action.set_fields}
+ if isinstance(data, list):
+ return [{**item, **action.set_fields} if isinstance(item, dict) else item
+ for item in data]
+ return data
+
+
+POST_RECEIVE_STRATEGIES = {
+ "root_property": _strategy_root_property,
+ "limit": _strategy_limit,
+ "filter": _strategy_filter,
+ "set": _strategy_set,
+}
+
+
+# ---------------------------------------------------------------------------
+# Execution
+
+async def execute_routing(
+ routing: Routing,
+ *,
+ params: Dict[str, Any],
+ connection,
+) -> Any:
+ """Walk a :class:`Routing` spec, dispatch via ``connection``, and
+ apply ``post_receive`` transforms. ``params`` is the already-validated
+ Pydantic params dict (``.model_dump()``). Credentials come from
+ ``connection`` — they're not in ``env``; ``={{credentials.x}}``
+ templates read the Connection's resolved secrets.
+ """
+ secrets = await connection.credentials()
+ env = {"params": params, "credentials": secrets}
+
+ req = routing.request
+ method = req.method
+ url = _resolve_template(req.url, env)
+ headers = _resolve_dict(req.headers, env)
+ qs = {k: v for k, v in _resolve_dict(req.qs, env).items() if v not in (None, "")}
+
+ kwargs: Dict[str, Any] = {"headers": headers, "params": qs}
+ if req.body is not None:
+ body_resolved = (
+ _resolve_dict(req.body, env) if isinstance(req.body, dict) else
+ _resolve_template(req.body, env)
+ )
+ if req.body_encoding == "form":
+ kwargs["data"] = body_resolved
+ else:
+ kwargs["json"] = body_resolved
+
+ response = await connection.request(method, url, **kwargs)
+ response.raise_for_status()
+ data: Any = response.json() if response.content else None
+
+ for action in routing.output.post_receive:
+ strategy = POST_RECEIVE_STRATEGIES.get(action.type)
+ if strategy is None:
+ raise ValueError(f"Unknown post_receive strategy: {action.type}")
+ data = strategy(data, action)
+
+ return data
diff --git a/server/services/plugin/scaling.py b/server/services/plugin/scaling.py
new file mode 100644
index 00000000..759df692
--- /dev/null
+++ b/server/services/plugin/scaling.py
@@ -0,0 +1,78 @@
+"""Temporal-aligned scaling knobs shared by every plugin node.
+
+Each :class:`BaseNode` subclass declares ``task_queue`` +
+``retry_policy`` + ``start_to_close_timeout`` + ``heartbeat_timeout`` as
+class attributes. The Temporal dispatcher (11.F) reads these when
+spawning activities; the in-process executor ignores them. Defaults
+here keep new nodes safe without any explicit configuration.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from datetime import timedelta
+from typing import Sequence
+
+
+class TaskQueue:
+ """Named worker-pool queues. Workers subscribe to one or more; every
+ plugin declares which queue runs it. New queues = add a string here
+ and provision a worker pool in ``services/temporal/worker.py``.
+ """
+
+ DEFAULT = "machina-default" # catch-all
+ REST_API = "rest-api" # lightweight HTTP calls (gmail, brave, twitter)
+ AI_HEAVY = "ai-heavy" # long-running LLM + agent loops
+ CODE_EXEC = "code-exec" # python/js/ts sandboxed execution
+ TRIGGERS_POLL = "triggers-poll" # polling triggers (long-lived)
+ TRIGGERS_EVENT = "triggers-event" # event-waiter triggers (long-lived)
+ ANDROID = "android" # ADB / relay ops
+ BROWSER = "browser" # agent-browser, Playwright
+ MESSAGING = "messaging" # whatsapp / telegram / twitter send
+
+ ALL = frozenset({
+ DEFAULT, REST_API, AI_HEAVY, CODE_EXEC,
+ TRIGGERS_POLL, TRIGGERS_EVENT, ANDROID, BROWSER, MESSAGING,
+ })
+
+
+@dataclass(frozen=True)
+class RetryPolicy:
+ """Mirrors ``temporalio.common.RetryPolicy`` so plugins can declare
+ it without importing Temporal at class-definition time (the Temporal
+ SDK is a runtime-only dependency of the worker).
+ """
+
+ initial_interval: timedelta = timedelta(seconds=1)
+ backoff_coefficient: float = 2.0
+ maximum_interval: timedelta = timedelta(seconds=60)
+ maximum_attempts: int = 3
+ non_retryable_error_types: Sequence[str] = field(default_factory=lambda: (
+ "ValidationError",
+ "PermissionDeniedError",
+ "InvalidParametersError",
+ ))
+
+ def to_temporal(self):
+ """Lazy import — only called inside the Temporal worker."""
+ from temporalio.common import RetryPolicy as _RP
+
+ return _RP(
+ initial_interval=self.initial_interval,
+ backoff_coefficient=self.backoff_coefficient,
+ maximum_interval=self.maximum_interval,
+ maximum_attempts=self.maximum_attempts,
+ non_retryable_error_types=list(self.non_retryable_error_types),
+ )
+
+
+# Sensible kind-level defaults. Overridden by subclass attributes.
+DEFAULT_START_TO_CLOSE = timedelta(minutes=10)
+DEFAULT_HEARTBEAT = timedelta(minutes=2)
+DEFAULT_RETRY = RetryPolicy()
+
+# Kind-specific defaults — picked up when a subclass doesn't override.
+ACTION_START_TO_CLOSE = timedelta(minutes=10)
+AI_START_TO_CLOSE = timedelta(minutes=30)
+TRIGGER_START_TO_CLOSE = timedelta(hours=24) # long-lived
+CODE_START_TO_CLOSE = timedelta(minutes=5)
diff --git a/server/services/plugin/tool.py b/server/services/plugin/tool.py
new file mode 100644
index 00000000..47d6dcdb
--- /dev/null
+++ b/server/services/plugin/tool.py
@@ -0,0 +1,51 @@
+"""ToolNode — passive capability exposed to AI Agents via input-tools.
+
+Return shape differs from :class:`ActionNode`: the LLM harness expects a
+flat dict (no ``success`` wrapper). ``.as_tool_schema()`` produces the
+JSON Schema the LLM sees — derived from :class:`Params` automatically.
+"""
+
+from __future__ import annotations
+
+from typing import Any, ClassVar, Dict
+
+from services.plugin.base import BaseNode
+from services.plugin.scaling import TaskQueue
+
+
+class ToolNode(BaseNode, abstract=True):
+ """Base class for AI-Agent tool nodes (calculatorTool, currentTimeTool)."""
+
+ component_kind: ClassVar[str] = "tool"
+ task_queue: ClassVar[str] = TaskQueue.REST_API
+
+ # Tool-safety annotations (Pipedream pattern).
+ annotations: ClassVar[Dict[str, Any]] = {
+ "destructive": False,
+ "readonly": True,
+ "open_world": False,
+ }
+
+ @classmethod
+ def as_tool_schema(cls) -> Dict[str, Any]:
+ """LLM-visible schema: ``{name, description, parameters}`` where
+ ``parameters`` is the Pydantic JSON schema of :class:`Params`."""
+ schema = cls.Params.model_json_schema()
+ # Strip $defs / definitions — LLM function-calling doesn't cope.
+ schema.pop("$defs", None)
+ schema.pop("definitions", None)
+ return {
+ "name": cls.type,
+ "description": cls.description or cls.display_name or cls.type,
+ "parameters": schema,
+ }
+
+ def _wrap_success(self, *, start_time: float, result):
+ """Tools return flat result (no success wrapper)."""
+ from pydantic import BaseModel
+
+ if isinstance(result, BaseModel):
+ return result.model_dump()
+ if isinstance(result, dict):
+ return result
+ return {"result": result}
diff --git a/server/services/plugin/trigger.py b/server/services/plugin/trigger.py
new file mode 100644
index 00000000..2b84403e
--- /dev/null
+++ b/server/services/plugin/trigger.py
@@ -0,0 +1,110 @@
+"""TriggerNode — long-lived node that waits for external events.
+
+Two lifecycle modes:
+
+- **Event-based** (webhookTrigger, chatTrigger, whatsappReceive,
+ telegramReceive) — registers an :mod:`services.event_waiter` Future
+ with a filter function built from the node's params.
+- **Polling-based** (gmailReceive, emailReceive, twitterReceive) —
+ implements :meth:`poll_once` which the executor invokes on a schedule
+ (via :class:`TriggerManager` in deployment mode).
+
+Both modes share the TriggerNode contract: the node's single "run"
+returns once an event arrives; the returned shape mirrors the event
+data. In deployment mode, each arrival spawns a fresh workflow run.
+
+Plugins choose by setting :attr:`mode`:
+
+- ``"event"`` — provide :meth:`build_filter` and :attr:`event_type`
+- ``"polling"`` — provide :meth:`poll_once` and :attr:`poll_interval`
+"""
+
+from __future__ import annotations
+
+from typing import Any, Awaitable, Callable, ClassVar, Dict, Literal, Optional
+
+from pydantic import BaseModel
+
+from core.logging import get_logger
+from services.plugin.base import BaseNode
+from services.plugin.context import NodeContext
+from services.plugin.scaling import TaskQueue, TRIGGER_START_TO_CLOSE
+
+logger = get_logger(__name__)
+
+
+class TriggerNode(BaseNode, abstract=True):
+ """Base class for workflow trigger nodes."""
+
+ component_kind: ClassVar[str] = "trigger"
+ task_queue: ClassVar[str] = TaskQueue.TRIGGERS_EVENT
+ start_to_close_timeout = TRIGGER_START_TO_CLOSE
+
+ mode: ClassVar[Literal["event", "polling"]] = "event"
+ # Event mode: dispatch key in services.event_waiter.TRIGGER_REGISTRY
+ event_type: ClassVar[str] = ""
+ # Polling mode: default interval seconds; overridden by params.
+ default_poll_interval: ClassVar[int] = 60
+
+ # ---- subclass hooks ---------------------------------------------------
+
+ def build_filter(self, params: BaseModel) -> Callable[[Dict[str, Any]], bool]:
+ """Event mode — return a callable that accepts an event dict
+ and returns True if this trigger should fire. Default: match all.
+ """
+ return lambda _event: True
+
+ async def poll_once(
+ self,
+ ctx: NodeContext,
+ params: BaseModel,
+ state: Dict[str, Any],
+ ) -> Awaitable[Optional[Dict[str, Any]]]:
+ """Polling mode — check for new events. Return event data dict
+ or None if nothing new. ``state`` persists across polls for
+ tracking last-seen IDs.
+ """
+ raise NotImplementedError("Polling triggers must override poll_once")
+
+ # ---- lifecycle --------------------------------------------------------
+
+ async def execute(
+ self,
+ node_id: str,
+ parameters: Dict[str, Any],
+ context: NodeContext,
+ ) -> Dict[str, Any]:
+ """Run-node execution for triggers — registers a one-shot wait
+ and returns when the event fires. Used by the "Run" button.
+
+ Deployment-mode long-running watches are driven by
+ :class:`TriggerManager`, not this method.
+ """
+ import time
+ from services import event_waiter
+
+ start_time = time.time()
+
+ try:
+ params_obj = self._validate_params(parameters)
+ except Exception as e:
+ return self._wrap_error(start_time=start_time, error=f"Invalid parameters: {e}")
+
+ if self.mode == "event":
+ waiter = event_waiter.register(
+ node_type=self.type,
+ node_id=node_id,
+ params=parameters,
+ )
+ try:
+ event_data = await waiter.future
+ except Exception as e:
+ return self._wrap_error(start_time=start_time, error=str(e))
+ return self._wrap_success(start_time=start_time, result=event_data)
+
+ # Polling mode: one iteration (deployment mode drives loops).
+ state: Dict[str, Any] = {}
+ result = await self.poll_once(context, params_obj, state) # type: ignore[arg-type]
+ if result is None:
+ return self._wrap_success(start_time=start_time, result={"no_event": True})
+ return self._wrap_success(start_time=start_time, result=result)
diff --git a/server/tests/test_plugin_contract.py b/server/tests/test_plugin_contract.py
new file mode 100644
index 00000000..c8f608b0
--- /dev/null
+++ b/server/tests/test_plugin_contract.py
@@ -0,0 +1,149 @@
+"""Wave 11 — plugin contract invariants.
+
+Enforces every :class:`BaseNode` subclass honours the declared shape
+before it ships. Mirrors the 108-invariant suite in ``test_node_spec.py``
+but for the class-based plugin path (11.B onwards).
+
+These run even when no plugins exist yet (emptiness ⇒ pass). As 11.B
+adds plugins, they automatically participate.
+"""
+
+from __future__ import annotations
+
+from typing import get_type_hints
+
+import pytest
+from pydantic import BaseModel
+
+
+def _all_plugin_classes():
+ # Import populates the plugin-class registry at module import time.
+ import nodes # noqa: F401 (populate registry)
+ from services.node_registry import registered_node_classes
+
+ return list(registered_node_classes().values())
+
+
+class TestBaseNodeDeclaration:
+ """Every subclass must declare the minimum viable fields."""
+
+ def test_non_empty_type(self):
+ for cls in _all_plugin_classes():
+ assert cls.type, f"{cls.__qualname__} missing required class attr `type`"
+
+ def test_non_empty_display_name(self):
+ for cls in _all_plugin_classes():
+ assert cls.display_name, f"{cls.__qualname__} missing `display_name`"
+
+ def test_non_empty_group(self):
+ for cls in _all_plugin_classes():
+ assert cls.group, f"{cls.__qualname__} missing `group`"
+
+ def test_version_is_positive_int(self):
+ for cls in _all_plugin_classes():
+ assert isinstance(cls.version, int) and cls.version >= 1, (
+ f"{cls.__qualname__} version must be a positive int"
+ )
+
+
+class TestParamsAndOutput:
+ """Params + Output must be Pydantic models."""
+
+ def test_params_is_basemodel(self):
+ for cls in _all_plugin_classes():
+ assert issubclass(cls.Params, BaseModel), (
+ f"{cls.__qualname__}.Params must be a Pydantic BaseModel"
+ )
+
+ def test_output_is_basemodel(self):
+ for cls in _all_plugin_classes():
+ assert issubclass(cls.Output, BaseModel), (
+ f"{cls.__qualname__}.Output must be a Pydantic BaseModel"
+ )
+
+
+class TestCredentials:
+ """Every declared credential must resolve to a registered class."""
+
+ def test_credentials_are_registered(self):
+ from services.plugin.credential import CREDENTIAL_REGISTRY, Credential
+
+ for cls in _all_plugin_classes():
+ for cred in cls.credentials:
+ assert issubclass(cred, Credential), (
+ f"{cls.__qualname__}.credentials must be Credential subclasses"
+ )
+ assert cred.id in CREDENTIAL_REGISTRY, (
+ f"{cls.__qualname__} references unregistered credential '{cred.id}'"
+ )
+
+
+class TestOperations:
+ """At least one op; names unique; routing requires credentials."""
+
+ def test_at_least_one_operation(self):
+ from services.plugin.base import _EmptyOutput
+
+ for cls in _all_plugin_classes():
+ # Pure-display plugins (no handler) are allowed — skip those.
+ if cls.Params.__name__ == "_EmptyParams" and cls.Output is _EmptyOutput:
+ continue
+ assert cls._operations, (
+ f"{cls.__qualname__} must declare at least one @Operation"
+ )
+
+ def test_operation_names_unique(self):
+ for cls in _all_plugin_classes():
+ names = [spec.name for spec in cls._operations.values()]
+ assert len(names) == len(set(names)), (
+ f"{cls.__qualname__} has duplicate operation names: {names}"
+ )
+
+ def test_routing_requires_credentials(self):
+ for cls in _all_plugin_classes():
+ for spec in cls._operations.values():
+ if spec.routing is not None:
+ assert cls.credentials, (
+ f"{cls.__qualname__}.{spec.name} uses routing but no "
+ f"credentials declared"
+ )
+
+
+class TestScalingKnobs:
+ """Temporal knobs must have sane values."""
+
+ def test_task_queue_declared(self):
+ from services.plugin.scaling import TaskQueue
+
+ for cls in _all_plugin_classes():
+ assert cls.task_queue in TaskQueue.ALL, (
+ f"{cls.__qualname__}.task_queue={cls.task_queue!r} "
+ f"not in TaskQueue.ALL"
+ )
+
+ def test_retry_policy_type(self):
+ from services.plugin.scaling import RetryPolicy
+
+ for cls in _all_plugin_classes():
+ assert isinstance(cls.retry_policy, RetryPolicy), (
+ f"{cls.__qualname__}.retry_policy must be a RetryPolicy"
+ )
+
+
+class TestToolSchemaGeneration:
+ """ToolNode.Params must produce LLM-compatible JSON schema."""
+
+ def test_tool_schema_has_no_refs(self):
+ from services.plugin.tool import ToolNode
+
+ for cls in _all_plugin_classes():
+ if not issubclass(cls, ToolNode):
+ continue
+ schema = cls.as_tool_schema()
+ params = schema["parameters"]
+ assert "$defs" not in params, (
+ f"{cls.__qualname__} tool schema contains $defs — LLM "
+ "function-calling rejects $ref"
+ )
+ assert "definitions" not in params
+ assert schema.get("name") == cls.type