Skip to content

Self-improving AI Employees for everyone

feat(stripe): CLI-managed OAuth login + auto-installer + skill

trohitga32f67131258
diff --git a/CLAUDE.md b/CLAUDE.md
index 60f8c4ca..12eb55bf 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -25,7 +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) |
+| **[Stripe Service](./docs-internal/stripe_service.md)** | Stripe CLI integration — `stripeAction` (CLI pass-through) + `stripeReceive` (signed-webhook trigger). Reference plugin for the Wave 12 event framework AND the **CLI-managed-auth pattern**: browser OAuth driven by `stripe login --non-interactive` + auto-installed binary (`ensure_stripe_cli` from GitHub releases) + marker-token reuse of `auth_service.store_oauth_tokens` + generic `credential_catalogue_updated` broadcast — zero per-provider hardcoding in the frontend. |
| **[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/client/src/components/credentials/panels/OAuthPanel.tsx b/client/src/components/credentials/panels/OAuthPanel.tsx
index 6ee467b9..db0cae02 100644
--- a/client/src/components/credentials/panels/OAuthPanel.tsx
+++ b/client/src/components/credentials/panels/OAuthPanel.tsx
@@ -14,7 +14,11 @@ import type { ProviderConfig } from '../types';
const OAuthPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ config, visible }) => {
const panel = useCredentialPanel(config, visible);
const status = useProviderStatus(config.statusHook);
- const connected = !!status?.connected;
+ // Providers without a registered status hook (e.g. CLI-managed auth
+ // like Stripe) signal "connected" via the catalogue's authoritative
+ // `stored` field — same source the modal sidebar uses for badges.
+ // Providers with a hook keep their hook-driven semantics.
+ const connected = status ? !!status.connected : !!config.stored;
return (
<div className="flex min-h-0 flex-1 flex-col p-5">
diff --git a/docs-internal/node_creation.md b/docs-internal/node_creation.md
index 38668db8..26800464 100644
--- a/docs-internal/node_creation.md
+++ b/docs-internal/node_creation.md
@@ -17,6 +17,7 @@ this file picks the right entry point based on what you're adding.
| 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` |
+| A plugin whose auth is owned by an external CLI (`stripe login`, `gh auth login`, `gcloud auth login`) | [Stripe Service](./stripe_service.md) — the reference for "marker-token + generic catalogue invalidation" — and [plugin_system.md → CLI-managed auth pattern](./plugin_system.md#cli-managed-auth-pattern) | self-contained folder + `_install.py` for the auto-downloader; `_handlers.py` calls `auth_service.store_oauth_tokens(provider, "cli-managed", "cli-managed")` after the CLI login completes, then broadcasts the existing generic `credential_catalogue_updated` event |
## The four node kinds
@@ -123,6 +124,79 @@ 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.
+## Recipe — CLI-managed auth (Stripe / `gh` / `gcloud` shape)
+
+When auth lives **inside** an external CLI (the CLI runs its own
+OAuth, persists tokens to its own config file, and our `<command>`
+calls just inherit those creds), use this pattern. Stripe is the
+canonical example.
+
+**Three plumbing pieces** — all already in the codebase, just
+reused:
+
+1. **Marker-token write after CLI login completes.** The plugin
+ writes synthetic strings to `auth_service.store_oauth_tokens`
+ with the provider id matching the catalogue's `status_hook`. The
+ strings exist purely to flip
+ `auth_service.get_oauth_tokens(status_hook) is not None` true,
+ which the catalogue handler at
+ [`server/routers/websocket.py:handle_get_credential_catalogue`](../server/routers/websocket.py)
+ uses to set `provider.stored = true`. **Same API path Google's
+ OAuth callback uses** — no new abstraction.
+
+ ```python
+ await auth_service.store_oauth_tokens(
+ provider="stripe", # matches status_hook in catalogue JSON
+ access_token="cli-managed", # marker; CLI owns the real auth
+ refresh_token="cli-managed",
+ )
+ ```
+
+2. **Generic broadcast on state change.** Plugin emits the existing
+ `credential_catalogue_updated` event — handled in
+ [`WebSocketContext.tsx`](../client/src/contexts/WebSocketContext.tsx)
+ line 671 since before Stripe shipped. The frontend invalidates
+ the catalogue, refetches, and the modal re-renders. No
+ per-provider broadcast type, no `case 'stripe_status'` —
+ **zero node-specific code in the frontend**.
+
+ ```python
+ await get_status_broadcaster().broadcast(
+ {"type": "credential_catalogue_updated"}
+ )
+ ```
+
+3. **Auto-installer for the CLI binary.** Plugins that wrap a CLI
+ ship a `_install.py` with a single `ensure_stripe_cli()`-shaped
+ async helper:
+ - Cached path → system PATH (`brew`, `scoop`, `apt`) → workspace
+ cache → fresh download from GitHub releases.
+ - Pinned version constant; `(system, machine) -> asset_name` map
+ covering Windows/Linux/Mac × x86_64/arm64.
+ - Returns absolute binary path; subsequent calls hit the cache.
+
+ The plugin's `DaemonEventSource` subclass overrides `start()` to
+ `await ensure_<provider>_cli()` before `super().start()` and
+ sets `binary_name = ""` so the framework's pre-flight
+ `shutil.which` check is skipped (we handle install ourselves).
+
+**Frontend contract**: the `OAuthPanel.tsx` `connected` derivation
+already supports CLI-managed providers via:
+
+```tsx
+const connected = status ? !!status.connected : !!config.stored;
+```
+
+Providers with no `statusHook` registered in `useProviderStatus`
+fall back to the catalogue's authoritative `config.stored` field.
+**No frontend edits needed** to add a new CLI-managed plugin.
+
+The cumulative effect: a new "wrap a CLI tool whose login is
+browser-OAuth" plugin lands as a self-contained folder under
+`server/nodes/<group>/` plus a one-line entry in
+`server/config/credential_providers.json` and zero touches outside
+the folder.
+
## What auto-wires (don't write it yourself)
When a plugin file is imported (which the `nodes/__init__.py`
@@ -156,7 +230,7 @@ What you **do** still write:
| 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) |
+| Stripe as the Wave 12 reference plugin (also the canonical CLI-managed-auth + auto-installer reference) | [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) |
| Dual-purpose nodes (workflow node + AI tool) | [dual_purpose_tool_node_creation.md](./dual_purpose_tool_node_creation.md) |
@@ -176,7 +250,18 @@ What you **do** still write:
([`services/events/`](../server/services/events/)). `EventSource`
hierarchy + CloudEvents-shaped envelope + verifier registry +
wiring helpers. Stripe is the reference.
+- **Wave 12.B** — CLI-managed-auth pattern (Stripe). Plugins whose
+ auth lives in an external CLI's own config file (`stripe login` →
+ `~/.config/stripe/config.toml`) reuse `auth_service.store_oauth_tokens`
+ with marker strings + the existing generic
+ `credential_catalogue_updated` broadcast — no provider-specific
+ Zustand entries, no per-provider WS handler cases. Includes a
+ reusable `ensure_<cli>_cli()` shape for downloading the CLI binary
+ on first use (pinned version + GitHub-releases asset map). The
+ same pattern fits any future CLI-managed integration (`gh auth
+ login`, `gcloud auth login`, `vercel login`, etc.).
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**.
+**zero edits outside the plugin folder** (and zero edits to the
+frontend).
diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.md
index 1bb585fb..ed27b5a0 100644
--- a/docs-internal/plugin_system.md
+++ b/docs-internal/plugin_system.md
@@ -1097,6 +1097,71 @@ daemon, verifying signed webhooks, exposing both a TriggerNode
(`stripeAction`). See [`stripe_service.md`](./stripe_service.md) for
the per-file walkthrough.
+### CLI-managed auth pattern
+
+Some plugins delegate auth to an external CLI tool that runs its own
+OAuth flow and persists tokens in its own config file (Stripe →
+`~/.config/stripe/config.toml`; future `gh auth login` →
+`~/.config/gh/hosts.yml`; `gcloud auth login` →
+`~/.config/gcloud/...`). Three reuse points let these plugins ship
+without any node-specific code in the frontend or in core services:
+
+1. **Marker-token write via the existing `auth_service.store_oauth_tokens`
+ API.** Plugin writes synthetic strings (e.g. `"cli-managed"`) on
+ login completion. The catalogue's existing per-provider `stored`
+ check at
+ [`routers/webhook.py:handle_get_credential_catalogue`](../server/routers/websocket.py)
+ uses
+ `auth_service.get_oauth_tokens(status_hook) is not None` —
+ identical to Google's OAuth-callback path. The synthetic tokens
+ exist purely to flip the existence check; the CLI owns the real
+ auth.
+
+2. **Generic `credential_catalogue_updated` broadcast.** The plugin
+ emits this event after every state change. The frontend's
+ existing handler in
+ [`WebSocketContext.tsx`](../client/src/contexts/WebSocketContext.tsx)
+ (line 671) invalidates the catalogue query; the modal refetches
+ and re-renders. **No new broadcast type, no Zustand entry, no
+ `case '<provider>_status'`.** Frontend has zero references to any
+ CLI-managed plugin's name.
+
+3. **`OAuthPanel.tsx` `connected` fallback.** The panel reads
+ `useProviderStatus(config.statusHook)` for legacy hook-driven
+ providers and falls back to `config.stored` (the catalogue's
+ authoritative flag) for everything else:
+
+ ```tsx
+ const connected = status ? !!status.connected : !!config.stored;
+ ```
+
+ Generic — no provider names anywhere. Future CLI-managed plugins
+ inherit correct connection-indicator behaviour automatically.
+
+**Auto-installer pattern.** Plugins wrapping a CLI binary that may
+not be on the user's `PATH` ship a `_install.py` exposing a single
+async helper:
+
+```python
+# server/nodes/<provider>/_install.py
+_VERSION = "1.40.9" # pinned
+_ASSETS = {
+ ("Windows", "AMD64"): ("…_windows_x86_64.zip", "zip", "stripe.exe"),
+ ("Linux", "x86_64"): ("…_linux_x86_64.tar.gz", "tar", "stripe"),
+ …
+}
+
+async def ensure_<cli>_cli() -> Path:
+ # 1. cached path → 2. shutil.which(...) → 3. workspace cache →
+ # 4. fresh download from GitHub releases.
+```
+
+The plugin's `DaemonEventSource` subclass overrides `start()` to
+`await ensure_<cli>_cli()` first, sets `binary_name = ""` so the
+framework's pre-flight `shutil.which` check is skipped, and uses
+the resolved path inside `build_command`. The same shape suits any
+project that publishes pre-built binaries via GitHub releases.
+
### Integration points (no core edits per plugin)
| Concern | Framework integration | Plugin contribution |
@@ -1111,6 +1176,8 @@ the per-file walkthrough.
| Credentials Modal panel | `server/config/credential_providers.json` (read by `services.credential_registry`) | one provider entry: name, category, color, `kind: "oauth"`, `icon_ref`, `status_hook`, `ws.{login,logout,status}` handler names, fields list, instructions string. Frontend modal renders it automatically — no React file edits. |
| AI tool surface | `services/ai.py` `DEFAULT_TOOL_NAMES` + `DEFAULT_TOOL_DESCRIPTIONS` | one row per dual-purpose ActionNode mapping `<nodeType>` → `<snake_case_of_node_type>` |
| Skill (LLM teaching markdown) | `server/skills/<agent>/<skill-name>/SKILL.md` (auto-discovered by `SkillLoader`) | the markdown itself, plus the linkage in `visuals.json` (`"<nodeType>": { ..., "skill": "<skill-name>" }`) |
+| Connection state surfaced to the modal (CLI-managed auth) | `auth_service.store_oauth_tokens(status_hook, "cli-managed", "cli-managed")` + the generic `credential_catalogue_updated` broadcast | one `_mark_logged_in` / `_mark_logged_out` helper pair calling `store_oauth_tokens` / `remove_oauth_tokens`; one `broadcast({"type": "credential_catalogue_updated"})` after every state change |
+| Auto-install of an external CLI binary | `_install.py` with `ensure_<cli>_cli()` + GitHub-releases asset map | pinned `_VERSION` constant, `(system, machine) -> (asset, kind, member)` table, and an override on `DaemonEventSource.start()` that `await`s the helper before `super().start()` (also set `binary_name = ""` to skip the framework's `shutil.which` pre-check) |
### Tool / skill / visuals naming contract
diff --git a/docs-internal/stripe_service.md b/docs-internal/stripe_service.md
index cdac4a1d..c2c9656c 100644
--- a/docs-internal/stripe_service.md
+++ b/docs-internal/stripe_service.md
@@ -88,51 +88,104 @@ StripeActionNode.run(params)
shlex.split(command)
│ → ["customers", "create", "--email", "[email protected]"]
▼
-run_cli_command(binary="stripe", argv=…, credential=StripeCredential)
+run_cli_command(binary="stripe", argv=…) # NO credential= injection
│
- ├── StripeCredential.resolve() → {"api_key": "sk_test_…", …}
├── shutil.which("stripe") → resolves binary on PATH
├── asyncio.create_subprocess_exec(
- │ binary, *argv, "--api-key", api_key,
+ │ binary, *argv, # plain argv, no --api-key
│ stdout=PIPE, stderr=PIPE,
│ )
+ │ (CLI reads creds from ~/.config/stripe/config.toml)
├── asyncio.wait_for(proc.communicate(), timeout=30.0)
├── json.loads(stdout) on success
▼
{"success": True, "result": {...}, "stdout": "..."}
```
-### Daemon lifecycle
+### Login lifecycle (browser OAuth + auto-install)
```
-WS message: stripe_connect
+WS message: stripe_login
│
▼
+handle_stripe_login()
+ │
+ ├── ensure_stripe_cli() ← _install.py
+ │ ├── system PATH lookup (brew/scoop/apt)
+ │ ├── workspace cache: {workspace}/_stripe/bin/stripe[.exe]
+ │ └── on miss: download v1.40.9 from github.com/stripe/stripe-cli/releases
+ │ returns absolute binary path
+ │
+ ├── run_cli_command([binary, "login", "--non-interactive"], timeout=10s)
+ │ (CLI prints {browser_url, verification_code, next_step} JSON
+ │ and exits in ~1s)
+ │
+ ├── return {success, url, verification_code} to the frontend
+ │ (modal opens the URL in a new tab, displays the code)
+ │
+ └── asyncio.create_task(_complete_login(binary, next_step))
+ │
+ ▼
+ run_cli_command([binary, "login", "--complete", next_step], timeout=600s)
+ │
+ │ (CLI polls Stripe; user authorises in browser; CLI writes
+ │ credentials to ~/.config/stripe/config.toml and exits 0)
+ │
+ ├── if is_logged_in():
+ │ ├── _mark_logged_in() ← marker-token write
+ │ │ auth_service.store_oauth_tokens(
+ │ │ provider="stripe",
+ │ │ access_token="cli-managed",
+ │ │ refresh_token="cli-managed",
+ │ │ )
+ │ │ (catalogue's get_oauth_tokens("stripe") now flips truthy)
+ │ │
+ │ └── get_listen_source().start() ← daemon auto-starts
+ │
+ └── _broadcast_catalogue_updated() ← generic broadcast
+ broadcaster.broadcast({"type": "credential_catalogue_updated"})
+ frontend's existing case-handler invalidates the catalogue
+ query → modal sees provider.stored = true → connection
+ indicator flips immediately
+
+WS message: stripe_logout
+ ▼
+handle_stripe_logout()
+ ├── get_listen_source().stop()
+ ├── run_cli_command([binary, "logout", "--all"])
+ │ (clears ~/.config/stripe/config.toml)
+ ├── _mark_logged_out() ← marker-token clear
+ │ auth_service.remove_oauth_tokens("stripe")
+ └── _broadcast_catalogue_updated()
+ (modal flips back to "Not Connected")
+```
+
+### Daemon lifecycle (post-login)
+
+```
StripeListenSource.start() (lock-protected, idempotent)
│
- ├── StripeCredential.resolve() → secrets
- ├── shutil.which("stripe") → fail fast if not installed
+ ├── ensure_stripe_cli() ← override before super().start()
+ ├── has_credential() → is_logged_in() ← override
+ │ (file check on ~/.config/stripe/config.toml)
+ ├── binary_name = "" ← framework PATH check skipped
├── ProcessService.start(
│ name="stripe-listen",
- │ command="stripe listen --forward-to http://localhost:{port}/webhook/stripe
- │ --print-secret --api-key sk_test_…",
+ │ command="<resolved-binary> listen
+ │ --forward-to http://localhost:{port}/webhook/stripe
+ │ --print-secret", # no --api-key
│ workflow_id="_stripe_global",
│ working_directory={workspace}/_stripe,
│ )
+ │ (CLI reads credentials from its config file)
│
- ├── 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
+ └── tail stderr.log
+ on match r"whsec_[A-Za-z0-9_]+":
+ auth_service.store_api_key("stripe_webhook_secret", …)
-WS message: stripe_disconnect
- ▼
StripeListenSource.stop()
- ├── cancel capture task
- ├── ProcessService.stop("stripe-listen", "_stripe_global")
- └── _broadcast_status()
+ ├── cancel tail task
+ └── ProcessService.stop("stripe-listen", "_stripe_global")
```
## Key Files
@@ -140,7 +193,11 @@ StripeListenSource.stop()
| 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/_credentials.py` | `StripeCredential(Credential)` — thin marker class. The CLI manages auth at `~/.config/stripe/config.toml`; this class only exposes the captured `stripe_webhook_secret` for the framework's signature-verifier path. |
+| `server/nodes/stripe/_install.py` | `ensure_stripe_cli()` — async, idempotent, lock-guarded. Resolves the binary path: in-process cache → system PATH → workspace-local cache at `{workspace}/_stripe/bin/stripe[.exe]` → fresh download from GitHub releases (pinned `_VERSION = "1.40.9"`). Asset-name map covers Windows AMD64, Linux x86_64/arm64, macOS x86_64/arm64. Subsequent calls hit the cache instantly. |
+| `server/skills/payments_agent/stripe-skill/SKILL.md` | LLM teaching markdown for the `stripe_action` tool. ~10K chars covering customers, charges, payment_intents, refunds, invoices, products/prices, subscriptions, the `trigger` command, common workflows, quoting/escaping, idempotency, test vs live mode, error patterns, and webhook delivery. |
+| `server/config/credential_providers.json` | JSON-driven Credentials Modal catalogue. The `payments` category + `stripe` provider entry tell the frontend modal to render a **Login with Stripe** button (no API-key field) wired to the `stripe_login` / `stripe_logout` / `stripe_status` WebSocket handlers. No React file edits required. |
+| `server/services/ai.py` | `DEFAULT_TOOL_NAMES['stripeAction'] = 'stripe_action'` and the matching tool-description entry — what the LLM sees when the action node is wired to an agent's `input-tools` handle. |
| `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`. |
@@ -163,23 +220,33 @@ StripeListenSource.stop()
### `StripeCredential`
+Thin marker class. The Stripe CLI handles its own auth state at
+`~/.config/stripe/config.toml`; nothing API-key-shaped lives in
+MachinaOs's auth_service for Stripe. Only the captured webhook
+signing secret rides as an extra field.
+
```python
-class StripeCredential(ApiKeyCredential):
- id = "stripe_api_key"
+class StripeCredential(Credential):
+ id = "stripe"
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
+ auth = "custom"
docs_url = "https://stripe.com/docs/cli"
+
+ @classmethod
+ async def resolve(cls, *, user_id: str = "owner") -> Dict[str, Any]:
+ secret = await container.auth_service().get_api_key("stripe_webhook_secret")
+ return {"stripe_webhook_secret": secret} if secret else {}
```
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. |
+| (no `stripe_api_key`) | — | Stripe CLI's `~/.config/stripe/config.toml` (populated by `stripe login`) | Authenticates every CLI invocation transparently. The CLI generates restricted keys with CLI-appropriate scopes — one for live mode, one for sandbox — valid 90 days. |
+| `stripe_webhook_secret` | API key (extra field) | Auto-captured by `StripeListenSource.parse_line` from the daemon'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. |
+| OAuth marker token | OAuth token (`auth_service.store_oauth_tokens`) | Written by `_mark_logged_in()` after `stripe login --complete` exits 0; cleared by `_mark_logged_out()` on disconnect. **Strings are dummies (`"cli-managed"`)** — the real OAuth lives in the CLI's config file. | Lights up the catalogue's `provider.stored = true` flag via the existing `auth_service.get_oauth_tokens(status_hook)` check. Same path Google's OAuth callback uses; no new abstraction. |
### `StripeListenSource(DaemonEventSource)`
@@ -190,11 +257,13 @@ 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. |
+| `binary_name = ""` | **Empty** — disables `DaemonEventSource`'s built-in `shutil.which` PATH check. The plugin handles install + verification itself via `ensure_stripe_cli()`, which falls back to a workspace-local download. |
| `workflow_namespace = "_stripe"` | The `ProcessService` workflow id and working dir under `{workspace_base}/_stripe`. |
-| `install_hint` | Surfaced in the "binary not on PATH" error. |
+| `install_hint` | Surfaced in the "install failed" error path when the auto-installer can't reach GitHub releases. |
| `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. |
+| `start()` (override) | `await ensure_stripe_cli()` then `super().start()`. Caches the resolved binary path so `build_command` (sync) can pick it up. |
+| `build_command(secrets)` | Returns `<resolved-binary> listen --forward-to … --print-secret` (no `--api-key` — CLI reads its own config file; binary path comes from `stripe_cli_path()` cache populated by `start()`). |
+| `has_credential()` (override) | Returns `is_logged_in()` — a filesystem check on `~/.config/stripe/config.toml`. The framework's auto-reconnect path uses this as the gate for restarting the daemon when a WS client connects. |
| `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)`
@@ -299,9 +368,9 @@ class StripeActionNode(ActionNode):
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,
- )
+ # No credential= — Stripe CLI reads its own creds from
+ # ~/.config/stripe/config.toml after `stripe login`.
+ result = await run_cli_command(binary="stripe", argv=shlex.split(cmd))
if not result["success"]:
raise RuntimeError(result.get("error") or "Stripe CLI invocation failed")
return {
@@ -328,17 +397,135 @@ 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:
+The lifecycle factory `make_lifecycle_handlers(prefix="stripe",
+source=…)` auto-generates `stripe_connect/disconnect/reconnect`
+from the source's `start/stop/restart` methods (used internally by
+the auto-reconnect path). The plugin-specific handlers wired into
+the modal's Connect button are `stripe_login` and `stripe_logout`:
| 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. |
+| `stripe_login` | `ensure_stripe_cli()` → `stripe login --non-interactive` (sync) → returns `{url, verification_code}` to the frontend; spawns background `_complete_login` task | **Modal "Login with Stripe" button** |
+| `stripe_logout` | stops daemon → `stripe logout --all` → `_mark_logged_out()` → `_broadcast_catalogue_updated()` | **Modal Disconnect button** |
+| `stripe_status` | returns `{logged_in, running, pid, webhook_secret_captured, connected = running ∧ logged_in}` | Optional read-only poll for diagnostics; the modal flips reactively from the catalogue refetch, not from this handler |
+| `stripe_trigger` | passes `["trigger", event]` to `run_cli_command` (after `ensure_stripe_cli`) | Synthetic test event |
+| `stripe_connect/disconnect/reconnect` | `source.start/stop/restart()` from the lifecycle factory | Daemon-only lifecycle; used by the auto-reconnect path on WS-client connect |
+
+Background `_complete_login(binary, next_step)` flow:
+
+1. `run_cli_command([binary, "login", "--complete", next_step], timeout=600s)` blocks until OAuth completes.
+2. `is_logged_in()` flips true (the CLI wrote `_api_key` lines into `config.toml`).
+3. `_mark_logged_in()` writes `auth_service.store_oauth_tokens("stripe", "cli-managed", "cli-managed")`.
+4. `get_listen_source().start()` spawns the supervised `stripe listen` daemon (which captures the `whsec_…` from its banner).
+5. `_broadcast_catalogue_updated()` emits `{type: "credential_catalogue_updated"}` — the existing generic broadcast handler in `WebSocketContext.tsx` invalidates the catalogue, the modal refetches, and `provider.stored = true` for stripe flips the connection indicator.
+
+## AI tool surface (`stripe_action`)
+
+When `StripeActionNode` is wired to an agent's `input-tools` handle,
+the LLM sees a tool named `stripe_action` (snake_case of the
+`stripeAction` node type). Three coordinates have to agree for both
+the LLM's tool-call resolver and the skill's icon resolver to find
+their target:
+
+| Place | Value | File |
+|---|---|---|
+| Node `type` (camelCase) | `stripeAction` | [`server/nodes/stripe/stripe_action.py`](../server/nodes/stripe/stripe_action.py) |
+| LLM tool name (snake_case of node type) | `stripe_action` | [`server/services/ai.py`](../server/services/ai.py) — `DEFAULT_TOOL_NAMES['stripeAction'] = 'stripe_action'` |
+| Skill `allowed-tools` (matches LLM tool name) | `stripe_action` | [`server/skills/payments_agent/stripe-skill/SKILL.md`](../server/skills/payments_agent/stripe-skill/SKILL.md) |
+| `visuals.json` key (= node type) | `stripeAction` with `"skill": "stripe-skill"` | [`server/nodes/visuals.json`](../server/nodes/visuals.json) |
+
+The skill resolver in `SkillLoader._parse_skill_metadata` runs each
+`allowed-tools` token through snake → camel (e.g. `stripe_action` →
+`stripeAction`) and looks the result up in `visuals.json` to source
+the skill's icon and color. The skill renders without an icon if
+those don't agree — see the **Common pitfall** callout in
+[`server/skills/GUIDE.md`](../server/skills/GUIDE.md#tool-naming--snake_case--camelcase-contract).
+
+## Skill — `payments_agent/stripe-skill`
+
+[`server/skills/payments_agent/stripe-skill/SKILL.md`](../server/skills/payments_agent/stripe-skill/SKILL.md)
+is the LLM-facing manual for the `stripe_action` tool. It teaches:
+
+- The single `command` field that mirrors what you'd type after
+ `stripe ` on the terminal.
+- The full Stripe CLI command surface organised by resource:
+ customers, charges, PaymentIntents, refunds, invoices, products,
+ prices, subscriptions, plus `trigger <event>` for synthetic
+ webhook events.
+- Common multi-step workflows (create-customer-then-charge,
+ refund-most-recent-payment, set-up-recurring-subscription).
+- Quoting and escaping rules — the `command` string is `shlex.split`
+ on the backend, so single-quote arguments containing spaces.
+- Idempotency keys via the CLI's `-H "Idempotency-Key: …"` flag.
+- Test vs live mode (key prefix = mode: `sk_test_` / `sk_live_`;
+ prefer restricted keys `rk_*` in production).
+- Common Stripe error codes (`resource_missing`, `card_declined`,
+ `invalid_request_error`, `authentication_required`,
+ `rate_limit_error`) and how to recover from each.
+- Webhook delivery via `stripeReceive` — including the
+ `event_type_filter` glob patterns (`charge.*`, `payment_intent.*`,
+ exact, `all`).
+- Best practices: restricted keys in production, never paste a key
+ into the `command` string (the CLI gets it from the stored
+ credential automatically), surface Stripe error messages verbatim
+ to the user.
+
+The `payments_agent/` folder is a new skill bucket (the 12th,
+alongside `assistant`, `android_agent`, `autonomous`, `coding_agent`,
+`productivity_agent`, `rlm_agent`, `social_agent`, `task_agent`,
+`terminal`, `travel_agent`, `web_agent`). It opens up future
+payments integrations (PayPal CLI, Square, etc.) under the same
+agent type.
+
+## Credentials Modal integration
+
+Stripe is wired into the JSON-driven Credentials Modal catalogue at
+[`server/config/credential_providers.json`](../server/config/credential_providers.json):
+
+```json
+"payments": { "label": "Payments", "order": 9 },
+…
+"stripe": {
+ "name": "Stripe",
+ "category": "payments",
+ "color": "dracula.purple",
+ "kind": "oauth",
+ "icon_ref": "asset:stripe",
+ "status_hook": "stripe",
+ "ws": {
+ "login": "stripe_login",
+ "logout": "stripe_logout",
+ "status": "stripe_status"
+ },
+ "instructions": "Click 'Login with Stripe' to open the Stripe Dashboard. After you authorise, the CLI stores credentials at ~/.config/stripe/config.toml and the listen daemon starts automatically. The Stripe CLI must be installed on PATH (https://stripe.com/docs/stripe-cli#install)."
+}
+```
+
+Notice there is **no `fields` array** — unlike Telegram (bot token)
+or Brave (subscription token), Stripe doesn't ask the user to paste
+anything. The CLI runs the OAuth dance and persists its own
+credentials.
+
+The catalogue is read at startup by
+[`server/services/credential_registry.py`](../server/services/credential_registry.py)
+and served to the frontend via the `get_credential_catalogue`
+WebSocket handler. The frontend Credentials Modal renders the
+provider list directly from the catalogue — **no React file edits
+required to add a new provider**, no `CredentialsModal.tsx` line
+changes.
+
+`kind: "oauth"` is the same pattern Twitter and Google use — the
+Modal renders a "Login with X" button that calls `ws.login`,
+expects a `{success, url}` response, opens that URL in a new tab,
+and listens for the `<status_hook>_status` push broadcast to flip
+the connection indicator. Stripe rides on this exact pattern with
+zero new frontend code; the difference is that Stripe's `ws.login`
+returns the URL produced by `stripe login --non-interactive`
+(rather than a URL we constructed via `oauth_utils.get_redirect_uri`
++ a Twitter/Google OAuth helper class), and there is no callback
+route in MachinaOs — the CLI completes the OAuth on its own and
+exits, at which point a background task in the `stripe_login`
+handler kicks the daemon and broadcasts updated status.
## Webhook signature verification
@@ -357,33 +544,109 @@ the framework logs a warning and accepts the event without
verification — this only happens during the first ~5 seconds of
daemon startup.
-## Status broadcasting
+## Status broadcasting — marker token + generic catalogue invalidation
-`make_status_refresh(source, status_key="stripe", broadcast_type="stripe_status")`
-runs once per WebSocket-client connect (via the
-`register_service_refresh` registry):
+There is **no `stripe_status` broadcast type, no Zustand entry, no
+hardcoded case in `WebSocketContext.tsx`**. Stripe rides on two
+existing generic mechanisms:
-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.
+### 1. The catalogue's authoritative `stored` field
-The broadcast payload:
+[`server/routers/websocket.py:handle_get_credential_catalogue`](../server/routers/websocket.py)
+enriches every provider with `stored: bool`. For providers that
+declare `status_hook` (Twitter, Google, Telegram, Stripe), the check is:
+
+```python
+tokens = await auth_service.get_oauth_tokens(status_hook)
+provider["stored"] = tokens is not None
+```
+
+Google's OAuth callback writes real tokens via
+`store_oauth_tokens("google", access_token, refresh_token, ...)`.
+Stripe writes **synthetic marker strings** (`"cli-managed"`) the
+same way — the catalogue's existing logic flips `stored: true`
+without any provider-specific code in the catalogue handler. The
+`auth_service.store_oauth_tokens` API doesn't validate the strings;
+the marker exists purely to flip the existence check.
+
+### 2. The generic `credential_catalogue_updated` broadcast
+
+After `_mark_logged_in()` / `_mark_logged_out()`, the plugin
+broadcasts:
+
+```json
+{ "type": "credential_catalogue_updated" }
+```
+
+`WebSocketContext.tsx` already has a generic case for this event
+(line 671 — predates Stripe). Its handler calls `invalidateCatalogue`
+on the TanStack Query client; the catalogue refetches; the modal
+sees the new `provider.stored` value and re-renders. **No
+stripe-specific code anywhere on the frontend.**
+
+### 3. `make_status_refresh` (auto-reconnect on WS-client connect)
+
+The plugin still registers `make_status_refresh` so that on every
+WebSocket-client connect:
+
+1. `has_credential()` (= `is_logged_in()`) is consulted. If true and
+ the daemon isn't running, `start()` is called — covers the
+ "MachinaOs restarted while user was logged in" path.
+2. `source.status()` is mirrored into `broadcaster._status["stripe"]`
+ for any consumers that read it directly. (The modal does not.)
+
+### Frontend `connected` derivation (single generic line)
+
+[`client/src/components/credentials/panels/OAuthPanel.tsx`](../client/src/components/credentials/panels/OAuthPanel.tsx):
+
+```tsx
+const connected = status ? !!status.connected : !!config.stored;
+```
+
+Providers with a `statusHook` registered in `useProviderStatus` (the
+five legacy providers) keep their hook-driven semantics. Providers
+without one (Stripe today, future CLI-managed-OAuth integrations
+tomorrow) fall back to the catalogue's authoritative `config.stored`
+field. **No `'stripe'` reference anywhere in the frontend.**
+
+## Installation
+
+The Stripe CLI is auto-installed on first use; manual install is
+optional for users who prefer system package managers:
+
+```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
+```
+
+If none of these are present, the first click on **Login with Stripe**
+triggers `ensure_stripe_cli()` which downloads the platform-matched
+release archive (~12 MB) from `github.com/stripe/stripe-cli/releases`,
+extracts the `stripe[.exe]` binary into
+`{workspace_base}/_stripe/bin/`, and proceeds with login. Subsequent
+calls hit the cache.
+
+If the download fails (no internet, GitHub down), the WS
+`stripe_login` response is:
```json
{
- "type": "stripe_status",
- "data": {
- "connected": true,
- "pid": 12345,
- "webhook_secret_captured": true
- }
+ "success": false,
+ "error": "Stripe CLI install failed. Manual install: https://stripe.com/docs/stripe-cli#install"
}
```
-The frontend Credentials Modal renders this as the connection
-indicator.
-
## Installation
The Stripe CLI must be installed and on `PATH`:
@@ -439,9 +702,13 @@ 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.
+- **Login with Stripe** button → fires `stripe_login`. The handler
+ returns a `{url, verification_code}` pair; the modal opens the URL
+ in a new tab and shows the verification code so the user can
+ confirm the pairing on the Stripe Dashboard.
+- **Disconnect** button → fires `stripe_logout`, which stops the
+ daemon and runs `stripe logout --all` to clear
+ `~/.config/stripe/config.toml`.
- **Status indicator** — driven by the `stripe_status` broadcast
(`connected`, `webhook_secret_captured`).
- **Reconnect** button — issues `stripe_reconnect` for stuck states.
@@ -452,16 +719,24 @@ 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).
+### CLI-managed credentials, not MachinaOs-managed
+
+There is no API key in `auth_service` for Stripe — the CLI persists
+its own credentials at `~/.config/stripe/config.toml` (or
+`$XDG_CONFIG_HOME/stripe/config.toml`). Implications:
+
+* **No `--api-key` in command lines.** Daemons and one-shot CLI
+ invocations run with plain argv; nothing leaks via `ps` or
+ `ProcessService`'s logged command field.
+* **`is_logged_in()` is a filesystem check.** A cheap sniff for
+ `_api_key` substring in `config.toml`. `has_credential()` and the
+ `stripe_status` `logged_in` field both use it.
+* **Logout deletes the file.** `stripe logout --all` removes the
+ profile section so the next start fails the `is_logged_in()` gate
+ until the user re-logs in.
+* **Multi-tenant deployments inherit a single config file.** That's
+ a CLI limitation, not ours; switch to per-tenant `XDG_CONFIG_HOME`
+ if needed.
### Webhook secret race window
@@ -492,38 +767,44 @@ hidden behind silent retries.
## Verification
-End-to-end smoke (requires Stripe CLI installed, test API key in
-Credentials):
+End-to-end smoke (requires Stripe CLI installed and a Stripe account):
-1. **Daemon start.** WS `{"type":"stripe_connect"}` → confirm:
+1. **Login.** Credentials Modal → Stripe → "Login with Stripe". WS
+ sends `{"type":"stripe_login"}` → reply contains `{url,
+ verification_code}`. Open the URL, confirm the code on Stripe
+ Dashboard, click Authorise. Within a few seconds the modal flips
+ to "Connected" and `stripe_status` broadcasts
+ `{logged_in: true, running: true, webhook_secret_captured: true}`.
+2. **Daemon auto-start.** After login, 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`
+3. **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`,
+4. **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
+5. **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
+6. **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.**
+7. **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.
+8. **Logout.** Credentials Modal → Disconnect. Confirm
+ `process_service.list_processes("_stripe_global")` is empty AND
+ `~/.config/stripe/config.toml` no longer contains an `_api_key`
+ line.
+9. **Auto-reconnect.** Restart MachinaOs. If still logged in
+ (`is_logged_in()` returns true), the first WS-client connect
+ triggers `make_status_refresh` which 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)
diff --git a/server/config/credential_providers.json b/server/config/credential_providers.json
index 1d629ac0..172a4379 100644
--- a/server/config/credential_providers.json
+++ b/server/config/credential_providers.json
@@ -11,7 +11,8 @@
"android": { "label": "Android", "order": 5 },
"search": { "label": "Search", "order": 6 },
"scrapers": { "label": "Scrapers", "order": 7 },
- "services": { "label": "Services", "order": 8 }
+ "services": { "label": "Services", "order": 8 },
+ "payments": { "label": "Payments", "order": 9 }
},
"providers": {
@@ -395,6 +396,22 @@
"required": true
}
]
+ },
+
+ "stripe": {
+ "name": "Stripe",
+ "category": "payments",
+ "category_label": "Payments",
+ "color": "dracula.purple",
+ "kind": "oauth",
+ "icon_ref": "asset:stripe",
+ "status_hook": "stripe",
+ "ws": {
+ "login": "stripe_login",
+ "logout": "stripe_logout",
+ "status": "stripe_status"
+ },
+ "instructions": "Click 'Login with Stripe' to open the Stripe Dashboard. After you authorise, the CLI stores credentials at ~/.config/stripe/config.toml and the listen daemon starts automatically. The Stripe CLI must be installed on PATH (https://stripe.com/docs/stripe-cli#install)."
}
}
}
diff --git a/server/nodes/stripe/_credentials.py b/server/nodes/stripe/_credentials.py
index 79c33f1c..b7d53268 100644
--- a/server/nodes/stripe/_credentials.py
+++ b/server/nodes/stripe/_credentials.py
@@ -1,25 +1,33 @@
-"""Stripe API key credential.
+"""Stripe credential — thin marker.
-Used by the two stripe plugins in this folder (stripe_action,
-stripe_receive) and by :class:`StripeService` for the supervised
-``stripe listen`` daemon.
-
-The webhook signing secret (``whsec_…``) is captured automatically from
-the CLI startup banner and stored as the ``stripe_webhook_secret``
-extra field — same persistence path as ``telegram_owner_chat_id``.
+The Stripe CLI manages its own auth state at
+``~/.config/stripe/config.toml`` (populated by ``stripe login`` and
+cleared by ``stripe logout``). MachinaOs doesn't store an API key
+itself — only the captured webhook signing secret rides along as an
+extra field so :class:`StripeWebhookSource` can verify
+``Stripe-Signature`` on incoming events.
"""
from __future__ import annotations
-from services.plugin.credential import ApiKeyCredential
+from typing import Any, Dict
+
+from services.plugin.credential import Credential
-class StripeCredential(ApiKeyCredential):
- id = "stripe_api_key"
+class StripeCredential(Credential):
+ id = "stripe"
display_name = "Stripe"
category = "Payments"
icon = "asset:stripe"
- key_name = "" # Stripe CLI takes the key via --api-key flag, not a header
- key_location = "header"
- extra_fields = ("stripe_webhook_secret",)
+ auth = "custom"
docs_url = "https://stripe.com/docs/cli"
+
+ @classmethod
+ async def resolve(cls, *, user_id: str = "owner") -> Dict[str, Any]:
+ """Return only the captured webhook signing secret. There is
+ no api_key — auth lives in the Stripe CLI's config file."""
+ from core.container import container
+
+ secret = await container.auth_service().get_api_key("stripe_webhook_secret")
+ return {"stripe_webhook_secret": secret} if secret else {}
diff --git a/server/nodes/stripe/_handlers.py b/server/nodes/stripe/_handlers.py
index 5676df6a..c89a952c 100644
--- a/server/nodes/stripe/_handlers.py
+++ b/server/nodes/stripe/_handlers.py
@@ -1,20 +1,101 @@
-"""Stripe WebSocket handlers — built from the framework lifecycle factory.
+"""Stripe WebSocket handlers.
-Only ``stripe_trigger`` (synthetic test events via the CLI) is
-plugin-specific; the other 4 lifecycle handlers come from
-:func:`services.events.make_lifecycle_handlers`.
+Login is a thin wrap around the Stripe CLI's two machine-friendly
+flags:
+
+* ``stripe login --non-interactive`` prints
+ ``{browser_url, verification_code, next_step}`` JSON and exits.
+* ``stripe login --complete <next_step>`` polls Stripe until the
+ user authorises in the browser, then writes credentials to
+ ``~/.config/stripe/config.toml`` and exits 0.
+
+The ``stripe_login`` handler runs step 1 synchronously, returns the
+URL and verification code to the frontend (same shape as Twitter /
+Google ``oauth_login`` handlers), then fires step 2 as a background
+task. When step 2 finishes, we kick the broadcaster's stripe-status
+refresh callback so the modal updates reactively.
+
+Every other lifecycle command (connect/disconnect/reconnect/status)
+comes from :func:`services.events.make_lifecycle_handlers`.
"""
from __future__ import annotations
+import asyncio
+import json
from typing import Any, Dict
from fastapi import WebSocket
+from core.logging import get_logger
from services.events import make_lifecycle_handlers, run_cli_command
-from ._credentials import StripeCredential
-from ._source import get_listen_source
+from ._install import ensure_stripe_cli, stripe_cli_path
+from ._source import (
+ get_listen_source,
+ is_logged_in,
+ stripe_config_path,
+)
+
+logger = get_logger(__name__)
+
+
+_LOGIN_TIMEOUT_SECONDS = 600
+
+
+async def _resolved_binary() -> str | None:
+ """Resolve the stripe binary path, downloading on first use.
+ Returns None on install failure (caller should surface error)."""
+ try:
+ return str(await ensure_stripe_cli())
+ except Exception as e:
+ logger.warning("[Stripe] CLI install failed: %s", e)
+ return None
+
+
+async def _status_snapshot() -> Dict[str, Any]:
+ """Compose the daemon-status + login-state dict the modal renders."""
+ src = get_listen_source()
+ status = await src.status()
+ status["logged_in"] = is_logged_in()
+ status["connected"] = bool(status.get("running")) and status["logged_in"]
+ return status
+
+
+# --- Catalogue-stored marker -------------------------------------------------
+#
+# The catalogue handler in routers/websocket.py keys its "stored" check off
+# `auth_service.get_oauth_tokens(status_hook)` for any provider with
+# `status_hook` set (the Google / Twitter pattern). The Stripe CLI manages
+# its own auth at ~/.config/stripe/config.toml — there are no real OAuth
+# tokens for us to store. We persist a synthetic marker via the same API
+# Google/Twitter use, so the catalogue's existing logic flips
+# `stored: true` after login without any node-specific code in the
+# catalogue handler.
+
+_MARKER_TOKEN = "cli-managed"
+
+
+async def _mark_logged_in() -> None:
+ from core.container import container
+ await container.auth_service().store_oauth_tokens(
+ provider="stripe",
+ access_token=_MARKER_TOKEN,
+ refresh_token=_MARKER_TOKEN,
+ )
+
+
+async def _mark_logged_out() -> None:
+ from core.container import container
+ await container.auth_service().remove_oauth_tokens("stripe")
+
+
+async def _broadcast_catalogue_updated() -> None:
+ """Trigger the generic catalogue invalidation listener already wired
+ in WebSocketContext (`case 'credential_catalogue_updated'`). The
+ frontend refetches the catalogue and sees the new stored state."""
+ from services.status_broadcaster import get_status_broadcaster
+ await get_status_broadcaster().broadcast({"type": "credential_catalogue_updated"})
async def handle_stripe_trigger(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
@@ -22,13 +103,91 @@ async def handle_stripe_trigger(data: Dict[str, Any], websocket: WebSocket) -> D
event = data.get("event")
if not event:
return {"success": False, "error": "event required (e.g. 'charge.succeeded')"}
- return await run_cli_command(
- binary="stripe", argv=["trigger", event], credential=StripeCredential,
+ binary = await _resolved_binary()
+ if not binary:
+ return {"success": False, "error": "Stripe CLI install failed"}
+ return await run_cli_command(binary=binary, argv=["trigger", event])
+
+
+async def handle_stripe_login(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Step 1 of CLI OAuth: get the browser URL + verification code."""
+ binary = await _resolved_binary()
+ if not binary:
+ return {
+ "success": False,
+ "error": "Stripe CLI install failed. Manual install: https://stripe.com/docs/stripe-cli#install",
+ }
+ result = await run_cli_command(
+ binary=binary, argv=["login", "--non-interactive"], timeout=10.0,
+ )
+ if not result["success"]:
+ return result
+ try:
+ info = json.loads(result["stdout"])
+ except json.JSONDecodeError as e:
+ return {"success": False, "error": f"unparseable stripe login response: {e}"}
+
+ next_step = info.get("next_step")
+ url = info.get("browser_url") or info.get("url")
+ if not (url and next_step):
+ return {"success": False, "error": "stripe login response missing browser_url / next_step"}
+
+ asyncio.create_task(_complete_login(binary, next_step))
+ return {
+ "success": True,
+ "url": url,
+ "verification_code": info.get("verification_code"),
+ }
+
+
+async def _complete_login(binary: str, next_step: str) -> None:
+ """Step 2: block on ``stripe login --complete`` until the user
+ authorises (or the 10-min timeout fires). On success, write the
+ same kind of marker the Google / Twitter callbacks write so the
+ catalogue's stored-check flips, then auto-start the listen
+ daemon and trigger the generic catalogue refresh on the frontend."""
+ await run_cli_command(
+ binary=binary, argv=["login", "--complete", next_step],
+ timeout=_LOGIN_TIMEOUT_SECONDS,
)
+ if is_logged_in():
+ logger.info("[Stripe] login completed; auto-starting listen daemon")
+ await _mark_logged_in()
+ await get_listen_source().start()
+ await _broadcast_catalogue_updated()
+
+
+async def handle_stripe_logout(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Stop the daemon (if running) and run ``stripe logout --all`` to
+ clear ``~/.config/stripe/config.toml``. Mirror the Google/Twitter
+ logout shape: drop the catalogue marker token + broadcast the
+ generic catalogue invalidation so the modal flips immediately."""
+ await get_listen_source().stop()
+ cached = stripe_cli_path()
+ if cached is None:
+ cfg = stripe_config_path()
+ if cfg.exists():
+ cfg.unlink(missing_ok=True)
+ result: Dict[str, Any] = {"success": True, "message": "Logged out (CLI not yet installed; cleared config file)"}
+ else:
+ result = await run_cli_command(binary=str(cached), argv=["logout", "--all"], timeout=10.0)
+ await _mark_logged_out()
+ await _broadcast_catalogue_updated()
+ return result
+
+
+async def handle_stripe_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Augments the stock daemon-status with login-state."""
+ return {"success": True, "status": await _status_snapshot()}
WS_HANDLERS = make_lifecycle_handlers(
prefix="stripe",
source=get_listen_source(),
- extra={"stripe_trigger": handle_stripe_trigger},
+ extra={
+ "stripe_login": handle_stripe_login,
+ "stripe_logout": handle_stripe_logout,
+ "stripe_trigger": handle_stripe_trigger,
+ },
)
+WS_HANDLERS["stripe_status"] = handle_stripe_status
diff --git a/server/nodes/stripe/_install.py b/server/nodes/stripe/_install.py
new file mode 100644
index 00000000..91f24f5b
--- /dev/null
+++ b/server/nodes/stripe/_install.py
@@ -0,0 +1,127 @@
+"""Stripe CLI auto-installer.
+
+On first use, downloads the official Stripe CLI binary from GitHub
+releases (https://github.com/stripe/stripe-cli/releases) and caches
+it under the workspace dir at ``_stripe/bin/stripe[.exe]``. A system
+install on PATH (brew / scoop / apt / direct binary) is preferred —
+the download path only fires when no system binary is found.
+
+Pin a version here when bumping; pre-built archives are signed by
+Stripe and served over GitHub's CDN.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import io
+import platform
+import shutil
+import stat
+import tarfile
+import zipfile
+from pathlib import Path
+from typing import Optional, Tuple
+
+import httpx
+
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+
+_VERSION = "1.40.9"
+_RELEASE_BASE = f"https://github.com/stripe/stripe-cli/releases/download/v{_VERSION}"
+
+# (system, machine) → (asset filename, archive type, member name to extract)
+_ASSETS: dict[Tuple[str, str], Tuple[str, str, str]] = {
+ ("Windows", "AMD64"): (f"stripe_{_VERSION}_windows_x86_64.zip", "zip", "stripe.exe"),
+ ("Linux", "x86_64"): (f"stripe_{_VERSION}_linux_x86_64.tar.gz", "tar", "stripe"),
+ ("Linux", "aarch64"): (f"stripe_{_VERSION}_linux_arm64.tar.gz", "tar", "stripe"),
+ ("Linux", "arm64"): (f"stripe_{_VERSION}_linux_arm64.tar.gz", "tar", "stripe"),
+ ("Darwin", "x86_64"): (f"stripe_{_VERSION}_mac-os_x86_64.tar.gz", "tar", "stripe"),
+ ("Darwin", "arm64"): (f"stripe_{_VERSION}_mac-os_arm64.tar.gz", "tar", "stripe"),
+}
+
+
+_cached_path: Optional[Path] = None
+_install_lock = asyncio.Lock()
+
+
+def _bin_dir() -> Path:
+ from core.config import Settings
+ p = Path(Settings().workspace_base_resolved).resolve() / "_stripe" / "bin"
+ p.mkdir(parents=True, exist_ok=True)
+ return p
+
+
+def stripe_cli_path() -> Optional[Path]:
+ """Sync getter for the resolved binary path. Returns ``None`` if
+ :func:`ensure_stripe_cli` hasn't run yet (or never resolved)."""
+ return _cached_path
+
+
+async def ensure_stripe_cli() -> Path:
+ """Return absolute path to the stripe binary, downloading it if
+ necessary. Idempotent + concurrent-safe.
+
+ Resolution order:
+ 1. Cached path from a prior call (in-process).
+ 2. ``shutil.which("stripe")`` — system install on PATH.
+ 3. Workspace-local copy at ``_stripe/bin/stripe[.exe]``.
+ 4. Fresh download from GitHub releases under
+ :data:`_VERSION`.
+ """
+ global _cached_path
+ if _cached_path and _cached_path.exists():
+ return _cached_path
+
+ sys_path = shutil.which("stripe")
+ if sys_path:
+ _cached_path = Path(sys_path)
+ logger.info("[Stripe] using system CLI at %s", _cached_path)
+ return _cached_path
+
+ binary_name = "stripe.exe" if platform.system() == "Windows" else "stripe"
+ target = _bin_dir() / binary_name
+
+ async with _install_lock:
+ if _cached_path and _cached_path.exists():
+ return _cached_path
+ if target.exists():
+ _cached_path = target
+ return target
+ await _download_release(target)
+ _cached_path = target
+ return target
+
+
+async def _download_release(target: Path) -> None:
+ key = (platform.system(), platform.machine())
+ asset = _ASSETS.get(key)
+ if asset is None:
+ raise RuntimeError(
+ f"No prebuilt Stripe CLI for {key}. Install manually from "
+ "https://stripe.com/docs/stripe-cli#install"
+ )
+ asset_name, kind, member = asset
+ url = f"{_RELEASE_BASE}/{asset_name}"
+ logger.info("[Stripe] downloading CLI v%s from %s", _VERSION, url)
+
+ async with httpx.AsyncClient(follow_redirects=True, timeout=120) as client:
+ resp = await client.get(url)
+ resp.raise_for_status()
+ archive = resp.content
+
+ if kind == "zip":
+ with zipfile.ZipFile(io.BytesIO(archive)) as z:
+ target.write_bytes(z.read(member))
+ else:
+ with tarfile.open(fileobj=io.BytesIO(archive), mode="r:gz") as t:
+ f = t.extractfile(member)
+ if f is None:
+ raise RuntimeError(f"Member {member!r} missing from {asset_name}")
+ target.write_bytes(f.read())
+
+ if platform.system() != "Windows":
+ target.chmod(target.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
+ logger.info("[Stripe] CLI installed to %s", target)
diff --git a/server/nodes/stripe/_source.py b/server/nodes/stripe/_source.py
index e276da39..654ad669 100644
--- a/server/nodes/stripe/_source.py
+++ b/server/nodes/stripe/_source.py
@@ -16,8 +16,10 @@ plug into the framework registries from ``__init__.py``.
from __future__ import annotations
import asyncio
+import os
import re
from datetime import datetime, timezone
+from pathlib import Path
from typing import Any, Dict, Optional
from fastapi import Request
@@ -38,6 +40,26 @@ _SECRET_RE = re.compile(r"whsec_[A-Za-z0-9_]+")
_SECRET_FIELD = "stripe_webhook_secret"
+def stripe_config_path() -> Path:
+ """Default location for the Stripe CLI's credentials file
+ (``~/.config/stripe/config.toml``, ``XDG_CONFIG_HOME``-aware)."""
+ base = os.environ.get("XDG_CONFIG_HOME")
+ return (Path(base) if base else Path.home() / ".config") / "stripe" / "config.toml"
+
+
+def is_logged_in() -> bool:
+ """Detect Stripe CLI login by sniffing its config file. Cheap
+ filesystem check — the CLI writes ``test_mode_api_key`` /
+ ``live_mode_api_key`` under a profile section on success."""
+ cfg = stripe_config_path()
+ if not cfg.exists():
+ return False
+ try:
+ return "_api_key" in cfg.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ return False
+
+
class StripeListenSource(DaemonEventSource):
"""Supervises ``stripe listen`` and persists the captured webhook
signing secret. Emits no events itself — Stripe events arrive over
@@ -45,19 +67,45 @@ class StripeListenSource(DaemonEventSource):
type = "stripe.listen"
process_name = "stripe-listen"
- binary_name = "stripe"
+ # Empty so DaemonEventSource skips its built-in PATH check; we
+ # do install + verification ourselves in start() via
+ # ensure_stripe_cli (which falls back to system PATH first, then
+ # workspace-local download).
+ binary_name = ""
workflow_namespace = "_stripe"
install_hint = "https://stripe.com/docs/stripe-cli#install"
credential = StripeCredential
def build_command(self, secrets: Dict) -> str:
+ # The CLI uses credentials it stored at ~/.config/stripe/config.toml
+ # (populated by `stripe login`). No --api-key flag here.
+ # Binary path is resolved by `ensure_stripe_cli` (called from
+ # the start() override below) and cached for sync access here.
from core.config import Settings
+ from ._install import stripe_cli_path
+
port = int(Settings().port)
+ binary = str(stripe_cli_path() or "stripe")
return (
- f"stripe listen --forward-to http://localhost:{port}/webhook/stripe "
- f"--print-secret --api-key {secrets['api_key']}"
+ f"{binary} listen --forward-to http://localhost:{port}/webhook/stripe "
+ f"--print-secret"
)
+ async def start(self) -> Dict[str, Any]:
+ """Ensure the CLI binary is downloaded before delegating to the
+ framework's daemon-start path (which calls ``build_command``)."""
+ from ._install import ensure_stripe_cli
+ try:
+ await ensure_stripe_cli()
+ except Exception as e:
+ return {"success": False, "error": f"Stripe CLI install failed: {e}"}
+ return await super().start()
+
+ async def has_credential(self) -> bool:
+ """The Stripe CLI manages auth state in its own config file —
+ that's our 'credential' for the daemon's start gate."""
+ return is_logged_in()
+
def parse_line(self, stream: str, line: str) -> Optional[WorkflowEvent]:
if stream == "stderr" and (m := _SECRET_RE.search(line)):
secret = m.group(0)
diff --git a/server/nodes/stripe/stripe_action.py b/server/nodes/stripe/stripe_action.py
index cececb05..e0203d53 100644
--- a/server/nodes/stripe/stripe_action.py
+++ b/server/nodes/stripe/stripe_action.py
@@ -59,12 +59,18 @@ class StripeActionNode(ActionNode):
@Operation("run", cost={"service": "stripe", "action": "run", "count": 1})
async def run(self, ctx: NodeContext, params: StripeActionParams) -> Any:
+ from ._install import ensure_stripe_cli
+
cmd = params.command.strip()
if not cmd:
raise RuntimeError("command is required (e.g. 'customers create --email [email protected]')")
- result = await run_cli_command(
- binary="stripe", argv=shlex.split(cmd), credential=StripeCredential,
- )
+ try:
+ binary = str(await ensure_stripe_cli())
+ except Exception as e:
+ raise RuntimeError(f"Stripe CLI install failed: {e}")
+ # No credential= — Stripe CLI reads its own creds from
+ # ~/.config/stripe/config.toml after `stripe login`.
+ result = await run_cli_command(binary=binary, argv=shlex.split(cmd))
if not result["success"]:
raise RuntimeError(result.get("error") or "Stripe CLI invocation failed")
return {
diff --git a/server/nodes/visuals.json b/server/nodes/visuals.json
index b722aed6..2efb039c 100644
--- a/server/nodes/visuals.json
+++ b/server/nodes/visuals.json
@@ -470,7 +470,8 @@
},
"stripeAction": {
"icon": "asset:stripe",
- "color": "#635BFF"
+ "color": "#635BFF",
+ "skill": "stripe-skill"
},
"stripeReceive": {
"icon": "asset:stripe",
diff --git a/server/services/ai.py b/server/services/ai.py
index 4083e681..4610887b 100644
--- a/server/services/ai.py
+++ b/server/services/ai.py
@@ -2623,6 +2623,8 @@ class AIService:
# Email (Himalaya CLI, dual-purpose tools)
'emailSend': 'email_send',
'emailRead': 'email_read',
+ # Stripe (CLI pass-through, dual-purpose tool)
+ 'stripeAction': 'stripe_action',
}
DEFAULT_TOOL_DESCRIPTIONS = {
'calculatorTool': 'Perform mathematical calculations. Operations: add, subtract, multiply, divide, power, sqrt, mod, abs',
@@ -2703,6 +2705,8 @@ class AIService:
# Email (Himalaya CLI, dual-purpose tools)
'emailSend': 'Send email via SMTP. Specify to, subject, body. Optional: cc, bcc, body_type (text/html).',
'emailRead': 'Read and manage emails via IMAP. Operations: list (envelopes), search (query), read (message by ID), folders (list), move, delete, flag.',
+ # Stripe (CLI pass-through, dual-purpose tool)
+ 'stripeAction': "Run any Stripe CLI command and return the parsed JSON response. Pass a 'command' field exactly as you would type after 'stripe ' (e.g. 'customers create --email [email protected]', 'charges list --limit 10', 'payment_intents create --amount 2000 --currency usd', 'refunds create --payment-intent pi_xxx', 'trigger charge.succeeded'). Covers every Stripe resource: customers, charges, payment_intents, refunds, invoices, products, prices, subscriptions, payment_methods, setup_intents, transfers, payouts, plus 'trigger <event>' for synthetic test events.",
}
try:
diff --git a/server/skills/GUIDE.md b/server/skills/GUIDE.md
index 4c476eaa..d79cf974 100644
--- a/server/skills/GUIDE.md
+++ b/server/skills/GUIDE.md
@@ -110,7 +110,7 @@ Provide usage guidelines, examples, and constraints.
|-------|----------|-------------|
| `name` | Yes | Lowercase, hyphens only. Must match pattern `^[a-z0-9]+(-[a-z0-9]+)*$` |
| `description` | Yes | One-line summary shown in skill lists and to the LLM |
-| `allowed-tools` | No | Space-delimited list of tool names. The first that resolves to a known node is the skill's visual source — its icon/color come from `server/nodes/visuals.json` via the `_visuals` handler. |
+| `allowed-tools` | No | Space-delimited list of LLM-facing tool names (snake_case, e.g. `stripe_action`, `apify_actor`, `whatsapp_send`). The first token whose snake→camel conversion (`stripe_action` → `stripeAction`) matches a node `type` in `server/nodes/visuals.json` becomes the skill's visual source — its icon/color come from that entry via the `_visuals` handler. **Convention:** the LLM tool name MUST be the snake_case form of the node type (e.g. `stripeAction` → `stripe_action`). The same string goes into `services/ai.py` `DEFAULT_TOOL_NAMES` so the LLM and the skill agree on the name. Mismatching the snake_case (e.g. `stripe_cli` for a `stripeAction` node) silently breaks icon resolution. |
| `metadata` | No | Arbitrary key-value pairs (author, version, category). **Don't set `icon`/`color` for skills that target a node** — those are resolved from the target node's `visuals.json` entry so the skill always mirrors the canvas. Skills with no node target (personality skills, memory operators, autonomous patterns) **may** set inline `icon` and `color` — they're the only visual source for those. |
### Name Format Rules
@@ -121,6 +121,21 @@ Provide usage guidelines, examples, and constraints.
- Examples: `my-skill`, `web-search-skill`, `code-skill`
- Invalid: `My_Skill`, `my--skill`, `MySkill`
+### Tool naming — snake_case ↔ camelCase contract
+
+Three places have to agree for a skill's icon to render correctly:
+
+| Place | Form | Example |
+|---|---|---|
+| Plugin node `type` (in `<plugin>.py`) | camelCase | `stripeAction` |
+| `server/nodes/visuals.json` key | camelCase (= node type) | `"stripeAction": { "icon": "asset:stripe", ... }` |
+| `server/services/ai.py` `DEFAULT_TOOL_NAMES` value | snake_case (LLM tool name) | `"stripeAction": "stripe_action"` |
+| Skill `allowed-tools` | snake_case (matches the LLM tool name) | `allowed-tools: "stripe_action"` |
+
+The skill resolver (`SkillLoader._parse_skill_metadata`) takes each `allowed-tools` token, runs snake→camel (`stripe_action` → `stripeAction`), and looks it up in `visuals.json`. If the conversion doesn't equal the node type, no icon resolves and the skill renders without one.
+
+**Common pitfall:** picking a "creative" LLM tool name that doesn't snake-back to the node type. For example, calling a `stripeAction` node's tool `stripe_cli` (because it wraps a CLI) breaks the convention — `stripe_cli` snakes to `stripeCli`, not `stripeAction`, so `visuals.json` lookup fails. Stick to `<node_type_in_snake_case>` unless you're prepared to also add an alias entry to `visuals.json`.
+
## Optional Supporting Files
Skills can include additional files that are loaded alongside the main instructions:
diff --git a/server/skills/payments_agent/stripe-skill/SKILL.md b/server/skills/payments_agent/stripe-skill/SKILL.md
new file mode 100644
index 00000000..1564025a
--- /dev/null
+++ b/server/skills/payments_agent/stripe-skill/SKILL.md
@@ -0,0 +1,306 @@
+---
+name: stripe-skill
+description: Process payments, manage customers, issue refunds, and handle subscriptions via the Stripe CLI. Pass any Stripe command (customers, charges, payment_intents, refunds, invoices, products, prices, subscriptions) and the tool runs it for you and returns parsed JSON.
+allowed-tools: "stripe_action"
+metadata:
+ author: machina
+ version: "1.0"
+ category: payments
+
+---
+
+# Stripe Skill
+
+Pass-through over the official [Stripe CLI](https://stripe.com/docs/cli).
+The tool runs `stripe <command> --api-key <stored-key>` for you and
+returns parsed JSON. Every Stripe resource the CLI supports works
+without code changes — products and prices created tomorrow work the
+same way.
+
+## Tool: stripe_action
+
+Single field: `command` — a string identical to what you would type
+after `stripe ` on the terminal.
+
+### Schema
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| command | string | Yes | Stripe CLI command (e.g. `"customers create --email [email protected]"`). Quote arguments that contain spaces. |
+
+### Response
+
+```json
+{
+ "command": "customers create --email [email protected]",
+ "success": true,
+ "result": {
+ "id": "cus_NkXz123",
+ "email": "[email protected]",
+ "object": "customer",
+ "created": 1730000000,
+ ...
+ },
+ "stdout": "<raw CLI stdout>"
+}
+```
+
+On CLI failure the tool raises an error with Stripe's own message
+(e.g. `"No such customer: cus_invalid"`).
+
+## Common commands
+
+### Customers
+
+| Command | Purpose |
+|---|---|
+| `customers create --email <addr>` | Create a customer. Optional: `--name`, `--description`, `--phone`, `--metadata key=val`. |
+| `customers retrieve <cus_id>` | Fetch a customer by id. |
+| `customers list --limit 10` | List recent customers. Optional: `--email <addr>` filter. |
+| `customers update <cus_id> --email <new>` | Update fields on a customer. |
+| `customers delete <cus_id>` | Permanently delete a customer. |
+
+Search:
+
+| Command | Purpose |
+|---|---|
+| `customers search --query "email:'[email protected]'"` | Server-side search across customers. Stripe Search query syntax. |
+
+### PaymentIntents (recommended for charges)
+
+| Command | Purpose |
+|---|---|
+| `payment_intents create --amount 2000 --currency usd` | Create a PaymentIntent for $20.00. Amount is in the smallest currency unit (cents for USD). |
+| `payment_intents create --amount 2000 --currency usd --customer cus_123` | Create attached to a saved customer. |
+| `payment_intents create --amount 2000 --currency usd --confirm --payment-method pm_card_visa` | Create + confirm in one shot (most common test path). |
+| `payment_intents retrieve pi_123` | Fetch by id. |
+| `payment_intents list --limit 20` | List recent intents. |
+| `payment_intents cancel pi_123` | Cancel an unconfirmed or processing intent. |
+
+### Charges (legacy direct-charge path)
+
+| Command | Purpose |
+|---|---|
+| `charges retrieve ch_123` | Fetch a charge by id. |
+| `charges list --limit 10` | List recent charges. |
+| `charges list --customer cus_123` | List charges for a specific customer. |
+
+For new integrations prefer **PaymentIntents** over direct
+`charges create` — Stripe deprecated raw card-token charge creation.
+
+### Refunds
+
+| Command | Purpose |
+|---|---|
+| `refunds create --payment-intent pi_123` | Refund a PaymentIntent in full. |
+| `refunds create --payment-intent pi_123 --amount 500` | Partial refund (in smallest currency unit). |
+| `refunds create --charge ch_123` | Refund by charge id (older flow). |
+| `refunds retrieve re_123` | Fetch a refund by id. |
+| `refunds list --limit 10` | List recent refunds. |
+
+### Invoices & Subscriptions
+
+| Command | Purpose |
+|---|---|
+| `invoices create --customer cus_123` | Draft an invoice. |
+| `invoices finalize_invoice in_123` | Finalize a draft (locks for sending/charging). |
+| `invoices pay in_123` | Charge the customer for a finalized invoice. |
+| `invoices list --customer cus_123` | List invoices for a customer. |
+| `subscriptions create --customer cus_123 --items='[{"price":"price_xxx"}]'` | Create a subscription. |
+| `subscriptions retrieve sub_123` | Fetch a subscription. |
+| `subscriptions cancel sub_123` | Cancel immediately. |
+| `subscriptions update sub_123 --cancel-at-period-end true` | Cancel at end of current billing period. |
+
+### Products & Prices
+
+| Command | Purpose |
+|---|---|
+| `products create --name "Pro Plan"` | Create a product. |
+| `prices create --product prod_123 --unit-amount 2000 --currency usd --recurring='{"interval":"month"}'` | Create a recurring price tied to a product. |
+| `prices list --product prod_123` | List prices for a product. |
+
+### Trigger (synthetic test events)
+
+| Command | Purpose |
+|---|---|
+| `trigger payment_intent.succeeded` | Fire a synthetic PaymentIntent succeeded event. |
+| `trigger charge.refunded` | Fire a synthetic refund event. |
+| `trigger customer.subscription.created` | Fire a synthetic subscription event. |
+
+`stripe trigger` is invaluable for testing webhook flows — it sends
+the event to Stripe, which sends it back through the same `stripe
+listen` daemon and into your `stripeReceive` trigger node.
+
+## Common workflows
+
+### Create a customer and charge them
+
+```json
+{ "command": "customers create --email [email protected] --name 'Rosy Sparrow'" }
+```
+returns `cus_…`. Then:
+```json
+{ "command": "payment_intents create --amount 2000 --currency usd --customer cus_xxx --payment-method pm_card_visa --confirm" }
+```
+
+### Refund the most recent payment for a customer
+
+```json
+{ "command": "payment_intents list --customer cus_123 --limit 1" }
+```
+read `data[0].id`, then:
+```json
+{ "command": "refunds create --payment-intent pi_xxx" }
+```
+
+### Set up a recurring subscription
+
+```json
+{ "command": "products create --name 'Pro Plan'" } -> prod_xxx
+{ "command": "prices create --product prod_xxx --unit-amount 2000 --currency usd --recurring='{\"interval\":\"month\"}'" } -> price_xxx
+{ "command": "subscriptions create --customer cus_xxx --items='[{\"price\":\"price_xxx\"}]'" }
+```
+
+## Quoting and escaping
+
+The `command` string is parsed with `shlex.split` before being handed
+to `stripe`. Use single quotes for arguments that contain spaces:
+
+| You want to send | Type this in `command` |
+|---|---|
+| `--name=Acme Inc` | `customers create --name 'Acme Inc'` |
+| metadata with spaces | `customers update cus_x --metadata 'plan=Acme Pro'` |
+| a JSON array as a flag value | `subscriptions create --items='[{"price":"price_xxx"}]'` |
+
+JSON inside `--items` / `--recurring` etc. should be a single quoted
+JSON string with no internal spaces — the CLI parses it on the
+server side.
+
+## Idempotency
+
+For any create/charge that you don't want to duplicate on retry, add
+an idempotency key:
+
+```
+customers create --email [email protected] -H "Idempotency-Key: order_42_user_7"
+```
+
+The CLI accepts custom headers via `-H`. Stripe deduplicates by the
+key for 24 hours.
+
+## Test mode vs live mode
+
+The stored API key (set in the Credentials Modal) determines mode:
+
+| Key prefix | Mode | Effect |
+|---|---|---|
+| `sk_test_…` | Test | Fake money, fake events, no real charges. Always use this for development. |
+| `sk_live_…` | Live | Real money. Real customers. Use only after thorough testing. |
+| `rk_test_…` / `rk_live_…` | Restricted | Scoped permissions; recommended for production agents that don't need full account access. |
+
+The CLI reports `livemode: true/false` on every response object so
+you can verify which environment a result is from.
+
+## Errors
+
+Stripe returns structured errors that surface in the tool's error
+field. Common ones:
+
+| Error code | Meaning | Recovery |
+|---|---|---|
+| `resource_missing` | The id you passed doesn't exist | Verify the id; list to find the right one |
+| `card_declined` | Card payment failed | Use a different `--payment-method`; in test mode try `pm_card_visa` |
+| `invalid_request_error` | Wrong / missing argument | Check `stripe <resource> create --help` |
+| `authentication_required` | 3DS challenge needed | Use a setup_intent or off-session payment_method |
+| `rate_limit_error` | Too many requests | Pause and retry; Stripe rate limit is 100/sec in live, 25/sec in test |
+
+The CLI's stderr always contains the Stripe request id (`req_…`) —
+include it when reporting issues.
+
+## Webhooks (`stripeReceive` trigger)
+
+When the Stripe daemon is connected (Credentials Modal → Stripe →
+Connect), every event Stripe sends is forwarded to MachinaOs and
+delivered to any active `stripeReceive` trigger nodes after
+HMAC-SHA256 signature verification (`Stripe-Signature` header).
+
+To test event delivery without making real payments, use the
+`trigger` command above. Events fire through the same path as real
+ones.
+
+Filters on the trigger node (`event_type_filter`):
+
+| Filter | Matches |
+|---|---|
+| `all` | every event |
+| `charge.succeeded` | exact match |
+| `charge.*` | every charge.* event (succeeded, refunded, failed, …) |
+| `payment_intent.*` | every PaymentIntent event |
+
+The trigger output mirrors Stripe's event shape: `event_id`,
+`event_type`, `created`, `livemode`, `api_version`, `request_id`,
+`account`, `data`.
+
+## Authentication — `stripe login` (browser OAuth)
+
+Authentication is delegated entirely to the Stripe CLI. There is no
+API key to paste into MachinaOs. The Credentials Modal's **Login
+with Stripe** button drives the CLI's two-step machine-friendly
+login:
+
+1. **Browser-side**: the modal opens
+ `https://dashboard.stripe.com/stripecli/auth/...` in a new tab and
+ shows a verification code. The user signs in to Stripe and
+ confirms the code.
+2. **CLI-side**: the CLI polls Stripe until the user authorises,
+ then writes credentials (one restricted key per mode, valid for
+ 90 days) to `~/.config/stripe/config.toml` (or
+ `$XDG_CONFIG_HOME/stripe/config.toml`).
+3. **MachinaOs-side**: when login completes, the listen daemon
+ starts automatically and captures the webhook signing secret.
+
+After login, every `stripe …` command run via this tool reads its
+credentials from the CLI's config file — no `--api-key` flag in any
+command you'd type.
+
+**Logout** (Credentials Modal → Disconnect) stops the listen daemon
+and runs `stripe logout --all` to clear the config file.
+
+## Best practices
+
+1. **Restricted keys are auto-issued.** When you `stripe login`, the
+ CLI generates restricted keys with CLI-appropriate scopes (one
+ per test/live mode) — you don't pick scopes manually.
+2. **Default to test mode** for development. The CLI distinguishes
+ modes; `livemode: true/false` is on every response.
+3. **Add idempotency keys to all create operations.** Especially for
+ charges and refunds — accidental retry without a key duplicates
+ the charge.
+4. **Quote string arguments with spaces** (`--name 'Acme Inc'`).
+5. **Use PaymentIntents, not raw charges** for new integrations.
+6. **Surface Stripe error messages verbatim to the user.** They are
+ precise and actionable; don't paraphrase them.
+7. **Don't include `--api-key` in your `command` string.** The CLI
+ already has stored credentials; an inline `--api-key` overrides
+ them and risks key leakage in process listings and logs.
+
+## Setup checklist
+
+1. **Stripe CLI binary** — auto-downloaded on first **Login with
+ Stripe** click if not already on PATH. Resolution order:
+ - System install (`brew install stripe/stripe-cli/stripe`,
+ `scoop install stripe`, `apt install stripe`, or a direct
+ binary from <https://stripe.com/docs/stripe-cli#install>).
+ - MachinaOs workspace cache at
+ `{workspace_base}/_stripe/bin/stripe[.exe]` (populated
+ automatically from GitHub releases — pinned to a known-good
+ CLI version).
+2. Credentials Modal → Stripe → **Login with Stripe** → a browser
+ tab opens to the Stripe Dashboard with a pairing code. Authorise.
+ The modal flips to "Connected" when the CLI's `login --complete`
+ subprocess returns and the listen daemon spins up
+ (`webhook_secret_captured: true`).
+3. The `Stripe` action node is connected to your agent's
+ `input-tools` handle.
+4. (For webhook flows) A `stripeReceive` trigger node is wired into
+ your workflow with the event-type filter you care about.
diff --git a/server/tests/nodes/test_stripe_plugin.py b/server/tests/nodes/test_stripe_plugin.py
index 848eb1b7..f72a9778 100644
--- a/server/tests/nodes/test_stripe_plugin.py
+++ b/server/tests/nodes/test_stripe_plugin.py
@@ -189,7 +189,8 @@ class TestStripeActionPassthrough:
def cli_capture(self):
captured: list[list[str]] = []
- async def fake_run(*, binary, argv, credential, **kwargs):
+ async def fake_run(*, binary, argv, **kwargs):
+ # Stripe CLI uses ~/.config/stripe/config.toml — no credential injection.
captured.append(list(argv))
return {"success": True, "result": {"id": "x"}, "stdout": "{}"}
@@ -221,7 +222,7 @@ class TestStripeActionPassthrough:
def test_cli_failure_raises(self):
from nodes.stripe.stripe_action import StripeActionNode, StripeActionParams
- async def fake_fail(*, binary, argv, credential, **kwargs):
+ async def fake_fail(*, binary, argv, **kwargs):
return {"success": False, "error": "stripe: unknown command 'frobnicate'"}
with patch("nodes.stripe.stripe_action.run_cli_command", AsyncMock(side_effect=fake_fail)):
@@ -241,6 +242,7 @@ class TestStripePluginRegistration:
from services.ws_handler_registry import get_ws_handlers
registered = get_ws_handlers()
for name in (
+ "stripe_login", "stripe_logout",
"stripe_connect", "stripe_disconnect", "stripe_reconnect",
"stripe_status", "stripe_trigger",
):
@@ -261,7 +263,9 @@ class TestStripePluginRegistration:
def test_credential_registered(self):
import nodes.stripe # noqa: F401
from services.plugin.credential import CREDENTIAL_REGISTRY
- assert "stripe_api_key" in CREDENTIAL_REGISTRY
+ # Stripe CLI manages auth at ~/.config/stripe/config.toml; the
+ # credential class is a thin marker keyed by "stripe" (no api_key).
+ assert "stripe" in CREDENTIAL_REGISTRY
def test_output_schemas_registered(self):
import nodes.stripe # noqa: F401
@@ -282,4 +286,8 @@ class TestStripePluginRegistration:
src = get_listen_source()
assert src.process_name == "stripe-listen"
assert src.workflow_namespace == "_stripe"
- assert src.binary_name == "stripe"
+ # Empty binary_name disables the framework's PATH check; the
+ # plugin resolves the binary itself via ensure_stripe_cli (which
+ # falls back to a workspace-local download on systems without
+ # a system install of the Stripe CLI).
+ assert src.binary_name == ""