Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
docs(events): Wave 12 framework + Stripe plugin reference
trohitg2c5826a6e7ce
diff --git a/CLAUDE.md b/CLAUDE.mdindex 2e49267c..c19716cd 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -25,6 +25,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[Pricing Service](./docs-internal/pricing_service.md)** | Centralized cost tracking for LLM tokens and API services (Twitter, Google Maps) with HTTPX event hooks || **[Proxy Service](./docs-internal/proxy_service.md)** | Residential proxy provider management with template-based URL formatting, health scoring, and transparent HTTP node injection || **[Email Service](./docs-internal/email_service.md)** | IMAP/SMTP integration via Himalaya CLI with EmailService orchestrator, provider presets, custom credential fallback, and polling triggers |+| **[Stripe Service](./docs-internal/stripe_service.md)** | Stripe CLI integration via the Wave 12 event framework — `stripeAction` (CLI pass-through) + `stripeReceive` (signed-webhook trigger). Reference plugin for `services/events/` (DaemonEventSource, WebhookSource, WebhookTriggerNode, signature verifiers, lifecycle helpers) || **[CI/CD Pipeline](./docs-internal/ci_cd.md)** | GitHub Actions workflows, predeploy validation, release publishing, and composite setup action || **[Workflow Schema](./docs-internal/workflow-schema.md)** | JSON schema for workflows, edge handle conventions, config node architecture || **[Execution Engine Design](./docs-internal/DESIGN.md)** | Architecture patterns, design standards, and implementation details for the workflow execution engine |diff --git a/docs-internal/node_creation.md b/docs-internal/node_creation.mdindex 62de8e6e..dc061cb1 100644--- a/docs-internal/node_creation.md+++ b/docs-internal/node_creation.md@@ -1,28 +1,181 @@# Node Creation Guide-> **Canonical recipe:** [Plugin System (Wave 11)](./plugin_system.md) and the inline [Nodes Cookbook](../server/nodes/README.md) next to the plugin files.+> **Companion docs:** [Plugin System](./plugin_system.md) (Wave 11 architecture + Wave 12 event framework) and the inline [Nodes Cookbook](../server/nodes/README.md) next to the plugin files.-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.+This guide is a fast index for adding a new node to MachinaOs. The+deep technical details live in [`plugin_system.md`](./plugin_system.md);+this file picks the right entry point based on what you're adding.-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.+## Decision tree-## Where to look+| You're adding… | Read this | Boilerplate |+|---|---|---|+| A simple action node (one HTTP call, no state) | [Quick start](./plugin_system.md#quick-start--adding-a-new-node) | one `<name>.py` file under `server/nodes/<group>/` |+| A dual-purpose node (workflow node + AI tool) | [Dual-Purpose Tool Guide](./dual_purpose_tool_node_creation.md) | one `<name>.py` with `usable_as_tool = True` |+| A specialized AI agent | [Specialized Agent Guide](./specialized_agent_node_creation.md) | one `<name>.py` under `server/nodes/agent/` |+| A standalone AI-tool node (no workflow surface) | [AI Tool Node Guide](./ai_tool_node_creation.md) | one `<name>.py` under `server/nodes/tool/` |+| A node that wraps a CLI tool, supervises a daemon, or receives signed webhooks | [Wave 12 event framework](./plugin_system.md#wave-12--generalized-event-framework-servicesevents) (this section is the most important one) | self-contained folder under `server/nodes/<group>/` using `services.events` base classes |+| A polling-based trigger node | [Wave 12 event framework](./plugin_system.md#wave-12--generalized-event-framework-servicesevents) — subclass `PollingEventSource` | new file or folder; framework owns the loop |+| A long-lived service plugin (bot connection, WebSocket bridge, SDK session) | [Self-contained plugin folders (Wave 11.H)](./plugin_system.md#self-contained-plugin-folders) — telegram is the reference | folder with `_credentials.py` / `_service.py` / `_handlers.py` / `_filters.py` / `_refresh.py` |++## The four node kinds++```+BaseNode (services/plugin/base.py)+├── ActionNode fire-once; returns {success, result} envelope+├── TriggerNode long-lived; event-mode or polling-mode+│ └── WebhookTriggerNode ← Wave 12: signed-webhook trigger backed by a WebhookSource+└── ToolNode AI-invoked; flat return shape+```++Single-file plugins inherit directly from `ActionNode` /+`TriggerNode` / `ToolNode`. Self-contained plugin folders (telegram,+stripe) layer additional bases from `services.events` underneath them.++## Five-minute recipe — single file++For nodes with no state, no daemon, no signed webhooks (the common+case):++```python+# server/nodes/<group>/<name>.py+from pydantic import BaseModel, Field+from services.plugin import (+ ActionNode, ApiKeyCredential, NodeContext, Operation, TaskQueue,+)+++class MyCredential(ApiKeyCredential):+ id = "my_api"+ display_name = "My Service"+ category = "Search"+ key_name = "X-API-Key"+++class MyParams(BaseModel):+ query: str = Field(..., min_length=1)+++class MyOutput(BaseModel):+ results: list+++class MyNode(ActionNode):+ type = "myNode"+ display_name = "My Node"+ icon = "asset:my"+ color = "#abcdef"+ group = ("search", "tool")+ description = "Brief description for palette + AI tool."+ component_kind = "square"+ handles = (+ {"name": "input-main", "kind": "input", "position": "left",+ "label": "Input", "role": "main"},+ {"name": "output-main", "kind": "output", "position": "right",+ "label": "Output", "role": "main"},+ )+ credentials = (MyCredential,)+ task_queue = TaskQueue.REST_API+ usable_as_tool = True+ Params = MyParams+ Output = MyOutput++ @Operation("search")+ async def search(self, ctx: NodeContext, params: MyParams) -> MyOutput:+ async with ctx.connection("my_api") as conn:+ resp = await conn.get(+ "https://api.example.com/search",+ params={"q": params.query},+ )+ return MyOutput(results=resp.json().get("hits", []))+```++That's the entire node. On server restart it auto-registers, the+NodeSpec is emitted at `/api/schemas/nodes/myNode/spec.json`, and it+appears in the Component Palette under the `search` group.++## Five-minute recipe — Wave 12 self-contained folder (signed webhook + CLI)++For nodes that wrap a CLI tool **and** receive signed webhooks+(Stripe, future GitHub-CLI / Cloudflare-Wrangler integrations), use+the [Wave 12 framework](./plugin_system.md#wave-12--generalized-event-framework-servicesevents).+Stripe is the reference implementation+([`server/nodes/stripe/`](../server/nodes/stripe/)). The shape:++```+server/nodes/<provider>/+├── __init__.py # 5 register_* calls (zero logic)+├── _credentials.py # ApiKeyCredential subclass+├── _source.py # DaemonEventSource + WebhookSource subclasses+├── _handlers.py # WS_HANDLERS via make_lifecycle_handlers()+├── <provider>_action.py # ActionNode + AI tool — uses run_cli_command+└── <provider>_receive.py # WebhookTriggerNode subclass+```++The framework absorbs the boilerplate that used to live in each+plugin: subprocess supervision, HMAC signature verification,+lifecycle WebSocket handlers, status-refresh callback, CLI invocation+with credential injection. A new framework plugin lands in+**~150 executable lines**, of which only `build_command` /+`parse_line` / `shape` / per-provider Params/Output schemas are+provider-specific. See:++- [Plugin System → Wave 12 framework](./plugin_system.md#wave-12--generalized-event-framework-servicesevents) — every base class + helper documented with examples.+- [Stripe Service](./stripe_service.md) — the reference implementation walked through file by file.++## What auto-wires (don't write it yourself)++When a plugin file is imported (which the `nodes/__init__.py`+walker does on startup), these registrations happen automatically:++| Mechanism | Where | When |+|---|---|---|+| Node class registration | `_NODE_CLASS_REGISTRY` | `BaseNode.__init_subclass__` on class definition |+| Metadata + Pydantic schemas | `NODE_METADATA`, `NODE_INPUT_MODELS`, `NODE_OUTPUT_SCHEMAS` | same |+| Handler dispatch | `_PLUGIN_HANDLERS` (merged into `NodeExecutor`) | same |+| Credentials | `CREDENTIAL_REGISTRY` | `Credential.__init_subclass__` when `_credentials.py` is imported |+| Trigger registry + filter builders | `event_waiter.TRIGGER_REGISTRY`, `FILTER_BUILDERS` | back-fill from `TriggerNode` subclasses on first lookup |+| Temporal activity wrapper | `cls.as_activity()` | first call; pooled into the worker queue declared by `task_queue` |+| Palette icon + color | `nodes/visuals.json` | central source of truth (frontend resolver reads it) |++What you **do** still write:++- An entry in `server/nodes/visuals.json` for the icon + color+ (unless the node sets them as class attributes, which override).+- An entry in `server/nodes/groups.py` if you introduce a new+ palette group.+- An asset in `client/src/assets/icons/<name>.svg` for `asset:<name>`+ icons.++## Where to look next| 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) |+| 5-minute recipe with shared helpers + common pitfalls | [server/nodes/README.md](../server/nodes/README.md) |+| Full plugin pattern (every class attribute, `@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) |+| Wave 12 event framework (signed webhooks, CLI daemons, polling) | [plugin_system.md → Wave 12](./plugin_system.md#wave-12--generalized-event-framework-servicesevents) |+| Stripe as the Wave 12 reference plugin | [stripe_service.md](./stripe_service.md) || 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) |+| Dual-purpose nodes (workflow node + AI tool) | [dual_purpose_tool_node_creation.md](./dual_purpose_tool_node_creation.md) || Specialized AI agents | [specialized_agent_node_creation.md](./specialized_agent_node_creation.md) |+| Polling triggers + event_waiter mechanics | [event_waiter_system.md](./event_waiter_system.md) |+| Process supervision (used by `DaemonEventSource`) | [server/services/process_service.py](../server/services/process_service.py) — singleton API |++## Wave summary (current state)-## Wave 11 end state+- **Wave 11** — Class-based plugin system. 111 plugins / 9 Temporal+ worker pools / 124 contract invariants. `services/handlers/` shrank+ from 12.8K → 1.1K LOC.+- **Wave 11.H** — Self-contained plugin folders. Five generic+ registries replace per-plugin hardcoding in core. Telegram is the+ reference.+- **Wave 12** — Generalized event framework+ ([`services/events/`](../server/services/events/)). `EventSource`+ hierarchy + CloudEvents-shaped envelope + verifier registry ++ wiring helpers. Stripe is the reference.-- 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.+The end state: every new event-source plugin is **~150 executable+lines** of provider-specific code on top of shared bases, with+**zero edits outside the plugin folder**.diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.mdindex bbbfb934..6090235b 100644--- a/docs-internal/plugin_system.md+++ b/docs-internal/plugin_system.md@@ -732,7 +732,19 @@ every CI run. Examples:`event_waiter.register_trigger_precheck` (trigger pre-executionchecks), `status_broadcaster.register_service_refresh` (WS-connectrefresh callbacks), `node_output_schemas.register_output_schema`- (output schemas). Telegram is the reference implementation:+ (output schemas).+- Wave 12 — Generalized event framework+ ([`services/events/`](../server/services/events/)). Adds+ `WorkflowEvent` (CloudEvents v1.0 envelope, in-house Pydantic),+ `EventSource` hierarchy (`PushEventSource` /+ `PollingEventSource` / `DaemonEventSource` / `WebhookSource` /+ `WebhookTriggerNode`), a verifier registry (Stripe / GitHub /+ Standard Webhooks / generic HMAC), and three wiring helpers+ (`make_lifecycle_handlers`, `make_status_refresh`,+ `run_cli_command`). Future event-source plugins drop to ≈150+ executable lines. Stripe is the reference implementation;+ Phase 2-4 migrate the existing polling and daemon triggers onto+ the framework. 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`@@ -759,3 +771,333 @@ files / 12,800 LOC):Every domain owns its own code under `nodes/<group>/` — plugin file +optional `_base.py` / `_inline.py` / `_credentials.py` siblings. Nohandler shells, no central credential registry, no cross-domain reach.++## Wave 12 — Generalized event framework (`services/events/`)++Wave 11.H proved the self-contained-folder pattern. Wave 12 takes the+next step: stop re-implementing the same event-source plumbing in+every folder. The new package+[`server/services/events/`](../server/services/events/) provides the+shared base classes that every trigger / daemon / signed-webhook+plugin builds on top of.++### Why++Pre-framework, every event-source plugin re-wrote the same boilerplate:++- **Polling loop frame** duplicated verbatim across `gmail_receive`,+ `email_receive`, `twitter_receive` (`sleep → poll → diff baseline →+ dispatch`).+- **Subprocess supervision** had no shared base — telegram (SDK loop),+ whatsapp (Go RPC), stripe (CLI subprocess) each owned their+ singleton.+- **HMAC signature verification** was about to be re-implemented per+ signed-webhook integration (Stripe, GitHub, Slack, Standard Webhooks+ / Svix providers).+- **Lifecycle WebSocket handlers** (connect / disconnect / reconnect /+ status) were ~25 LOC of identical boilerplate per plugin.+- **Status-refresh callback** (auto-reconnect on WS-client connect) was+ another ~12 LOC of identical boilerplate per plugin.+- **CLI invocation** (find binary on PATH, inject API key, subprocess+ with timeout, parse JSON, uniform error envelope) was a copy-paste+ target.++Wave 12 absorbs all of this into framework code. New event-source+plugins drop to **~150 executable lines** (vs ~600+ pre-framework).++### Public surface++```python+from services.events import (+ # Envelope+ WorkflowEvent, # CloudEvents v1.0 model (in-house)++ # EventSource hierarchy+ EventSource, # ABC: start / stop / status / emit+ PushEventSource, # external code calls receive()+ PollingEventSource, # poll_once() at intervals+ DaemonEventSource, # ProcessService-supervised subprocess+ WebhookSource, # HTTP POST to /webhook/{path}+ BaseTriggerParams, # Pydantic base for trigger Params+ WebhookTriggerNode, # TriggerNode bound to a WebhookSource++ # Webhook signature verifiers+ WebhookVerifier, # ABC+ StripeVerifier, # t=,v1=,HMAC-SHA256+ GitHubVerifier, # X-Hub-Signature-256+ StandardWebhooksVerifier, # Svix scheme (id.timestamp.body)+ HmacVerifier, # Generic single-header HMAC fallback++ # Wiring helpers+ register_webhook_source, # WEBHOOK_SOURCES[path] = source+ make_lifecycle_handlers, # connect/disconnect/reconnect/status WS dict+ make_status_refresh, # register_service_refresh callback factory+ run_cli_command, # subprocess + credential + JSON parse+)+```++### Source taxonomy++Modality-axis hierarchy aligned with Apache Camel EIP and n8n trigger+modes:++```+EventSource (abstract)+├── PushEventSource events arrive via external write (HTTP, RPC, SSE)+│ └── WebhookSource HTTP POST to /webhook/{path}+├── PollingEventSource sleep → poll_once → emit; framework owns the loop+└── DaemonEventSource long-lived subprocess via ProcessService;+ tail stdout/stderr; parse_line() → events+```++Cron / scheduled events stay on APScheduler — they don't need this+base. Internal in-process events go through `event_waiter.dispatch`+directly.++### Unified envelope (`WorkflowEvent`)++Mirrors CloudEvents v1.0 verbatim+([spec](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md))+plus three MachinaOs routing extras (`workflow_id`,+`trigger_node_id`, `correlation_id`). Field set:+`specversion / id / source / type / time / subject / datacontenttype /+dataschema / data` plus the extras.++```python+WorkflowEvent(+ id=payload["id"], # provider's event id (replay safety)+ source="stripe://acct_test", # URI: scheme://provider/account+ type="stripe.charge.succeeded", # reverse-DNS event type+ time=datetime.fromtimestamp(payload["created"], tz=timezone.utc),+ subject=payload.get("type"),+ data=payload,+)+```++`WorkflowEvent.matches_type(pattern)` does CloudEvents-style glob+matching: `"all"` / `""` matches everything, `"foo.*"` matches+`"foo.X"` and `"foo.X.Y"`, exact strings match exactly.++`from_legacy(event_type, payload)` wraps pre-framework `Dict`+dispatches as a back-compat shim — every existing trigger keeps+working untouched.++### `WebhookTriggerNode` — the canonical TriggerNode base++Subclass for any signed-webhook trigger. Plugin declares only what+differs from the generic shape:++```python+from services.events import (+ BaseTriggerParams, WebhookTriggerNode, WorkflowEvent,+)++class MyParams(BaseTriggerParams):+ livemode_filter: Literal["all", "test", "live"] = "all"++class MyReceiveNode(WebhookTriggerNode):+ type = "myReceive"+ display_name = "My Receive"+ group = ("myprovider", "trigger")+ handles = (...,)+ credentials = (MyCredential,)++ webhook_source = MyWebhookSource # required: which source feeds events+ event_type_prefix = "my." # auto-prepended to user filters+ Params = MyParams+ Output = MyOutput++ async def _check_precondition(self) -> Optional[str]:+ from ._source import get_listen_source+ return None if get_listen_source()._started else "Daemon not running"++ def _extra_filter(self, params): # optional; on top of event-type match+ if params.livemode_filter == "all":+ return None+ target = params.livemode_filter == "live"+ return lambda ev: bool(ev.data.get("livemode")) is target++ def shape_output(self, event: WorkflowEvent) -> Dict:+ # Optional override; default returns event.model_dump(mode="json")+ ...+```++`WebhookTriggerNode` provides:++- `event_type` derived from `webhook_source.type` automatically.+- `build_filter` combining CloudEvents type-glob + optional+ `_extra_filter`.+- `execute()` with `_check_precondition` short-circuit and reshape+ passthrough.+- The `@Operation("wait")` stub.++### `WebhookSource` — HTTP receiver++Plugin pairs the trigger with a `WebhookSource` that owns signature+verification + payload shaping:++```python+from services.events import StripeVerifier, WebhookSource, WorkflowEvent++class StripeWebhookSource(WebhookSource):+ type = "stripe.webhook"+ path = "stripe" # /webhook/stripe+ verifier = StripeVerifier+ secret_field = "stripe_webhook_secret"+ credential = StripeCredential++ async def shape(self, request, body, payload) -> WorkflowEvent:+ return WorkflowEvent(+ id=payload["id"],+ type=f"stripe.{payload['type']}",+ source=f"stripe://{payload.get('account', 'default')}",+ time=datetime.fromtimestamp(payload["created"], tz=timezone.utc),+ data=payload,+ )+```++The shared dispatch path lives in `routers/webhook.py` — it consults+`WEBHOOK_SOURCES`, runs the verifier, calls `shape()`, dispatches via+`event_waiter`. **No plugin name is hardcoded in core.**++### `DaemonEventSource` — supervised subprocess driver++For plugins that wrap a long-lived CLI tool or SDK loop (Stripe CLI,+future GitHub-CLI / Cloudflare-Wrangler / etc.). Delegates lifecycle+to `ProcessService` (battle-tested PATHEXT-aware launching, kill_tree+cleanup, log capture):++```python+from services.events import DaemonEventSource, WorkflowEvent++class StripeListenSource(DaemonEventSource):+ type = "stripe.listen"+ process_name = "stripe-listen"+ binary_name = "stripe"+ workflow_namespace = "_stripe"+ install_hint = "https://stripe.com/docs/stripe-cli#install"+ credential = StripeCredential++ def build_command(self, secrets: Dict) -> str:+ return f"stripe listen --print-secret --api-key {secrets['api_key']}"++ def parse_line(self, stream: str, line: str) -> Optional[WorkflowEvent]:+ # called per-line for both stdout and stderr+ if stream == "stderr" and (m := WHSEC_RE.search(line)):+ asyncio.create_task(self._persist_secret(m.group(0)))+ return None+```++The base provides `start()` / `stop()` / `restart()` / `status()` /+`has_credential()` / lifecycle locking / pre-flight `shutil.which`+check / log tailing.++### Webhook verifiers++Drop-in HMAC schemes covering the major providers:++| Class | Header | Algorithm | Used by |+|---|---|---|---|+| `StripeVerifier` | `Stripe-Signature: t=…,v1=…` | HMAC-SHA256 over `t.body` | Stripe |+| `StandardWebhooksVerifier` | `webhook-id` / `webhook-timestamp` / `webhook-signature` | HMAC-SHA256 base64 over `id.ts.body` | Svix-backed providers (Resend, Clerk, Loops, …) |+| `GitHubVerifier` | `X-Hub-Signature-256: sha256=…` | HMAC-SHA256 over body | GitHub |+| `HmacVerifier` | configurable header + prefix | HMAC-SHA256 over body | generic fallback |++Each verifier raises `ValueError` on mismatch; `WebhookSource.handle`+catches it and returns HTTP 400.++### Wiring helpers++Two factory functions collapse the per-plugin `__init__.py` boilerplate+to four lines:++```python+# nodes/stripe/_handlers.py+from services.events import make_lifecycle_handlers, run_cli_command+from ._source import get_listen_source++WS_HANDLERS = make_lifecycle_handlers(+ prefix="stripe",+ source=get_listen_source(),+ extra={"stripe_trigger": handle_stripe_trigger}, # plugin-specific extras+)+# → registers stripe_connect / stripe_disconnect / stripe_reconnect /+# stripe_status from the source's start/stop/restart/status methods ++# the stripe_trigger handler the plugin owns.++# nodes/stripe/__init__.py+register_service_refresh(make_status_refresh(+ get_listen_source(),+ status_key="stripe",+ broadcast_type="stripe_status",+))+# → auto-reconnect on WS-client connect + mirror status into+# broadcaster._status["stripe"] + broadcast.+```++### `run_cli_command` — generic CLI invocation++Used by ActionNodes that wrap a CLI tool. Resolves the binary on+PATH, optionally injects the credential's `api_key` via the+convention flag (`--api-key` by default), runs subprocess with+timeout, parses stdout as JSON, returns a uniform envelope:++```python+from services.events import run_cli_command++result = await run_cli_command(+ binary="stripe",+ argv=["customers", "create", "--email", "[email protected]"],+ credential=StripeCredential,+)+# {"success": bool, "result": parsed-or-None, "stdout": str,+# "stderr": str, "error": str-or-None}+```++### Stripe — reference implementation++The Stripe plugin+([`server/nodes/stripe/`](../server/nodes/stripe/)) is the canonical+Wave 12 example: 540 LOC total / 258 executable, supervising a CLI+daemon, verifying signed webhooks, exposing both a TriggerNode+(`stripeReceive`) and a dual-purpose ActionNode + AI tool+(`stripeAction`). See [`stripe_service.md`](./stripe_service.md) for+the per-file walkthrough.++### Integration points (no core edits per plugin)++| Concern | Framework integration | Plugin contribution |+|---|---|---|+| HTTP webhook ingress | `routers/webhook.py` consults `WEBHOOK_SOURCES` registry | `register_webhook_source(MySource())` |+| Event dispatch into workflows | `event_waiter.dispatch(source.type, event)` from `WebhookSource.handle` | provider-specific `shape()` returning `WorkflowEvent` |+| Trigger waiting + filtering | `WebhookTriggerNode.build_filter` (CloudEvents glob) | optional `_extra_filter(params)` |+| Daemon lifecycle | `DaemonEventSource.start/stop/restart` via `ProcessService` | `build_command(secrets)` + `parse_line(stream, line)` |+| Lifecycle WebSocket commands | `make_lifecycle_handlers(prefix, source, extra=…)` | provider-specific extra handlers |+| Status refresh on WS connect | `make_status_refresh(source, status_key, broadcast_type)` | nothing — auto-derived from source |+| CLI subprocess invocation | `run_cli_command(binary=…, argv=…, credential=…)` | nothing — credential injection is automatic |++### When to use the framework++Use it for any new event-source plugin:++- Signed webhooks → `WebhookSource` + `WebhookTriggerNode` + a verifier+ from `services.events.verifiers` (or contribute a new one).+- CLI daemons → `DaemonEventSource`.+- API polling → `PollingEventSource`.+- Pure HTTP push without a verifier → `PushEventSource` directly.++Use plain `TriggerNode` only for in-process / synthetic events+(`taskTrigger`, `chatTrigger`) that don't have an external source.++### Phase rollout++- **Phase 1 (shipped):** framework lands, Stripe plugin built natively+ on top. Existing 9 trigger plugins keep using their pre-framework+ paths (the `event_waiter.dispatch(event_type, Dict)` shim accepts+ legacy `Dict` payloads alongside `WorkflowEvent`).+- **Phase 2 (planned):** migrate `gmailReceive`, `emailReceive`,+ `twitterReceive` to `PollingEventSource`. Net delete: ~30 LOC each.+- **Phase 3 (planned):** migrate `telegramReceive` and+ `whatsappReceive` to `DaemonEventSource`. Net delete: ~50 LOC each.+- **Phase 4 (planned):** sunset the legacy `Dict`-payload shim once+ every trigger uses `WorkflowEvent`.diff --git a/docs-internal/stripe_service.md b/docs-internal/stripe_service.mdnew file mode 100644index 00000000..cdac4a1d--- /dev/null+++ b/docs-internal/stripe_service.md@@ -0,0 +1,540 @@+# Stripe Service++Stripe integration via the official [Stripe CLI](https://stripe.com/docs/stripe-cli).+Two workflow nodes:++- **`stripeAction`** (dual-purpose ActionNode + AI tool) — runs any+ `stripe …` command via subprocess and returns parsed JSON.+- **`stripeReceive`** (TriggerNode) — fires when `stripe listen`+ forwards a webhook event to MachinaOs at `/webhook/stripe`.++Stripe is the reference implementation of the Wave 12 event framework+documented in [Plugin System → Wave 12](./plugin_system.md#wave-12--generalized-event-framework-servicesevents).+Most of the heavy lifting (HMAC signature verification, daemon+supervision, lifecycle WebSocket handlers, status broadcasts, CLI+invocation) lives in [`services/events/`](../server/services/events/) —+this folder contributes only the Stripe-specific shapes.++## Architecture++```+ ┌────────────────────────────────────────────────────┐+ │ services/events/ │+ │ WorkflowEvent, EventSource, WebhookTriggerNode, │+ │ DaemonEventSource, StripeVerifier, run_cli_command│+ │ make_lifecycle_handlers, make_status_refresh │+ └──────────────────────┬─────────────────────────────┘+ │ subclassed by+ ┌──────────────────────────────┼──────────────────────────────┐+ ▼ ▼ ▼+┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐+│ StripeListenSrc │ │ StripeWebhookSrc │ │ StripeAction │+│ (DaemonEvent │ │ (WebhookSource) │ │ Node │+│ Source) │ │ │ │ (ActionNode │+│ │ │ path = "stripe" │ │ + AI tool) │+│ supervises │ │ verifier = │ │ │+│ `stripe listen` │ │ StripeVerifier│ │ runs any │+│ via │ │ shape() → │ │ `stripe ...` │+│ ProcessService │ │ WorkflowEvent │ │ via │+│ │ │ │ │ run_cli_command │+│ captures whsec_ │ └──────────────────┘ └──────────────────┘+│ from stderr │ ▲ ▲+│ banner │ │ │+└──────────────────┘ │ │+ ▲ │ │+ │ start/stop/status │ POST /webhook/stripe │ subprocess+ │ │ │+ stripe CLI subprocess stripe listen ──forwards─▶ MachinaOs+ (long-lived daemon) (running daemon writes to localhost)+```++### Request flow — incoming webhook event++```+Stripe (cloud)+ │ event fires+ ▼+stripe listen (local daemon, supervised by StripeListenSource)+ │ forwards to --forward-to URL with Stripe-Signature header+ ▼+POST http://localhost:{port}/webhook/stripe+ │+ ▼+routers/webhook.py:handle_webhook+ │ if path in WEBHOOK_SOURCES → delegate+ ▼+StripeWebhookSource.handle(request)+ │+ ├── verifier.verify(headers, body, secret)+ │ Stripe-Signature: t=<ts>,v1=<hmac>+ │ raises ValueError → HTTPException(400)+ │+ ├── shape(request, body, payload)+ │ → WorkflowEvent(id=evt_…, type="stripe.charge.succeeded",+ │ source="stripe://acct_…", data=payload)+ │+ └── event_waiter.dispatch(source.type, event)+ ▼+ StripeReceiveNode waiters resolved+ (WebhookTriggerNode.execute returns the shaped event)+```++### Request flow — outgoing CLI action++```+StripeActionNode.run(params)+ │ params.command = "customers create --email [email protected]"+ ▼+shlex.split(command)+ │ → ["customers", "create", "--email", "[email protected]"]+ ▼+run_cli_command(binary="stripe", argv=…, credential=StripeCredential)+ │+ ├── StripeCredential.resolve() → {"api_key": "sk_test_…", …}+ ├── shutil.which("stripe") → resolves binary on PATH+ ├── asyncio.create_subprocess_exec(+ │ binary, *argv, "--api-key", api_key,+ │ stdout=PIPE, stderr=PIPE,+ │ )+ ├── asyncio.wait_for(proc.communicate(), timeout=30.0)+ ├── json.loads(stdout) on success+ ▼+{"success": True, "result": {...}, "stdout": "..."}+```++### Daemon lifecycle++```+WS message: stripe_connect+ │+ ▼+StripeListenSource.start() (lock-protected, idempotent)+ │+ ├── StripeCredential.resolve() → secrets+ ├── shutil.which("stripe") → fail fast if not installed+ ├── ProcessService.start(+ │ name="stripe-listen",+ │ command="stripe listen --forward-to http://localhost:{port}/webhook/stripe+ │ --print-secret --api-key sk_test_…",+ │ workflow_id="_stripe_global",+ │ working_directory={workspace}/_stripe,+ │ )+ │+ ├── spawn _capture_secret task+ │ tails {cwd}/.processes/stripe-listen/stderr.log+ │ regex: r"whsec_[A-Za-z0-9_]+"+ │ on match: auth_service.store_api_key("stripe_webhook_secret", …)+ │+ └── _broadcast_status() → broadcaster._status["stripe"] + WS broadcast++WS message: stripe_disconnect+ ▼+StripeListenSource.stop()+ ├── cancel capture task+ ├── ProcessService.stop("stripe-listen", "_stripe_global")+ └── _broadcast_status()+```++## Key Files++| File | Description |+|---|---|+| `server/nodes/stripe/__init__.py` | Wiring: 5 `register_*` calls + `make_status_refresh`. |+| `server/nodes/stripe/_credentials.py` | `StripeCredential(ApiKeyCredential)` declaring the `stripe_api_key` secret + `stripe_webhook_secret` extra field. |+| `server/nodes/stripe/_source.py` | `StripeListenSource(DaemonEventSource)` and `StripeWebhookSource(WebhookSource)` plus their singletons. |+| `server/nodes/stripe/_handlers.py` | WS handlers via `make_lifecycle_handlers`; the only plugin-specific handler is `stripe_trigger` (synthetic test events). |+| `server/nodes/stripe/stripe_action.py` | `StripeActionNode` — pass-through over the CLI via `run_cli_command`. |+| `server/nodes/stripe/stripe_receive.py` | `StripeReceiveNode(WebhookTriggerNode)` — filter overrides + output reshape. |+| `server/services/events/__init__.py` | Public framework surface — exports every base class + helper. |+| `server/services/events/daemon.py` | `DaemonEventSource` — supervises subprocess via `ProcessService`, tails logs. |+| `server/services/events/webhook.py` | `WebhookSource` + `WEBHOOK_SOURCES` registry + `register_webhook_source`. |+| `server/services/events/triggers.py` | `WebhookTriggerNode` + `BaseTriggerParams`. |+| `server/services/events/cli.py` | `run_cli_command` helper. |+| `server/services/events/lifecycle.py` | `make_lifecycle_handlers` + `make_status_refresh`. |+| `server/services/events/verifiers/stripe.py` | `StripeVerifier` (`t=…,v1=…` HMAC-SHA256). |+| `server/routers/webhook.py` | Path-handler arm: consults `WEBHOOK_SOURCES` before falling through to legacy generic dispatch. |+| `server/nodes/visuals.json` | `stripeAction` / `stripeReceive` icon + color (`asset:stripe`, `#635BFF`). |+| `server/nodes/groups.py` | `payments` palette group. |+| `client/src/assets/icons/stripe.svg` | Stripe icon. |+| `server/tests/services/test_events.py` | 18 framework tests (envelope, verifiers, polling/daemon lifecycle, WebhookSource). |+| `server/tests/nodes/test_stripe_plugin.py` | 21 Stripe-specific tests (shape, filter, action passthrough, registrations). |++## Plugin classes++### `StripeCredential`++```python+class StripeCredential(ApiKeyCredential):+ id = "stripe_api_key"+ display_name = "Stripe"+ category = "Payments"+ icon = "asset:stripe"+ key_name = "" # CLI takes the key via --api-key, not a header+ extra_fields = ("stripe_webhook_secret",) # captured from CLI banner+ docs_url = "https://stripe.com/docs/cli"+```++Storage:++| Key | Type | Origin | Purpose |+|---|---|---|---|+| `stripe_api_key` | API key | User pastes from Stripe Dashboard → Developers → API keys | Authenticates every CLI invocation. Use a **restricted key** (Stripe → API keys → Create restricted key) with the minimum scopes you need. |+| `stripe_webhook_secret` | API key (extra field) | Auto-captured by `StripeListenSource._capture_secret` from the CLI's stderr banner | Verifies forwarded webhook signatures via `StripeVerifier`. Stable across daemon restarts; the CLI re-uses the same secret for the same MachinaOs install. |++### `StripeListenSource(DaemonEventSource)`++Supervises `stripe listen` as a long-lived process. Inherits the+full `DaemonEventSource` lifecycle (start / stop / restart / status /+log tailing). The Stripe-specific overrides are minimal:++| Method / attr | Purpose |+|---|---|+| `process_name = "stripe-listen"` | Key used by `ProcessService` to track this daemon. |+| `binary_name = "stripe"` | Resolved via `shutil.which`; surfaces a clear "not installed" error. |+| `workflow_namespace = "_stripe"` | The `ProcessService` workflow id and working dir under `{workspace_base}/_stripe`. |+| `install_hint` | Surfaced in the "binary not on PATH" error. |+| `credential = StripeCredential` | Resolved by the framework before `build_command` is called. |+| `build_command(secrets)` | Returns the `stripe listen --forward-to … --print-secret --api-key …` command string. |+| `parse_line(stream, line)` | On each stderr line, regex-matches `whsec_…`; on first match, persists the secret via `auth_service.store_api_key("stripe_webhook_secret", …)`. The Stripe daemon doesn't emit events itself — events arrive via the webhook receiver. |++### `StripeWebhookSource(WebhookSource)`++Receives forwarded events at `/webhook/stripe`. The framework owns+signature verification, JSON parsing, and `event_waiter.dispatch`;+this class declares only the path, the verifier, the secret-field+name, and the payload-to-`WorkflowEvent` shaping:++```python+class StripeWebhookSource(WebhookSource):+ type = "stripe.webhook"+ path = "stripe"+ verifier = StripeVerifier+ secret_field = "stripe_webhook_secret"+ credential = StripeCredential++ async def shape(self, request, body, payload) -> WorkflowEvent:+ created = payload.get("created")+ time = (+ datetime.fromtimestamp(int(created), tz=timezone.utc)+ if created else datetime.now(timezone.utc)+ )+ account = payload.get("account") or "default"+ return WorkflowEvent(+ id=payload.get("id") or "", # provider event id (replay safety)+ type=f"stripe.{payload.get('type', 'unknown')}",+ source=f"stripe://{account}",+ time=time,+ data=payload,+ subject=payload.get("type"),+ )+```++The `id` mirrors Stripe's `evt_…` so duplicate deliveries (Stripe+retries on 5xx) are idempotent at the WorkflowEvent level.++### `StripeReceiveNode(WebhookTriggerNode)`++```python+class StripeReceiveParams(BaseTriggerParams):+ livemode_filter: Literal["all", "test", "live"] = "all"+++class StripeReceiveNode(WebhookTriggerNode):+ type = "stripeReceive"+ display_name = "Stripe Receive"+ subtitle = "Webhook Event"+ group = ("payments", "trigger")+ handles = (+ {"name": "output-main", "kind": "output", "position": "right",+ "label": "Output", "role": "main"},+ )+ credentials = (StripeCredential,)+ webhook_source = StripeWebhookSource+ event_type_prefix = "stripe." # users write "charge.*" not "stripe.charge.*"+ Params = StripeReceiveParams+ Output = StripeReceiveOutput++ async def _check_precondition(self) -> Optional[str]:+ # Refuse to register a waiter if the daemon isn't running.+ ...++ def _extra_filter(self, params): # livemode filter on top of event-type+ ...++ def shape_output(self, event: WorkflowEvent) -> Dict:+ # Extract Stripe-shaped fields from the WorkflowEvent's CloudEvents data.+ ...+```++The framework's `WebhookTriggerNode` handles event-type glob matching+(`charge.*`, `payment_intent.*`, `all`), the+`event_type_prefix` auto-prepend, the `_check_precondition`+short-circuit, and the `Operation("wait")` stub. This class only+contributes the livemode filter and the output reshape.++### `StripeActionNode(ActionNode)` — dual-purpose++```python+class StripeActionParams(BaseModel):+ command: str = Field(default="", description=...)+++class StripeActionOutput(BaseModel):+ command: Optional[str] = None+ success: Optional[bool] = None+ result: Optional[Any] = None+ stdout: Optional[str] = None+ error: Optional[str] = None+++class StripeActionNode(ActionNode):+ type = "stripeAction"+ group = ("payments", "tool")+ credentials = (StripeCredential,)+ task_queue = TaskQueue.REST_API+ usable_as_tool = True++ @Operation("run", cost={"service": "stripe", "action": "run", "count": 1})+ async def run(self, ctx, params):+ cmd = params.command.strip()+ if not cmd:+ raise RuntimeError("command is required")+ result = await run_cli_command(+ binary="stripe", argv=shlex.split(cmd), credential=StripeCredential,+ )+ if not result["success"]:+ raise RuntimeError(result.get("error") or "Stripe CLI invocation failed")+ return {+ "command": cmd, "success": True,+ "result": result.get("result"), "stdout": result.get("stdout"),+ }+```++The CLI does its own argument parsing, validation, and error+messages. We don't re-implement per-resource operations — the user+(or LLM) types the command exactly as they would after `stripe `:++| Example command | What it does |+|---|---|+| `customers create --email [email protected] --name "Acme Inc"` | Create a Stripe customer |+| `customers list --limit 10` | List recent customers |+| `payment_intents create --amount 2000 --currency usd --customer cus_…` | Create a PaymentIntent |+| `refunds create --payment-intent pi_…` | Refund a PaymentIntent |+| `charges retrieve ch_…` | Fetch a charge |+| `trigger charge.succeeded` | Fire a synthetic test event (also exposed via the `stripe_trigger` WebSocket handler) |++All Stripe CLI commands are supported automatically; future Stripe+resources work without code changes.++## WebSocket handlers++Built via `make_lifecycle_handlers(prefix="stripe", source=…)` — the+4 lifecycle handlers are auto-generated; only `stripe_trigger` is+plugin-specific:++| Type | Handler | Purpose |+|---|---|---|+| `stripe_connect` | `source.start()` | Spawn the daemon. Idempotent. |+| `stripe_disconnect` | `source.stop()` | Stop the daemon, cancel the secret-capture task. |+| `stripe_reconnect` | `source.restart()` | Stop + start. |+| `stripe_status` | `source.status()` + `has_credential()` | Returns `{connected, pid, webhook_secret_captured, has_stored_key}`. |+| `stripe_trigger` | `run_cli_command("stripe", ["trigger", event])` | Synthetic test event. |++## Webhook signature verification++`StripeVerifier` ([`server/services/events/verifiers/stripe.py`](../server/services/events/verifiers/stripe.py))+implements [Stripe's webhook signature scheme](https://stripe.com/docs/webhooks/signatures):++- Header format: `Stripe-Signature: t=<unix_ts>,v1=<hex_hmac>[,v1=<rotated>]`+- Signed payload: `f"{timestamp}.{raw_body}"`+- Algorithm: HMAC-SHA256 hex-encoded+- Multiple `v1=` entries are accepted (secret rotation)++Verifier raises `ValueError` on mismatch; `WebhookSource.handle`+catches it and returns HTTP 400. If the signing secret hasn't been+captured yet (race between first webhook and the `whsec_…` banner),+the framework logs a warning and accepts the event without+verification — this only happens during the first ~5 seconds of+daemon startup.++## Status broadcasting++`make_status_refresh(source, status_key="stripe", broadcast_type="stripe_status")`+runs once per WebSocket-client connect (via the+`register_service_refresh` registry):++1. Auto-reconnects the daemon if a `stripe_api_key` is stored but+ the daemon isn't running.+2. Mirrors the source's status into `broadcaster._status["stripe"]`.+3. Broadcasts a `stripe_status` message to every connected client.++The broadcast payload:++```json+{+ "type": "stripe_status",+ "data": {+ "connected": true,+ "pid": 12345,+ "webhook_secret_captured": true+ }+}+```++The frontend Credentials Modal renders this as the connection+indicator.++## Installation++The Stripe CLI must be installed and on `PATH`:++```bash+# macOS+brew install stripe/stripe-cli/stripe++# Windows (Scoop)+scoop install stripe++# Linux (apt)+echo "deb [signed-by=/usr/share/keyrings/stripe.gpg] https://packages.stripe.dev/stripe-cli-debian-local stable main" \+ | sudo tee /etc/apt/sources.list.d/stripe.list+sudo apt update && sudo apt install stripe++# Direct binary+# https://github.com/stripe/stripe-cli/releases+```++`StripeListenSource.start()` resolves the binary via+`shutil.which("stripe")`. If missing, the WS `stripe_connect`+response is:++```json+{+ "success": false,+ "error": "'stripe' not on PATH. Install: https://stripe.com/docs/stripe-cli#install"+}+```++## Configuration++No JSON config file. Everything plugin-configurable lives on the+class attributes:++| Knob | Where | Default |+|---|---|---|+| Daemon process name | `StripeListenSource.process_name` | `"stripe-listen"` |+| Binary name | `StripeListenSource.binary_name` | `"stripe"` |+| Workspace subdir | `StripeListenSource.workflow_namespace` | `"_stripe"` (under `Settings().workspace_base_resolved`) |+| Webhook path | `StripeWebhookSource.path` | `"stripe"` (i.e. `/webhook/stripe`) |+| Forward-to port | derived from `Settings().port` | typically `3010` |+| Verifier | `StripeWebhookSource.verifier` | `StripeVerifier` |+| Action operation cost | `@Operation("run", cost=…)` | `{service: "stripe", action: "run", count: 1}` |++The CLI's webhook secret (`whsec_…`) is captured at runtime and+persisted automatically — no manual config step.++## Credentials Modal UI++The Stripe panel lives in the Payments category (introduced+specifically for this plugin in the `payments` palette group). It+provides:++- **API key** input (secret) — pasted from Stripe Dashboard.+- **Connect / Disconnect** buttons → fire `stripe_connect` /+ `stripe_disconnect` WebSocket messages.+- **Status indicator** — driven by the `stripe_status` broadcast+ (`connected`, `webhook_secret_captured`).+- **Reconnect** button — issues `stripe_reconnect` for stuck states.++No webhook-secret input is needed — the daemon captures it+automatically. The UI surfaces "secret captured ✓" once the value is+persisted.++## Operational notes++### API key in process argv++`stripe listen --api-key sk_test_…` puts the key in the daemon's+command line, which means it's visible to anyone with `ps` access on+the host **and** in `ProcessService`'s `command` field which is+logged at INFO. Acceptable on a single-user dev machine — Stripe's+docs explicitly endorse the `--api-key` flag for headless use. If a+future deployment hosts multiple tenants, swap to environment-variable+injection (a one-line change to `DaemonEventSource.start` to merge+caller-supplied env into the subprocess env).++### Webhook secret race window++The first ~5 seconds after `stripe_connect`, the secret-capture task+hasn't yet matched the `whsec_…` line in stderr. If a webhook arrives+during that window, the framework logs a warning and accepts the+event without verification. In practice this is benign because Stripe+won't deliver real events until the daemon is fully ready, but+synthetic events triggered via `stripe_trigger` immediately after+connect can hit this path.++### Single global daemon++One Stripe account per MachinaOs install. The daemon is+singleton-global (`workflow_id="_stripe_global"`). Multi-account+support is deferred to a future revision; the design holds — give+`StripeListenSource` a `__init__(account_id)` and key the singleton+by id.++### No auto-restart on crash++If `stripe listen` exits unexpectedly, the framework surfaces the+disconnected status and waits for the user to reconnect via the+Credentials Modal. The `_capture_secret` task hits EOF on the log+file and exits cleanly. There's no exponential-backoff respawn loop+— that's deliberate to keep failing daemons visible rather than+hidden behind silent retries.++## Verification++End-to-end smoke (requires Stripe CLI installed, test API key in+Credentials):++1. **Daemon start.** WS `{"type":"stripe_connect"}` → confirm:+ - `process_service.list_processes("_stripe_global")` shows+ `stripe-listen` running.+ - Within ~3 s the stderr.log contains `whsec_…`.+ - `auth_service.get_api_key("stripe_webhook_secret")` returns the+ secret.+ - WS reply: `{connected: true, webhook_secret_captured: true}`.+2. **Synthetic event.** Build a workflow with `StripeReceiveNode`+ (filter: `charge.*`) → console node. Deploy. WS+ `{"type":"stripe_trigger","event":"charge.succeeded"}`. Console+ fires with `event_type="charge.succeeded"`, `event_id` matches the+ CLI's emitted event.+3. **Filter rejection.** Set filter to `payment_intent.created`,+ retrigger `charge.succeeded` — node does NOT fire. Trigger+ `payment_intent.created` — it does.+4. **Action node.** Configure `StripeActionNode` with+ `command="customers create --email [email protected]"`. Run. Output+ contains `id: cus_…`, `email: [email protected]`.+5. **AI tool surface.** From a chat agent, prompt+ "create a Stripe test customer with email [email protected]"; the+ LLM emits a `stripeAction.run` tool call.+6. **Signature failure.**+ `curl -X POST -H "Stripe-Signature: t=0,v1=garbage" http://localhost:3010/webhook/stripe -d '{}'`+ returns 400; no event dispatched.+7. **Reconnect.** WS `stripe_disconnect` → process gone. WS+ `stripe_reconnect` → idempotent reattach + new `whsec_…` capture.+8. **Auto-reconnect.** Restart MachinaOs. On first WS-client connect,+ `make_status_refresh` sees the stored key and auto-spawns the+ daemon.++Unit tests live in [`server/tests/nodes/test_stripe_plugin.py`](../server/tests/nodes/test_stripe_plugin.py)+(21 tests) and [`server/tests/services/test_events.py`](../server/tests/services/test_events.py)+(18 framework tests). Run via `pytest server/tests/services/test_events.py+server/tests/nodes/test_stripe_plugin.py -v`.++## Related Docs++- [Plugin System → Wave 12 framework](./plugin_system.md#wave-12--generalized-event-framework-servicesevents) — the framework Stripe is built on.+- [Plugin System → Self-contained plugin folders](./plugin_system.md#self-contained-plugin-folders) — Wave 11.H pattern Stripe also follows.+- [Node Creation Guide](./node_creation.md) — when to use which framework piece for a new plugin.+- [Event Waiter System](./event_waiter_system.md) — generic dispatch path that `WebhookSource.handle` calls into.+- [Status Broadcaster](./status_broadcaster.md) — `register_service_refresh` registry that backs `make_status_refresh`.+- [Credentials Encryption](./credentials_encryption.md) — how `stripe_api_key` and `stripe_webhook_secret` are stored.