Skip to content

Self-improving AI Employees for everyone

docs(plugins): self-contained plugin folder pattern + telegram reference

trohitgf4e08c9c419d
diff --git a/CLAUDE.md b/CLAUDE.md
index d765ffd0..4a647e6f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -12,9 +12,9 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Frontend Architecture](./docs-internal/frontend_architecture.md)** | Current frontend stack (React 19 + Vite + Tailwind v4 + shadcn/ui + Radix + RHF/zod + TanStack Query + Zustand). Tokens, primitives, forms, credentials exemplar, ownership boundary, `uiHints` catalogue. |
| **[UI Migration Plan](./docs-internal/ui_migration_plan.md)** | antd → shadcn/ui migration plan + completion log. Waves 1–10 done. Full frontend is schema-driven (backend SSOT); remaining DIY widget registry (ex-Phase 6) is the one deferred item. |
| **[Schema Source of Truth RFC](./docs-internal/schema_source_of_truth_rfc.md)** | Backend is SSOT for node schemas, visual metadata, handlers, palette metadata, icons. Plugin pattern: one `BaseNode` subclass in `server/nodes/<group>/<name>.py`. Wire format: `asset:<key>` / `<lib>:<brand>` / URL / emoji. Endpoint: `/api/schemas/nodes/{type}/spec.json`. 124 pytest invariants lock the contract. |
-| **[Plugin System (Wave 11)](./docs-internal/plugin_system.md)** | Class-based plugin-first architecture. `BaseNode` / `ActionNode` / `TriggerNode` / `ToolNode` + `@Operation` decorator. Pydantic `Params`/`Output`. Declarative `Routing` DSL + `Connection` facade (Nango pattern). 18 `Credential` subclasses live in each node folder's `_credentials.py` (or inline for single-use). `TaskQueue` constants route to Temporal worker pools. 111 plugins live across 9 queues; handler bodies fully inlined (`services/handlers/` shrank 12.8K → 1.1K LOC across 16 → 4 files; only cross-cutting orchestration remains: `tools.py` AI-tool dispatch + agent delegation, `google_auth.py`, `triggers.py`). |
-| **[Nodes Cookbook](./server/nodes/README.md)** | 5-minute recipe + folder map + shared helpers (`_base.py` / `_inline.py` per domain) + shared credentials + contract invariants + common pitfalls. Lives next to the plugin files. |
-| **[Node Creation Guide](./docs-internal/node_creation.md)** | Canonical plugin recipe — one Python file, zero frontend edits. Subclass `ActionNode`/`TriggerNode`/`ToolNode`, declare metadata + `Params` + `Output`, decorate op methods with `@Operation`. Auto-registers via `BaseNode.__init_subclass__`. |
+| **[Plugin System (Wave 11)](./docs-internal/plugin_system.md)** | Class-based plugin-first architecture. `BaseNode` / `ActionNode` / `TriggerNode` / `ToolNode` + `@Operation` decorator. Pydantic `Params`/`Output`. Declarative `Routing` DSL + `Connection` facade (Nango pattern). 18 `Credential` subclasses live in each node folder's `_credentials.py` (or inline for single-use). `TaskQueue` constants route to Temporal worker pools. 111 plugins live across 9 queues; handler bodies fully inlined (`services/handlers/` shrank 12.8K → 1.1K LOC across 16 → 4 files; only cross-cutting orchestration remains: `tools.py` AI-tool dispatch + agent delegation, `google_auth.py`, `triggers.py`). **Wave 11.H added "self-contained plugin folders"** — five generic registries (`ws_handler_registry`, `event_waiter.{register_filter_builder,register_trigger_precheck}`, `status_broadcaster.register_service_refresh`, `node_output_schemas.register_output_schema`) so rich plugins like telegram own their entire surface area without core-services edits. |
+| **[Nodes Cookbook](./server/nodes/README.md)** | 5-minute recipe + folder map + shared helpers (`_base.py` / `_inline.py` per domain) + shared credentials + **self-contained plugin folder pattern (telegram reference)** + contract invariants + common pitfalls. Lives next to the plugin files. |
+| **[Node Creation Guide](./docs-internal/node_creation.md)** | Canonical plugin recipe — one Python file (default), or a self-contained folder for richer plugins (telegram-style). Zero frontend edits, zero core-services edits. Auto-registers via `BaseNode.__init_subclass__` + the five `register_*` hooks. |
| **[AI Tool Node Guide](./docs-internal/ai_tool_node_creation.md)** | Detailed guide for creating dedicated AI Agent tool nodes (schemas, handlers, toolkits) |
| **[Specialized Agent Guide](./docs-internal/specialized_agent_node_creation.md)** | Guide for creating specialized AI agents (Android, Coding, Web, Task, Social, Travel, Tool, Productivity, Payments, Consumer) with full AI configuration |
| **[Dual-Purpose Tool Guide](./docs-internal/dual_purpose_tool_node_creation.md)** | Guide for nodes that work as both workflow nodes AND AI Agent tools (e.g., whatsappSend) |
@@ -52,6 +52,69 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
**CRITICAL: Always follow these principles when modifying backend execution code:**
+### 0. Adding a new node — the canonical recipe (Wave 11.H)
+
+**One file is the default; a self-contained folder is the next step up.**
+Reference implementation: [`server/nodes/telegram/`](./server/nodes/telegram/).
+
+1. **Default — single file.** `server/nodes/<group>/<name>.py` with one
+ `ActionNode` / `TriggerNode` / `ToolNode` subclass. Declare `type`,
+ `display_name`, `group`, `handles`, `Params`, `Output`, `credentials`,
+ `task_queue`, and `@Operation`-decorated methods. Auto-registers via
+ `BaseNode.__init_subclass__` on import. Zero edits anywhere else.
+ See [server/nodes/README.md](./server/nodes/README.md).
+
+2. **Promote to a self-contained folder** when the plugin owns:
+ - a long-lived stateful object (bot / device / SDK session / subprocess),
+ - credentials-modal WebSocket commands beyond Save / Load / Delete,
+ - trigger pre-execution checks that need plugin-specific state,
+ - a status-refresh callback that runs on WS-client connect.
+
+ Folder shape (telegram is the reference):
+ ```
+ server/nodes/<group>/
+ ├── __init__.py # imports + register_* calls (zero logic)
+ ├── _credentials.py # <Provider>Credential subclass
+ ├── _service.py # singleton/service lifecycle
+ ├── _handlers.py # WS_HANDLERS dict
+ ├── _filters.py # build_<provider>_filter (event_waiter)
+ ├── _refresh.py # refresh_*_status + precheck_*_trigger
+ ├── <provider>_send.py
+ └── <provider>_receive.py
+ ```
+ Underscore-prefixed files are package-private (the node walker skips
+ them). The package `__init__.py` is the single wiring point.
+
+3. **Five generic registries** the package self-registers into. Nothing
+ outside the plugin folder hardcodes the plugin's name:
+
+ | Concern | Register call | Backed by |
+ |---|---|---|
+ | Credentials-modal WebSocket commands | `services.ws_handler_registry.register_ws_handlers({type: handler})` | central `_resolve_handler()` in `routers/websocket.py` |
+ | Trigger event-filter builder | `services.event_waiter.register_filter_builder(node_type, fn)` | `event_waiter.FILTER_BUILDERS` |
+ | Trigger pre-execution check | `services.event_waiter.register_trigger_precheck(node_type, async_fn)` | generic `services/handlers/triggers.py` runs `run_trigger_precheck` before entering the wait loop |
+ | Service-status refresh on WS connect | `services.status_broadcaster.register_service_refresh(async_callback)` | `_refresh_all_services` TaskGroup |
+ | Output schema | `services.node_output_schemas.register_output_schema(node_type, ModelClass)` | central `NODE_OUTPUT_SCHEMAS` |
+
+ All five are idempotent (same callable / class for the same key is a
+ no-op; conflicts raise `ValueError`).
+
+4. **Wire format is the contract — not module paths.** The frontend
+ identifies plugin commands by WebSocket message-type strings
+ (`telegram_connect`, `telegram_status`, …). Moving handler bodies
+ between Python files is invisible to the frontend so long as the
+ registered keys stay the same. The 754-line telegram extraction
+ from `services/telegram_service.py` (Wave 11.H) changed zero
+ frontend code.
+
+5. **What NOT to do**: don't import the plugin folder from `routers/`,
+ `services/`, or another `nodes/` subfolder. Don't edit
+ `event_waiter.py` / `status_broadcaster.py` / `routers/websocket.py`
+ to add a new plugin's handler/filter/refresh — register from the
+ plugin's `__init__.py` instead.
+
+Full reference: [docs-internal/plugin_system.md → "Self-contained plugin folders"](./docs-internal/plugin_system.md#self-contained-plugin-folders).
+
### 1. Use Existing Patterns - No Tribal Code
- **Never add ad-hoc workarounds** - Use the established patterns documented in DESIGN.md
- **Conductor Decide Pattern** - All orchestration goes through `_workflow_decide()` loop
@@ -85,7 +148,7 @@ server/services/
├── nodejs_client.py # HTTP client for Node.js code executor
├── pricing.py # LLM and API cost calculation (loads config/pricing.json)
├── markdown_formatter.py # GFM markdown to platform-specific formatting (Telegram HTML, WhatsApp, plain)
-├── telegram_service.py # TelegramService with python-telegram-bot long-polling
+├── ws_handler_registry.py # Plugin-owned WS commands self-register here (Wave 11.H)
├── browser_service.py # BrowserService singleton wrapping agent-browser CLI
├── himalaya_service.py # HimalayaService CLI wrapper for IMAP/SMTP (any email provider)
├── email_service.py # EmailService orchestrator (credential resolution, provider presets)
@@ -1077,18 +1140,24 @@ TWITTER_CLIENT_SECRET=your_client_secret
# TWITTER_REDIRECT_URI is derived at runtime from request context (no env var needed)
```
-### Telegram Nodes (2 nodes)
-Telegram bot integration using `python-telegram-bot` SDK with long-polling for incoming messages.
+### Telegram Nodes (2 nodes) — reference for self-contained plugin folders
+Telegram bot integration using `python-telegram-bot` SDK with long-polling for incoming messages. **All telegram code lives in `server/nodes/telegram/`** — the plugin folder owns its service, WebSocket handlers, event filter, lifecycle hooks, and credentials. Read this folder first before adding any plugin that needs more than a single `BaseNode` subclass; see [docs-internal/plugin_system.md → "Self-contained plugin folders"](./docs-internal/plugin_system.md#self-contained-plugin-folders).
- **telegramSend**: **Dual-purpose node** - Send text, photo, document, location, or contact messages via Telegram bot. Works as workflow node OR AI Agent tool. Group: `['social', 'tool']`. Recipient types: Self (bot owner), User/Chat ID, Group. Parameters: recipient_type, chat_id, message_type, text, media_url, caption, parse_mode (Auto/HTML/Markdown/MarkdownV2/None), silent, reply_to_message_id. **Auto parse_mode** (default, recommended): converts GFM markdown to Telegram HTML via `markdown_formatter.to_telegram_html()`. MarkdownV2/Markdown text auto-escaped via `_escape_text()`; falls back to plain text on `BadRequest`. "Self" restores `owner_chat_id` from credentials DB if not in memory.
-- **telegramReceive**: Event-driven trigger that waits for incoming Telegram messages. Group: `['social', 'trigger']`. Uses `senderFilter` dropdown: All Messages, From Self (Bot Owner) (zero-config), Private/Group/Supergroup/Channel Only, Specific Chat, Specific User, Keywords. Content type filter and ignore bots option. "From Self" uses lazy `_get_owner_chat_id()` lookup at match time. Auto-reconnects on server restart via `StatusBroadcaster._refresh_telegram_status()`.
+- **telegramReceive**: Event-driven trigger that waits for incoming Telegram messages. Group: `['social', 'trigger']`. Uses `senderFilter` dropdown: All Messages, From Self (Bot Owner) (zero-config), Private/Group/Supergroup/Channel Only, Specific Chat, Specific User, Keywords. Content type filter and ignore bots option. "From Self" uses lazy `_get_owner_chat_id()` lookup at match time. Auto-reconnects on server restart via the registered service-refresh callback.
-**Key Files:**
+**Key Files** (all under `server/nodes/telegram/`):
| File | Description |
|------|-------------|
-| `server/services/telegram_service.py` | TelegramService with long-polling message handler |
-| `server/services/handlers/telegram.py` | Node handlers for send and receive |
-| `client/src/components/CredentialsModal.tsx` | Telegram bot token panel |
+| `__init__.py` | Imports + 6 self-registration calls — the only wiring needed (zero logic). |
+| `_credentials.py` | `TelegramCredential(ApiKeyCredential)` — bot token + `telegram_owner_chat_id` extra field. |
+| `_service.py` | `TelegramService` singleton: connect/disconnect/send/poll lifecycle, idempotent connect, parse-mode fallback helper. |
+| `_handlers.py` | 7 WebSocket handlers (`telegram_connect` / `_disconnect` / `_status` / `_send` / `_reconnect` / `_get_me` / `_get_chat`) + `WS_HANDLERS` dict registered into `services.ws_handler_registry`. |
+| `_filters.py` | `build_telegram_filter` — registered into `event_waiter.FILTER_BUILDERS`. |
+| `_refresh.py` | `refresh_telegram_status` (registered into `status_broadcaster._SERVICE_REFRESH_CALLBACKS`) + `precheck_telegram_trigger` (registered into `event_waiter._TRIGGER_PRECHECKS`). |
+| `telegram_send.py` | `TelegramSendNode(ActionNode)` + `TelegramSendOutput` — the workflow + AI-tool plugin. |
+| `telegram_receive.py` | `TelegramReceiveNode(TriggerNode)` + `TelegramReceiveOutput` — the trigger plugin (declares `event_type = "telegram_message_received"`). |
+| `client/src/components/CredentialsModal.tsx` | Telegram bot token panel (frontend; identifies commands by WebSocket message-type strings, not Python paths). |
**Authentication:** Bot token from @BotFather on Telegram. Stored via `auth_service.store_api_key('telegram_bot_token', token, models=[])`. Owner auto-captured on first private message, persisted as `telegram_owner_chat_id`. Credentials panel: Save (store only), Connect (store + connect), Reconnect. All credential access uses `from core.container import container; container.auth_service()` (NOT `from services.auth import get_auth_service`).
diff --git a/docs-internal/node_creation.md b/docs-internal/node_creation.md
index 7c5e4ce2..62de8e6e 100644
--- a/docs-internal/node_creation.md
+++ b/docs-internal/node_creation.md
@@ -4,12 +4,15 @@
This file is a redirect. New nodes use the class-based `ActionNode` / `TriggerNode` / `ToolNode` hierarchy under `server/nodes/<group>/<name>.py`. Each subclass declares `type`, metadata, `Params` + `Output` Pydantic models, `credentials`, `handles`, `task_queue`, and operations on the class object; `BaseNode.__init_subclass__` writes to the four legacy registries (`NODE_METADATA`, `_DIRECT_MODELS`, `NODE_OUTPUT_SCHEMAS`, `_HANDLER_REGISTRY`) plus the class registry on import. No frontend edits.
+For richer plugins that own a long-lived service, credentials-modal WebSocket commands, trigger pre-checks, or service-status refresh hooks, see the **self-contained plugin folder** pattern documented in [`plugin_system.md`](./plugin_system.md#self-contained-plugin-folders) and demonstrated in [`server/nodes/telegram/`](../server/nodes/telegram/). All cross-cutting concerns plug into generic registries (`register_ws_handlers`, `register_filter_builder`, `register_trigger_precheck`, `register_service_refresh`, `register_output_schema`) — nothing outside the plugin folder hardcodes the plugin's name.
+
## Where to look
| Need | Doc |
|------|-----|
| 5-minute recipe, folder map, shared helpers | [server/nodes/README.md](../server/nodes/README.md) |
| Full plugin pattern, `@Operation`, declarative `Routing`, `Connection` facade, Temporal task queues, credential classes | [plugin_system.md](./plugin_system.md) |
+| Self-contained plugin folders (rich plugins like telegram with their own service, WS handlers, pre-checks) | [plugin_system.md → "Self-contained plugin folders"](./plugin_system.md#self-contained-plugin-folders) |
| Backend-as-SSOT design (NodeSpec, icons, output schemas) | [schema_source_of_truth_rfc.md](./schema_source_of_truth_rfc.md) |
| JSON workflow format, edge handle conventions | [workflow-schema.md](./workflow-schema.md) |
| AI-tool nodes (dual-purpose or dedicated) | [ai_tool_node_creation.md](./ai_tool_node_creation.md), [dual_purpose_tool_node_creation.md](./dual_purpose_tool_node_creation.md) |
@@ -20,5 +23,6 @@ This file is a redirect. New nodes use the class-based `ActionNode` / `TriggerNo
- 111 plugins across 9 Temporal worker pools (`rest-api`, `ai-heavy`, `code-exec`, `triggers-poll`, `triggers-event`, `android`, `browser`, `messaging`, `machina-default`).
- Per-domain `_credentials.py` in each node folder (18 `Credential` subclasses; central `server/credentials/` was deleted in Wave 11.E.1).
- `services/handlers/` shrank to 4 files / 1.1K LOC — only cross-cutting orchestration remains (`tools.py` AI-tool dispatch + agent delegation, `google_auth.py`, `triggers.py`).
+- Five generic registries replace per-plugin hardcoding in core services: `services.ws_handler_registry`, `services.event_waiter.{FILTER_BUILDERS, _TRIGGER_PRECHECKS}`, `services.status_broadcaster._SERVICE_REFRESH_CALLBACKS`, `services.node_output_schemas`. Plugin packages self-register from their `__init__.py`.
- Agent delegation invokes child agents through `BaseNode.execute()` via the node registry.
- 124 pytest invariants in `tests/test_node_spec.py` lock the contract.
diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.md
index 90c57530..bbbfb934 100644
--- a/docs-internal/plugin_system.md
+++ b/docs-internal/plugin_system.md
@@ -415,6 +415,139 @@ hand-edit of `event_waiter.py` required.
Hardcoded entries still win when present (authoritative), so plugin
upgrades never silently replace hand-tuned filter behaviour.
+## Self-contained plugin folders
+
+Some plugins are richer than a single `BaseNode` subclass — they own a
+long-lived service (a bot connection, a WebSocket bridge, an SDK
+session), their own credentials-modal WebSocket commands, custom
+event filtering, lifecycle hooks. Telegram is the reference shape.
+
+**Principle**: every cross-cutting concern resolves to a generic
+registry that the consumer (router, broadcaster, event waiter, schema
+emitter) reads at dispatch time. Plugin packages **register
+themselves** into those registries from their package `__init__.py`.
+**Nothing outside the plugin folder hardcodes the plugin's name.**
+
+### Folder shape (Telegram reference)
+
+```
+server/nodes/telegram/
+├── __init__.py # imports + 6 register_* calls (no logic)
+├── _credentials.py # TelegramCredential (ApiKeyCredential)
+├── _service.py # TelegramService singleton (bot lifecycle)
+├── _handlers.py # WebSocket handlers + WS_HANDLERS dict
+├── _filters.py # build_telegram_filter (event_waiter filter)
+├── _refresh.py # refresh_telegram_status + precheck_telegram_trigger
+├── telegram_send.py # ActionNode + AI tool
+└── telegram_receive.py # TriggerNode
+```
+
+Underscore-prefixed files are package-private; the `nodes` walker
+skips them. The two non-underscore files are the plugin classes (one
+per node type) — same pattern as every other folder.
+
+### Five cross-cutting registries
+
+| Concern | Registry module | Register from plugin via |
+|---|---|---|
+| Credentials-modal WebSocket commands (Connect / Disconnect / Send / Status / etc.) | `services.ws_handler_registry` | `register_ws_handlers({type: handler, ...})` |
+| Trigger event-filter builder | `services.event_waiter` | `register_filter_builder(node_type, fn)` |
+| Trigger pre-execution check (e.g. "bot not connected") | `services.event_waiter` | `register_trigger_precheck(node_type, fn)` |
+| Service-status refresh on WebSocket connect | `services.status_broadcaster` | `register_service_refresh(callback)` |
+| Per-node output schema (when not auto-derivable) | `services.node_output_schemas` | `register_output_schema(node_type, ModelClass)` |
+
+All five accept idempotent re-imports (same callable / class for the
+same key is a no-op; conflicts raise `ValueError`).
+
+### Telegram `__init__.py` (canonical wiring)
+
+```python
+# server/nodes/telegram/__init__.py
+from services.event_waiter import register_filter_builder, register_trigger_precheck
+from services.node_output_schemas import register_output_schema
+from services.status_broadcaster import register_service_refresh
+from services.ws_handler_registry import register_ws_handlers
+
+from ._credentials import TelegramCredential
+from ._filters import build_telegram_filter
+from ._handlers import WS_HANDLERS
+from ._refresh import precheck_telegram_trigger, refresh_telegram_status
+from ._service import TelegramService, get_telegram_service
+
+# Plugin classes (importing them runs __init_subclass__ for the node registry)
+from .telegram_receive import TelegramReceiveNode, TelegramReceiveOutput
+from .telegram_send import TelegramSendNode, TelegramSendOutput
+
+# --- self-registration on import -------------------------------------------
+register_ws_handlers(WS_HANDLERS)
+register_filter_builder("telegramReceive", build_telegram_filter)
+register_trigger_precheck("telegramReceive", precheck_telegram_trigger)
+register_service_refresh(refresh_telegram_status)
+register_output_schema("telegramReceive", TelegramReceiveOutput)
+register_output_schema("telegramSend", TelegramSendOutput)
+```
+
+That's the entire wiring. Adding telegram-style cross-cutting code to
+a new plugin folder takes one register call per concern; the consumer
+never learns the plugin's name.
+
+### How consumers consult the registries
+
+Each consumer hits its registry at dispatch time, not at module load,
+so plugins registered later still work:
+
+```python
+# routers/websocket.py — central WS dispatcher
+from services.ws_handler_registry import get_ws_handlers
+
+def _resolve_handler(msg_type):
+ return MESSAGE_HANDLERS.get(msg_type) or get_ws_handlers().get(msg_type)
+
+# services/handlers/triggers.py — generic trigger handler
+precheck_error = await event_waiter.run_trigger_precheck(node_type, parameters)
+if precheck_error:
+ return error_envelope(precheck_error)
+waiter = await event_waiter.register(node_type, node_id, parameters)
+
+# services/status_broadcaster.py — WS-connect refresh
+async with asyncio.TaskGroup() as tg:
+ tg.create_task(self._refresh_whatsapp_status()) # legacy hardcoded
+ # ... future migrations move into the registry too:
+ for callback in _SERVICE_REFRESH_CALLBACKS:
+ tg.create_task(callback(self))
+```
+
+### When does a plugin need the full self-contained shape?
+
+Most plugins are a single `BaseNode` subclass — that's the right
+default. Promote to the self-contained folder shape only when the
+plugin owns one of:
+
+- A long-lived stateful object (bot / device / session / subprocess).
+- Credentials-modal lifecycle commands beyond the standard
+ Save / Load / Delete (e.g. Connect / Disconnect).
+- Trigger pre-checks that need plugin-specific service state.
+- A status refresh that runs on WebSocket connect.
+- A duplicate `Output` Pydantic class that the central
+ `node_output_schemas.NODE_OUTPUT_SCHEMAS` would otherwise pin.
+
+If none of those apply: a single `<name>.py` in the right folder is
+the whole node. Don't create `_service.py` / `_handlers.py` / etc.
+just because telegram has them.
+
+### Wire format is the contract — not module paths
+
+The frontend identifies plugin commands by **WebSocket message type**
+strings (`telegram_connect`, `telegram_status`, …). Moving the handler
+implementation between Python files is invisible to the frontend so
+long as the registered keys stay the same. The
+`credential_providers.json` declarative config and the
+`credentials/providers.tsx` registry are likewise stable across
+backend reorganisations.
+
+This is why the telegram refactor changed zero frontend code despite
+moving 754 lines out of `services/telegram_service.py`.
+
## Folder layout
```
@@ -592,6 +725,26 @@ every CI run. Examples:
LOC.
- Wave 11.G — Nodes cookbook (`server/nodes/README.md`) + CLAUDE.md
plugin section + this file refreshed to match shipped state.
+- Wave 11.H — Self-contained plugin folders. Five new generic
+ registries replace per-plugin hardcoding in core services:
+ `services.ws_handler_registry` (WebSocket commands),
+ `event_waiter.register_filter_builder` (event filters),
+ `event_waiter.register_trigger_precheck` (trigger pre-execution
+ checks), `status_broadcaster.register_service_refresh` (WS-connect
+ refresh callbacks), `node_output_schemas.register_output_schema`
+ (output schemas). Telegram is the reference implementation:
+ ~870 lines of telegram-specific code moved out of
+ `services/telegram_service.py` (deleted), `routers/websocket.py`
+ (7 inline handlers removed), `services/event_waiter.py`
+ (`build_telegram_filter` + hardcoded registry entry removed),
+ `services/status_broadcaster.py` (`_refresh_telegram_status`
+ removed), `services/handlers/triggers.py` (hardcoded
+ `if node_type == 'telegramReceive'` branch removed),
+ `services/node_output_schemas.py` (duplicate
+ `TelegramReceiveOutput` class removed) — all relocated to
+ `nodes/telegram/`. Wire-format unchanged → zero frontend
+ changes. Frontend identifies plugin commands by WebSocket message
+ type strings, not Python module paths.
`services/handlers/` is now **4 files / 1,112 LOC** (down from 16
files / 12,800 LOC):
diff --git a/server/nodes/README.md b/server/nodes/README.md
index a98d264e..2a9d59be 100644
--- a/server/nodes/README.md
+++ b/server/nodes/README.md
@@ -210,6 +210,75 @@ Run: `pytest server/tests/test_plugin_contract.py -q`.
---
+## Self-contained plugin folders (richer plugins)
+
+Most plugins are a single file in the right folder — that's the
+default. But some own a long-lived service (bot connection, SDK
+session, subprocess), credentials-modal Connect/Disconnect commands,
+trigger pre-checks, etc. Those graduate to a **self-contained folder
+shape** so nothing telegram-specific (or whatsapp-specific, twitter-
+specific, …) lives outside that folder.
+
+**Reference: `server/nodes/telegram/`.** Read it first before adding a
+similar plugin.
+
+```
+server/nodes/telegram/
+├── __init__.py # imports + 6 register_* calls (zero logic)
+├── _credentials.py # TelegramCredential subclass
+├── _service.py # singleton bot lifecycle (connect / send / poll)
+├── _handlers.py # WS_HANDLERS dict (telegram_connect, …)
+├── _filters.py # build_telegram_filter (event_waiter filter)
+├── _refresh.py # WS-connect refresh + trigger precheck
+├── telegram_send.py # ActionNode + AI tool
+└── telegram_receive.py # TriggerNode
+```
+
+### Five generic registries to plug into
+
+Telegram's `__init__.py` is the canonical wiring example. Adding any
+of these concerns to your plugin is one `register_*` call from your
+package's `__init__.py` — the consumer never imports your folder.
+
+| Concern | Where to register | What it does |
+|---|---|---|
+| Credentials-modal WebSocket commands | `services.ws_handler_registry.register_ws_handlers({"<type>": handler})` | Adds `<type>` to the central WS dispatcher (no router edits) |
+| Event-trigger filter | `services.event_waiter.register_filter_builder(node_type, fn)` | Plugs into `FILTER_BUILDERS` for `event_waiter.build_filter()` |
+| Trigger pre-execution check | `services.event_waiter.register_trigger_precheck(node_type, async_fn)` | Generic `triggers.py` handler runs `run_trigger_precheck` before entering the wait loop |
+| Service-status refresh on WS connect | `services.status_broadcaster.register_service_refresh(async_callback)` | Callback runs once per `_refresh_all_services` cycle |
+| Output schema | `services.node_output_schemas.register_output_schema(node_type, ModelClass)` | Avoids declaring a duplicate `Output` class in the central schema file |
+
+All five are idempotent (same callable / class for the same key is a
+no-op; conflicts raise `ValueError`).
+
+### When NOT to use this shape
+
+Don't create `_service.py` / `_handlers.py` siblings unless the plugin
+genuinely owns:
+
+- A long-lived stateful object (bot / device / session / subprocess).
+- Credentials-modal lifecycle commands beyond the standard
+ Save / Load / Delete.
+- Trigger pre-checks that depend on plugin-specific service state.
+- A status refresh that runs on WebSocket connect.
+
+A single search node, an HTTP-only REST plugin, a code executor — all
+of those stay one file. Adding the folder ceremony for them is just
+overhead.
+
+### Wire format is stable across moves
+
+Frontend identifies plugin commands by **WebSocket message type
+strings** (`telegram_connect`, `telegram_status`, …) — never by Python
+module paths. As long as your `WS_HANDLERS` keys stay the same, you
+can rearrange your `nodes/<group>/` folder freely with zero frontend
+changes. The telegram refactor moved 754 lines without touching
+`client/`.
+
+Full reference: [docs-internal/plugin_system.md → "Self-contained plugin folders"](../../docs-internal/plugin_system.md#self-contained-plugin-folders).
+
+---
+
## Common pitfalls
- **Don't edit `server/nodes/__init__.py`** — it's a pure auto-discovery