Skip to content

Self-improving AI Employees for everyone

feat(vercel): Vercel CLI plugin — deploy/inspect/list node with device-flow login

trohitg06e14c714d99
diff --git a/CLAUDE.md b/CLAUDE.md
index 3c9a8184..04599b67 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -27,6 +27,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[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 — `stripeAction` (CLI pass-through) + `stripeReceive` (signed-webhook trigger). Reference plugin for the Wave 12 event framework AND the **CLI-managed-auth pattern**: browser OAuth via `stripe login --non-interactive` + `--complete <url>` (URL extracted from `next_step` shell command via `shlex.split`) + auto-installed binary (`ensure_stripe_cli` from GitHub releases) + marker-token reuse of `auth_service.store_oauth_tokens` + CloudEvents-shaped `broadcast_credential_event("credential.oauth.connected" \| ".disconnected", provider=...)` — zero per-provider hardcoding in the frontend. Daemon stdout/stderr ingested via `ProcessService`'s `line_handler` callback (no log-file tailing); credential gate routed through `await self.has_credential()` so non-api-key auth (`is_logged_in()`) plugs in via subclass override. |
+| **[Vercel Service](./docs-internal/vercel_service.md)** | Vercel CLI integration — `vercelAction` (deploy / inspect / list + `custom` CLI passthrough; AI tool `vercel`). Second reference for the CLI-managed-auth pattern: the **device-flow variant** (`vercel login` is one blocking process — no two-step `--complete`; direct `create_subprocess_exec` + chunk-based banner read for the code-embedding URL, pumps drain pipes for the process lifetime, success gate = auth.json mtime advance + sniff). Dual auth: optional `vercel_token` field (injected as `VERCEL_TOKEN` env, never argv) OR CLI login with marker tokens. All invocations pin `--global-config <DATA_DIR>/vercel/` (the `CLAUDE_CONFIG_DIR` isolation idiom). npm install into the shared packages tree (pinned version). First-deploy project guard raises `NodeUserError` instead of letting Vercel derive an invalid name from the workspace dir. Shipped with the generic OAuthConnect change: Login gates on **required** fields only, so optional fields never block CLI login. |
| **[CI/CD Pipeline](./docs-internal/ci_cd.md)** | GitHub Actions workflows, predeploy validation, release publishing, and composite setup action |
| **[Performance](./docs-internal/performance.md)** | Cold-start measurements (Application startup complete 2.90 s warm, first WS connect 8.29 s) + per-phase timeline + optimisation history (lazy LangChain imports, esbuild sidecar bundle, scoped `compileall`, PartySocket reconnect, TanStack Query auth bootstrap, `manualChunks`) + bottleneck inventory + reproduction commands + anti-patterns to never reintroduce. Pairs with the build-time pipeline doc below. |
| **[Release Build Pipeline](./docs-internal/release_build_pipeline.md)** | npm-distribution build pipeline: `tsgo` for type-check (5× faster than tsc), Vite `manualChunks` + `target: 'es2022'`, esbuild Node.js sidecar bundle (drops `tsx` interpreter cost), `python -O -m compileall` for project-source bytecode (excludes `.venv/`, `tests/`). Single source of truth for the bytecode-compile path list: `machina.commands.build.COMPILEALL_SOURCE_DIRS`. |
@@ -489,7 +490,7 @@ class CacheEntry(SQLModel, table=True):
## Codebase Summary
- **Hybrid architecture**: Python (FastAPI + Pydantic plugins) + React/TypeScript frontend + Node.js subprocess for JS/TS code execution.
-- **Backend NodeSpec is the single source of truth.** Plugins live in [`server/nodes/<group>/<name>.py`](./server/nodes/) and auto-register via `BaseNode.__init_subclass__`. Authoritative node count is whatever globs out of `server/nodes/**/*.py` (excluding `_*.py` helpers and `__init__.py`); folders cover agent / model / android / google / whatsapp / twitter / telegram / social / email / search / scraper / document / code / filesystem / proxy / location / chat / text / scheduler / trigger / tool / utility / workflow / skill / browser / stripe.
+- **Backend NodeSpec is the single source of truth.** Plugins live in [`server/nodes/<group>/<name>.py`](./server/nodes/) and auto-register via `BaseNode.__init_subclass__`. Authoritative node count is whatever globs out of `server/nodes/**/*.py` (excluding `_*.py` helpers and `__init__.py`); folders cover agent / model / android / google / whatsapp / twitter / telegram / social / email / search / scraper / document / code / filesystem / proxy / location / chat / text / scheduler / trigger / tool / utility / workflow / skill / browser / stripe / vercel.
- **WebSocket-first frontend-backend communication.** Authoritative handler count is the size of the `MESSAGE_HANDLERS` dict in [`server/routers/websocket.py`](./server/routers/websocket.py) plus plugin-registered handlers via `services.ws_handler_registry`. Don't hand-maintain the count in this doc — it drifts on every plugin add.
- **Plugin-first architecture (Wave 11).** One file = one node. `services/handlers/` shrank from 12.8K → 1.1K LOC across 16 → 4 files. Live invariant total via `pytest --collect-only`.
@@ -612,7 +613,7 @@ The project uses WebSocket as the primary communication method between frontend
> The authoritative, per-node reference is the backend plugin registry plus the per-node "logic-flow" cards under [docs-internal/node-logic-flows/](./docs-internal/node-logic-flows/) (one card per node, grouped by category, with handles / params / outputs / side-effects / edge-cases). Live node list = the plugin registry (one folder per node under `server/nodes/<group>/`, ~118 node types today; a bare `__init__.py` glob also counts the 26 group packages); live total via `pytest --collect-only`. Do NOT maintain a per-node catalogue here — it drifts on every plugin add.
-Node groups (palette categories): agent, model, skill, tool, trigger, workflow, search, google, android, whatsapp, telegram, twitter, social, email, proxy, chat, scheduler, text, code, document, location, utility, browser, scraper, filesystem, stripe. See [docs-internal/node-logic-flows/](./docs-internal/node-logic-flows/) for the card index.
+Node groups (palette categories): agent, model, skill, tool, trigger, workflow, search, google, android, whatsapp, telegram, twitter, social, email, proxy, chat, scheduler, text, code, document, location, utility, browser, scraper, filesystem, stripe, vercel. See [docs-internal/node-logic-flows/](./docs-internal/node-logic-flows/) for the card index.
## Backend Services
diff --git a/client/src/assets/icons/index.ts b/client/src/assets/icons/index.ts
index 6596bf1d..53008998 100644
--- a/client/src/assets/icons/index.ts
+++ b/client/src/assets/icons/index.ts
@@ -48,6 +48,7 @@ import Kimi from '@lobehub/icons/es/Kimi';
import Mistral from '@lobehub/icons/es/Mistral';
import Ollama from '@lobehub/icons/es/Ollama';
import LmStudio from '@lobehub/icons/es/LmStudio';
+import Vercel from '@lobehub/icons/es/Vercel';
type RawSvg = string;
@@ -152,6 +153,7 @@ const LOBEHUB_BRANDS: Readonly<Record<string, any>> = {
mistral: Mistral,
ollama: Ollama,
lmstudio: LmStudio,
+ vercel: Vercel,
};
const ICON_LIBRARIES: Readonly<Record<string, LibraryResolver>> = {
diff --git a/client/src/components/credentials/primitives/OAuthConnect.tsx b/client/src/components/credentials/primitives/OAuthConnect.tsx
index 31650fea..34fc147e 100644
--- a/client/src/components/credentials/primitives/OAuthConnect.tsx
+++ b/client/src/components/credentials/primitives/OAuthConnect.tsx
@@ -40,18 +40,21 @@ const OAuthConnect: React.FC<Props> = ({
}) => {
// Some providers (e.g. Stripe) delegate auth entirely to an external
// CLI tool — they have no MachinaOs-side credentials to paste, so
- // there's nothing to "store" before Login is meaningful.
- const hasFields = !!config.fields?.length;
+ // there's nothing to "store" before Login is meaningful. Only
+ // *required* fields gate the Login button: optional fields are an
+ // alternative auth path, not a prerequisite (e.g. Vercel's access
+ // token alongside its CLI device-flow login).
+ const hasRequiredFields = !!config.fields?.some((f) => f.required);
const statusRows: StatusRowDef[] = [
{ label: 'Status', ok: () => connected, trueText: 'Connected', falseText: 'Not Connected' },
- ...(hasFields
+ ...(hasRequiredFields
? [{ label: 'Credentials', ok: () => stored, trueText: 'Configured', falseText: 'Not configured' } as StatusRowDef]
: []),
];
const actions: ActionDef[] = [
- { key: 'login', label: `Login with ${config.name}`, intent: 'save', onClick: onLogin, disabled: hasFields && !stored, hidden: connected },
+ { key: 'login', label: `Login with ${config.name}`, intent: 'save', onClick: onLogin, disabled: hasRequiredFields && !stored, hidden: connected },
{ key: 'logout', label: 'Disconnect', intent: 'stop', onClick: onLogout, hidden: !connected },
{ key: 'refresh', label: 'Refresh', intent: 'save', onClick: onRefresh, icon: <RotateCcw className="h-4 w-4" /> },
];
@@ -96,7 +99,7 @@ const OAuthConnect: React.FC<Props> = ({
? config.account_label
? `Connected as ${config.account_label}.`
: `Your ${config.name} account is connected.`
- : (stored || !hasFields)
+ : (stored || !hasRequiredFields)
? 'Click Login to authorize.'
: 'Enter your credentials above to get started.'}
</div>
diff --git a/docs-internal/node_creation.md b/docs-internal/node_creation.md
index 440e6fa1..248245ac 100644
--- a/docs-internal/node_creation.md
+++ b/docs-internal/node_creation.md
@@ -17,7 +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 |
+| A plugin whose auth is owned by an external CLI (`stripe login`, `vercel 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); [Vercel Service](./vercel_service.md) for the **device-flow** variant (single blocking `login` process, no two-step complete flag) | 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
@@ -153,6 +153,26 @@ browser-OAuth" plugin lands as a self-contained folder under
`server/config/credential_providers.json` and zero touches outside
the folder.
+**Device-flow variant (Vercel).** Not every CLI exposes Stripe's
+machine-friendly two-step (`--non-interactive` → `--complete <url>`).
+`vercel login` is a single **blocking** OAuth device flow: it prints a
+verification URL, then polls until the browser auth completes. The
+login handler therefore cannot use `run_cli_command` (which buffers
+output until process exit) — it spawns the CLI directly with
+`asyncio.create_subprocess_exec` (`stdin=PIPE` left un-written, the
+claude-login EOF guard), reads stdout+stderr in chunks until the URL
+appears (chunk-based, not `readline()` — spinner `\r` frames overrun
+the line limit; pumps keep draining for the process lifetime so the
+pipe buffer never fills), returns `{success, url}` immediately, and a
+background task awaits exit. Success gate is the same mtime-advance +
+sniff pair, against a **pinned config dir**: every invocation passes
+`--global-config <DATA_DIR>/vercel/` (the `CLAUDE_CONFIG_DIR`
+isolation idiom) so the auth-file path is deterministic across
+platforms. The installer is `npm install <pkg> --prefix
+<packages_dir()>` into the shared npm tree instead of a GitHub-release
+download. Reference: [`server/nodes/vercel/`](../server/nodes/vercel/)
++ [vercel_service.md](./vercel_service.md).
+
## What auto-wires (don't write it yourself)
When a plugin file is imported (which the `nodes/__init__.py`
diff --git a/docs-internal/vercel_service.md b/docs-internal/vercel_service.md
new file mode 100644
index 00000000..f4f2e236
--- /dev/null
+++ b/docs-internal/vercel_service.md
@@ -0,0 +1,142 @@
+# Vercel Service
+
+Self-contained plugin at [`server/nodes/vercel/`](../server/nodes/vercel/)
+wrapping the official **Vercel CLI** (npm package `vercel`, pinned in
+`_install.py`). One dual-purpose node — `vercelAction` (workflow node +
+AI tool `vercel`) — with four operations: `deploy`, `inspect`, `list`,
+and a `custom` raw-command passthrough (the Stripe passthrough idiom, so
+env vars / logs / rollback / promote / domains / aliases / projects all
+work without additional code). No trigger node in v1: the Vercel CLI
+has no `listen`-style daemon; a `vercelReceive` (account webhooks or
+`vercel ls` polling) is a documented follow-up.
+
+It is the second in-repo reference for the **CLI-managed-auth
+pattern** (see [node_creation.md → CLI-managed auth](./node_creation.md)
+and [stripe_service.md](./stripe_service.md)) — specifically the
+**device-flow variant**, where the CLI's login is a single blocking
+process rather than Stripe's two-step `--non-interactive` /
+`--complete <url>` pair.
+
+## File map
+
+| File | Role |
+|---|---|
+| `__init__.py` | Wiring only: `register_ws_handlers(WS_HANDLERS)` + `register_output_schema("vercelAction", VercelActionOutput)`; node class auto-registers on import |
+| `vercel_action.py` | `VercelActionNode(ActionNode)`, `usable_as_tool=True`, `tool_name="vercel"`, gmail-style multi-`@Operation` dispatch on `operation: Literal["deploy","inspect","list","custom"]` |
+| `_handlers.py` | `vercel_login` / `vercel_logout` / `vercel_status` WS handlers; device-flow driver; marker-token write + `broadcast_credential_event` |
+| `_service.py` | Config-dir pinning, `is_logged_in()` sniff, `global_argv()` / `vercel_env()` builders, ANSI-strip + login-URL/code parsers |
+| `_install.py` | `ensure_vercel_cli()` — pinned `npm install vercel@<X>` into the shared npm tree (`<DATA_DIR>/packages/`); system PATH preferred; one-shot `telemetry disable` post-install |
+| `_credentials.py` | `VercelCredential(Credential)` thin marker (`auth="custom"`); `resolve()` returns the optional `vercel_token` api-key row |
+| `meta.json` | Node color. **No co-located `icon.svg`** — the icon is the official brand glyph via `visuals.json: {"vercelAction": {"icon": "lobehub:Vercel", "skill": "vercel-skill"}}`; a folder SVG would silently override it (first hit in `get_plugin_icon_path`), and its absence is locked by `test_vercel_plugin.py::test_plugin_folder_assets` |
+
+Paired skill: [`server/skills/vercel/vercel-skill/SKILL.md`](../server/skills/vercel/vercel-skill/SKILL.md)
+(auto-attached when the tool connects to an agent, via the
+`visuals.json` skill map).
+
+## Auth — two independent paths
+
+Either path is sufficient; the token wins when both exist.
+
+1. **Access token** (headless-safe): the catalogue entry declares one
+ `fields` row, `vercel_token` with `"required": false`. Stored as a
+ plain api-key row; injected as the **`VERCEL_TOKEN` env var** on
+ every invocation — never argv, so it stays out of process lists.
+2. **CLI login** (browser device flow): `vercel_login` spawns
+ `vercel login` directly with `asyncio.create_subprocess_exec`
+ (`stdin=PIPE` left un-written — the claude-login EOF guard).
+ `run_cli_command` is unusable here: it buffers via `communicate()`
+ until exit, and the device flow blocks for up to 10 minutes while
+ the URL is needed immediately. The banner reader is **chunk-based**
+ (`stream.read(4096)`, not `readline()` — spinner `\r` repaints
+ overrun the StreamReader line limit) and its pumps deliberately
+ outlive the handler, draining both pipes for the process lifetime
+ so the CLI never blocks on a full pipe buffer. The first
+ code-embedding URL is returned as `{success, url,
+ verification_code}` — the frontend only opens `url`
+ (`useCredentialPanel.oauthLogin`), so the URL must carry the code.
+ A background task (strong-ref'd — asyncio holds only weak refs)
+ awaits process exit; the success gate is **`auth.json` mtime
+ advanced past the pre-login snapshot AND `is_logged_in()`** (exit
+ codes are not trusted; Stripe precedent). On success the handler
+ writes the `cli-managed` marker OAuth tokens and broadcasts
+ `credential.oauth.connected`.
+
+### Config-dir pinning
+
+Every invocation appends `--global-config <DATA_DIR>/vercel/` (plus
+`--no-color`; env gets `NO_COLOR=1`). The CLI's default
+`com.vercel.cli` location varies wildly by OS — pinning makes the
+`auth.json` sniff deterministic and isolates MachinaOs-managed auth
+from the user's own system `vercel login` (the
+`CLAUDE_CONFIG_DIR = data_path("claude")` idiom). The path is composed
+inline in `_service.vercel_config_dir()` per the `core.paths` rule.
+
+### Credentials modal
+
+Catalogue entry (`server/config/credential_providers.json`):
+`kind:"oauth"`, category `deployment` (new, order 10), **no
+`status_hook`** — the marker tokens satisfy the plain `kind=="oauth"`
+stored-derivation in `handle_get_credential_catalogue`, and the
+`connected` badge falls back to `config.stored` in `OAuthPanel`.
+`icon_ref: "lobehub:Vercel"` (official brand icon; registered in
+`client/src/assets/icons/index.ts` `LOBEHUB_BRANDS`).
+
+**Frontend gating change that shipped with this plugin**:
+`OAuthConnect.tsx` now gates the Login button on **required** fields
+only (`config.fields?.some(f => f.required)`), so Vercel's optional
+token field renders without blocking Login. Existing providers are
+unchanged (Google/Twitter/Telegram all declare `required: true` on
+their gating fields).
+
+## Operations
+
+| Op | argv shape | Notes |
+|---|---|---|
+| `deploy` | `deploy --yes [--prod] [--prebuilt] [--archive=tgz] [--project X] [--scope X] <extra_args>` | cwd = `path` param (relative → resolved against `ctx.workspace_dir`) or the workspace itself; **stdout carries only the deployment URL** (progress → stderr), returned as `url`; 600 s timeout |
+| `inspect` | `inspect <deployment> [--logs] [--wait [--timeout T]]` | 300 s subprocess timeout when `--wait`, else 60 s |
+| `list` | `list [project] [--prod] [--status S] --yes` | Human table in `stdout` (no `--json` upstream) |
+| `custom` | `<command verbatim, shlex-split>` | cwd = workspace when present; JSON-capable commands (`logs --json`, `project ls --format=json`) come back parsed in `result` |
+
+Shared per-op plumbing: `_preflight()` (no token AND not logged in →
+`PermissionError` annotated `provider="vercel" / reason="missing" /
+auth="oauth2"`, which produces the credential envelope + the
+`credential.oauth.runtime_failed` broadcast) → `ensure_vercel_cli()` →
+`run_cli_command(..., env=vercel_env(token), cwd=...)` → non-zero exit
+→ `NodeUserError` carrying the stderr tail (user/LLM-correctable, one
+WARN line, no traceback).
+
+**First-deploy project guard**: an unlinked deploy (no `project`
+param, no `.vercel/project.json` in the cwd, no `VERCEL_PROJECT_ID`,
+no `--project` in `extra_args`) raises a `NodeUserError` up front with
+the remediation, instead of letting Vercel derive a project name from
+the cwd — workflow workspace dirs (`AI_Assistant_1`) violate Vercel's
+lowercase naming rules and would 400 only **after** the upload. No
+name is invented and no naming rules are re-implemented — Vercel stays
+the authority; the LLM/user supplies a valid name and retries.
+
+## Framework touch (one)
+
+`run_cli_command` (`server/services/events/cli.py`) gained a
+`cwd: Optional[str] = None` kwarg (keyword-only, backward compatible)
+— deploys are directory-scoped.
+
+## Tests
+
+[`server/tests/test_vercel_plugin.py`](../server/tests/test_vercel_plugin.py):
+argv builders per operation (`--global-config` + `--yes` presence,
+token → env not argv), device-flow banner parsing against recorded
+fixtures (ANSI included), marker-token flip + catalogue broadcast,
+install-path resolution, `PermissionError` annotation attrs, the
+first-deploy project guard, catalogue-entry shape (`required: false`
+on the token field), and the no-folder-icon contract. The generic
+`test_plugin_contract.py` / `test_plugin_self_containment.py`
+invariants pick the plugin up automatically.
+
+## Runtime caveat
+
+The device-flow banner format is parsed from the pinned CLI version's
+output; Vercel changed login flows in early 2026 (email / `--github` /
+`--oob` removed). If the URL regex ever misses, `vercel_login` returns
+the raw CLI output lines in `error` so the failure is diagnosable from
+the modal. Re-verify against `vercel login --help` when bumping the
+pinned version.
diff --git a/server/config/credential_providers.json b/server/config/credential_providers.json
index 6eac0df8..c26b061a 100644
--- a/server/config/credential_providers.json
+++ b/server/config/credential_providers.json
@@ -12,7 +12,8 @@
"search": { "label": "Search", "order": 6 },
"scrapers": { "label": "Scrapers", "order": 7 },
"services": { "label": "Services", "order": 8 },
- "payments": { "label": "Payments", "order": 9 }
+ "payments": { "label": "Payments", "order": 9 },
+ "deployment": { "label": "Deployment", "order": 10 }
},
"providers": {
@@ -503,6 +504,32 @@
"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)."
+ },
+
+ "vercel": {
+ "name": "Vercel",
+ "category": "deployment",
+ "category_label": "Deployment",
+ "color": "dracula.cyan",
+ "kind": "oauth",
+ "icon_ref": "lobehub:Vercel",
+ "ws": {
+ "login": "vercel_login",
+ "logout": "vercel_logout",
+ "status": "vercel_status"
+ },
+ "fields": [
+ {
+ "key": "vercel_token",
+ "label": "Access Token (optional)",
+ "type": "password",
+ "secret": true,
+ "placeholder": "vcp_...",
+ "required": false,
+ "help": "Create at vercel.com/account/tokens. Used headless as VERCEL_TOKEN on every CLI call and takes precedence over CLI login. The Login button works without it."
+ }
+ ],
+ "instructions": "Two independent auth paths: click 'Login with Vercel' for the browser device flow (the CLI is auto-installed via npm and stores its auth state under MachinaOs's data directory), or paste an access token above for headless use."
}
}
}
diff --git a/server/nodes/README.md b/server/nodes/README.md
index 9f7f9f18..94ddfb88 100644
--- a/server/nodes/README.md
+++ b/server/nodes/README.md
@@ -125,6 +125,8 @@ utility/ — console / httpRequest / webhookResponse / processManager / team
workflow/ — start
skill/ — simpleMemory / masterSkill
browser/ — browser (agent-browser CLI)
+stripe/ — Stripe (CLI passthrough action + signed-webhook trigger)
+vercel/ — Vercel (CLI deploy / inspect / list / custom passthrough)
```
---
diff --git a/server/nodes/groups.py b/server/nodes/groups.py
index 0ad96ad9..b1f08144 100644
--- a/server/nodes/groups.py
+++ b/server/nodes/groups.py
@@ -50,6 +50,7 @@ register_group(key="proxy", metadata={"label": "Proxy", "icon": "🛡", "color":
register_group(key="whatsapp", metadata={"label": "WhatsApp", "icon": "💬", "color": "#25D366", "visibility": "dev"})
register_group(key="email", metadata={"label": "Email", "icon": "✉️", "color": "#8be9fd", "visibility": "dev"})
register_group(key="payments", metadata={"label": "Payments", "icon": "asset:stripe", "color": "#635BFF", "visibility": "dev"})
+register_group(key="deployment", metadata={"label": "Deployment", "icon": "lobehub:Vercel", "color": "#666666", "visibility": "dev"})
register_group(key="browser", metadata={"label": "Browser", "icon": "🌐", "color": "#ff79c6", "visibility": "dev"})
register_group(key="scraper", metadata={"label": "Scrapers", "icon": "🕸", "color": "#ff79c6", "visibility": "dev"})
register_group(key="filesystem", metadata={"label": "Filesystem", "icon": "📁", "color": "#8be9fd", "visibility": "dev"})
diff --git a/server/nodes/vercel/__init__.py b/server/nodes/vercel/__init__.py
new file mode 100644
index 00000000..d0be5364
--- /dev/null
+++ b/server/nodes/vercel/__init__.py
@@ -0,0 +1,26 @@
+"""Plugins for the 'deployment' palette group — Vercel.
+
+Self-contained CLI-managed-auth plugin (stripe shape, minus the
+daemon/webhook surface — the Vercel CLI has no ``listen`` equivalent).
+This package contributes only the Vercel-specific shapes: the action
+node with its argv builders, the device-flow login driver, the config
+pinning helpers, and the credential class.
+"""
+
+from __future__ import annotations
+
+from services.node_output_schemas import register_output_schema
+from services.ws_handler_registry import register_ws_handlers
+
+from ._credentials import VercelCredential
+from ._handlers import WS_HANDLERS
+from .vercel_action import VercelActionNode, VercelActionOutput
+
+register_ws_handlers(WS_HANDLERS)
+register_output_schema("vercelAction", VercelActionOutput)
+
+__all__ = [
+ "VercelCredential",
+ "VercelActionNode",
+ "WS_HANDLERS",
+]
diff --git a/server/nodes/vercel/_credentials.py b/server/nodes/vercel/_credentials.py
new file mode 100644
index 00000000..cedfe7cc
--- /dev/null
+++ b/server/nodes/vercel/_credentials.py
@@ -0,0 +1,36 @@
+"""Vercel credential — thin marker (stripe idiom).
+
+Two independent auth paths, either is sufficient:
+
+* **CLI login** — ``vercel login`` (browser device flow) driven by the
+ ``vercel_login`` WS handler; the CLI stores its own auth state in the
+ MachinaOs-pinned ``--global-config`` dir (``<DATA_DIR>/vercel/``),
+ and a synthetic marker OAuth token flips the catalogue's ``stored``
+ flag.
+* **Access token** — the optional ``vercel_token`` api-key row, pasted
+ in the credentials modal and injected as the ``VERCEL_TOKEN`` env var
+ on every CLI invocation (token takes precedence over CLI login).
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict
+
+from services.plugin.credential import Credential
+
+
+class VercelCredential(Credential):
+ id = "vercel"
+ display_name = "Vercel"
+ category = "Deployment"
+ auth = "custom"
+ docs_url = "https://vercel.com/docs/cli"
+
+ @classmethod
+ async def resolve(cls, *, user_id: str = "owner") -> Dict[str, Any]:
+ """Return the optional access token. There is no api_key — CLI
+ login state lives in the pinned ``--global-config`` dir."""
+ from services.plugin.deps import get_auth_service
+
+ token = await get_auth_service().get_api_key("vercel_token")
+ return {"vercel_token": token} if token else {}
diff --git a/server/nodes/vercel/_handlers.py b/server/nodes/vercel/_handlers.py
new file mode 100644
index 00000000..dc3699c6
--- /dev/null
+++ b/server/nodes/vercel/_handlers.py
@@ -0,0 +1,325 @@
+"""Vercel WebSocket handlers.
+
+``vercel login`` (2026 CLI) is an OAuth **device flow**: the CLI prints
+a verification URL (+ user code) and then blocks, polling Vercel until
+the user authorises in a browser. Unlike Stripe there is no two-step
+``--non-interactive`` / ``--complete <url>`` pair, so the login handler
+cannot use :func:`run_cli_command` (it buffers output via
+``communicate()`` until process exit — the URL is needed mid-run).
+Instead it spawns the CLI directly, reads stdout/stderr incrementally
+until the URL appears, returns ``{success, url}`` to the frontend
+(which ``window.open``s the url — it never renders a separate code, so
+the url must be the code-embedding link), and lets a background task
+await process exit.
+
+Success gate mirrors Stripe's exit-code-distrust idiom: the pinned
+``auth.json`` mtime must advance past its pre-login snapshot AND
+:func:`is_logged_in` must hold. On success a synthetic marker OAuth
+token flips the catalogue's ``stored`` flag (``_cli_base`` pattern) and
+the generic catalogue-invalidation broadcast fires.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any, Dict, List, Optional
+
+from fastapi import WebSocket
+
+from core.logging import get_logger
+from services.events import run_cli_command
+
+from ._install import ensure_vercel_cli, vercel_cli_path
+from ._service import (
+ extract_login_url,
+ extract_verification_code,
+ global_argv,
+ is_logged_in,
+ stored_token,
+ strip_ansi,
+ vercel_auth_path,
+ vercel_env,
+)
+
+logger = get_logger(__name__)
+
+_LOGIN_TIMEOUT_SECONDS = 600
+# How long to wait for the device-flow URL to appear on the CLI's
+# output before giving up on this login attempt.
+_URL_DEADLINE_SECONDS = 20
+# The frontend drops WS requests after 30s (REQUEST_TIMEOUT in
+# WebSocketContext). The first-ever login pays a cold `npm install
+# vercel` inside this handler, which can blow well past that — so the
+# handler answers within this budget no matter what, and the login
+# keeps going in the background (the CLI auto-opens the browser on
+# this machine when it gets to the device-flow prompt).
+_RESPONSE_BUDGET_SECONDS = 22
+_MARKER_TOKEN = "cli-managed"
+
+
+async def _resolved_binary() -> Optional[str]:
+ """Resolve the vercel binary path, installing on first use.
+ Returns None on install failure (caller surfaces the error)."""
+ try:
+ return str(await ensure_vercel_cli())
+ except Exception as e:
+ logger.warning("[Vercel] CLI install failed: %s", e)
+ return None
+
+
+async def _mark_logged_in() -> None:
+ from services.plugin.deps import get_auth_service
+
+ await get_auth_service().store_oauth_tokens(
+ provider="vercel",
+ access_token=_MARKER_TOKEN,
+ refresh_token=_MARKER_TOKEN,
+ )
+
+
+async def _mark_logged_out() -> None:
+ from services.plugin.deps import get_auth_service
+
+ await get_auth_service().remove_oauth_tokens("vercel")
+
+
+async def _broadcast_credential_event(event_type: str) -> None:
+ from services.status_broadcaster import get_status_broadcaster
+
+ await get_status_broadcaster().broadcast_credential_event(
+ event_type,
+ provider="vercel",
+ )
+
+
+# Strong refs for fire-and-forget tasks — asyncio only holds weak refs,
+# so an un-referenced running task can be garbage-collected mid-flight.
+_background_tasks: set = set()
+
+
+def _spawn_background(coro) -> asyncio.Task:
+ task = asyncio.create_task(coro)
+ _background_tasks.add(task)
+ task.add_done_callback(_background_tasks.discard)
+ return task
+
+
+async def _read_login_banner(proc: asyncio.subprocess.Process) -> tuple[Optional[str], Optional[str], List[str]]:
+ """Read the login process's early output until a URL shows up (or
+ the deadline / EOF). Returns ``(url, verification_code, tail_lines)``.
+
+ Chunk-based, not ``readline()`` — device-flow spinners repaint via
+ ``\\r`` frames with no newline, which would overrun the
+ StreamReader line limit. The pumps deliberately OUTLIVE this
+ function: they keep draining both pipes for the process lifetime so
+ the CLI never blocks on a full pipe buffer during its ~10-minute
+ poll; only the first 32 KiB is retained for parsing.
+ """
+ buf: List[str] = []
+ buf_len = 0
+ new_data = asyncio.Event()
+
+ async def pump(stream: Optional[asyncio.StreamReader]) -> None:
+ nonlocal buf_len
+ if stream is None:
+ new_data.set()
+ return
+ while True:
+ chunk = await stream.read(4096)
+ if not chunk:
+ break
+ if buf_len < 32768:
+ text = chunk.decode(errors="replace")
+ buf.append(text)
+ buf_len += len(text)
+ new_data.set()
+ new_data.set()
+
+ pumps = [_spawn_background(pump(proc.stdout)), _spawn_background(pump(proc.stderr))]
+
+ url: Optional[str] = None
+ code: Optional[str] = None
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + _URL_DEADLINE_SECONDS
+ while True:
+ blob = strip_ansi("".join(buf))
+ url = url or extract_login_url(blob)
+ code = code or extract_verification_code(blob)
+ if url or all(t.done() for t in pumps):
+ break
+ remaining = deadline - loop.time()
+ if remaining <= 0:
+ break
+ new_data.clear()
+ try:
+ await asyncio.wait_for(new_data.wait(), timeout=remaining)
+ except asyncio.TimeoutError:
+ break
+
+ tail = [ln.strip() for ln in strip_ansi("".join(buf)).splitlines() if ln.strip()]
+ return url, code, tail
+
+
+async def _start_login_flow() -> Dict[str, Any]:
+ """Install (if needed) + spawn the device-flow login + parse the
+ banner + schedule completion. Never raises — returns the WS
+ response dict."""
+ try:
+ binary = await _resolved_binary()
+ if not binary:
+ return {
+ "success": False,
+ "error": "Vercel CLI install failed. Manual install: npm i -g vercel (https://vercel.com/docs/cli)",
+ }
+
+ auth = vercel_auth_path()
+ pre_mtime = auth.stat().st_mtime if auth.exists() else 0.0
+
+ # stdin=PIPE left un-written — under the FastAPI daemon (no TTY)
+ # an inherited closed stdin makes the CLI see EOF and abort the
+ # device-flow poll (claude auth login precedent, see
+ # run_cli_command's stdin doc).
+ proc = await asyncio.create_subprocess_exec(
+ binary,
+ *global_argv(["login"]),
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ env=vercel_env(),
+ )
+
+ url, code, lines = await _read_login_banner(proc)
+ if not url:
+ proc.kill()
+ banner = " | ".join(lines[-5:]) or "(no output)"
+ logger.warning("[Vercel] login banner had no URL within %ss: %s", _URL_DEADLINE_SECONDS, banner)
+ return {
+ "success": False,
+ "error": f"Could not extract the login URL from 'vercel login' output. CLI said: {banner}",
+ }
+
+ logger.info(
+ "[Vercel] device-flow URL issued (code=%s) — opening on frontend; awaiting browser confirmation in background (timeout=%ss)",
+ code,
+ _LOGIN_TIMEOUT_SECONDS,
+ )
+ _spawn_background(_complete_login(proc, pre_mtime))
+ # The frontend only opens `url`; `verification_code` rides along for
+ # forward-compat (never rendered today — keep the URL code-embedding).
+ return {"success": True, "url": url, "verification_code": code}
+ except Exception as e:
+ logger.exception("[Vercel] login flow raised unexpectedly: %s", e)
+ return {"success": False, "error": f"Vercel login failed: {e}"}
+
+
+async def handle_vercel_login(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Answer within the frontend's request window no matter what.
+
+ Fast path (CLI already installed): the device-flow URL is on the
+ CLI's output within a few seconds — return it so the frontend opens
+ the browser. Cold path (first run pays ``npm install vercel``): the
+ budget expires first; return a pending success immediately and let
+ the flow finish in the background — ``vercel login`` opens the
+ browser on this machine itself once it reaches the device-flow
+ prompt, and the connected-state broadcast flips the modal when the
+ user authorises."""
+ logger.info("[Vercel] login flow starting (device flow)")
+ flow = _spawn_background(_start_login_flow())
+ try:
+ return await asyncio.wait_for(asyncio.shield(flow), timeout=_RESPONSE_BUDGET_SECONDS)
+ except asyncio.TimeoutError:
+ logger.info(
+ "[Vercel] login still preparing after %ss (cold CLI install) — continuing in background; the CLI will open the browser itself",
+ _RESPONSE_BUDGET_SECONDS,
+ )
+ return {
+ "success": True,
+ "pending": True,
+ "message": "Vercel CLI is being installed — your browser will open shortly to complete the login.",
+ }
+
+
+async def _complete_login(proc: asyncio.subprocess.Process, pre_mtime: float) -> None:
+ """Await the device-flow poll. Success = ``auth.json`` mtime advanced
+ past the pre-login snapshot AND the sniff holds — the exit code alone
+ is not trusted (Stripe precedent: CLIs exit non-zero after a
+ successful credential write)."""
+ try:
+ try:
+ returncode = await asyncio.wait_for(proc.wait(), timeout=_LOGIN_TIMEOUT_SECONDS)
+ except asyncio.TimeoutError:
+ proc.kill()
+ logger.warning("[Vercel] login timed out after %ss — user never completed the browser flow", _LOGIN_TIMEOUT_SECONDS)
+ return
+ except Exception as e:
+ # asyncio.create_task swallows exceptions silently — log them.
+ logger.exception("[Vercel] login wait raised unexpectedly: %s", e)
+ return
+
+ auth = vercel_auth_path()
+ post_mtime = auth.stat().st_mtime if auth.exists() else 0.0
+ fresh_credentials_written = post_mtime > pre_mtime and is_logged_in()
+
+ if not fresh_credentials_written:
+ logger.warning(
+ "[Vercel] login exited (code=%s) but no fresh credentials written to %s (pre=%.3f post=%.3f) — user likely closed the browser before authorising",
+ returncode,
+ auth,
+ pre_mtime,
+ post_mtime,
+ )
+ return
+
+ if returncode != 0:
+ logger.debug("[Vercel] login exited non-zero (%s) but credentials WERE written — treating as success", returncode)
+
+ logger.info("[Vercel] auth successful — credentials written to %s; persisting catalogue marker", auth)
+ await _mark_logged_in()
+ await _broadcast_credential_event("credential.oauth.connected")
+
+
+async def handle_vercel_logout(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """``vercel logout`` against the pinned config dir, then drop the
+ catalogue marker + broadcast so the modal flips immediately."""
+ logger.info("[Vercel] logout starting")
+ cached = vercel_cli_path()
+ if cached is None:
+ auth = vercel_auth_path()
+ auth.unlink(missing_ok=True)
+ result: Dict[str, Any] = {"success": True, "message": "Logged out (CLI not yet installed; cleared auth file)"}
+ logger.info("[Vercel] logout fallback: CLI not installed; deleted %s", auth)
+ else:
+ result = await run_cli_command(
+ binary=str(cached),
+ argv=global_argv(["logout"]),
+ timeout=15.0,
+ env=vercel_env(),
+ )
+ # Belt-and-braces: the sniff must not report logged-in afterwards.
+ if is_logged_in():
+ vercel_auth_path().unlink(missing_ok=True)
+ await _mark_logged_out()
+ await _broadcast_credential_event("credential.oauth.disconnected")
+ logger.info("[Vercel] logout complete: marker token removed + catalogue broadcast sent")
+ return result
+
+
+async def handle_vercel_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Login-state snapshot: connected when EITHER auth path is live."""
+ token = await stored_token()
+ logged_in = is_logged_in()
+ return {
+ "success": True,
+ "status": {
+ "logged_in": logged_in,
+ "token_stored": bool(token),
+ "connected": logged_in or bool(token),
+ },
+ }
+
+
+WS_HANDLERS = {
+ "vercel_login": handle_vercel_login,
+ "vercel_logout": handle_vercel_logout,
+ "vercel_status": handle_vercel_status,
+}
diff --git a/server/nodes/vercel/_install.py b/server/nodes/vercel/_install.py
new file mode 100644
index 00000000..e0fff6c2
--- /dev/null
+++ b/server/nodes/vercel/_install.py
@@ -0,0 +1,121 @@
+"""Vercel CLI auto-installer.
+
+The Vercel CLI ships as the npm package ``vercel`` — it lands in the
+shared MachinaOs npm tree at :func:`core.paths.packages_dir`
+(``<DATA_DIR>/packages/``), the same single ``package.json`` +
+``node_modules/`` that holds ``@anthropic-ai/claude-code`` /
+``edgymeow`` / ``agent-browser``. ``npm install <pkg> --prefix
+<packages_dir>`` extends the shared tree idempotently.
+
+A system install on PATH is preferred; the npm install only fires when
+no system binary is found. Pin ``_NPM_SPEC`` when bumping (whatsapp
+precedent — ``@latest`` makes cold installs non-reproducible).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+from typing import Optional
+
+from core.logging import get_logger
+from core.paths import packages_dir
+
+logger = get_logger(__name__)
+
+_NPM_SPEC = "[email protected]"
+
+_cached_path: Optional[Path] = None
+_install_lock = asyncio.Lock()
+
+
+def vercel_cli_path() -> Optional[Path]:
+ """Sync getter for the resolved binary path. Returns ``None`` if
+ :func:`ensure_vercel_cli` hasn't run yet (or never resolved)."""
+ return _cached_path
+
+
+def _shared_tree_bin() -> Path:
+ bin_name = "vercel.cmd" if sys.platform == "win32" else "vercel"
+ return packages_dir() / "node_modules" / ".bin" / bin_name
+
+
+def _npm_install() -> Path:
+ """Blocking npm install into the shared tree. Raises on failure."""
+ root = packages_dir()
+ bin_path = _shared_tree_bin()
+
+ npm_cmd = shutil.which("npm")
+ if not npm_cmd:
+ raise RuntimeError("npm not on PATH — install Node.js or the Vercel CLI manually (npm i -g vercel)")
+
+ logger.info("[Vercel] installing %s into shared tree %s", _NPM_SPEC, root)
+ root.mkdir(parents=True, exist_ok=True)
+ result = subprocess.run(
+ [npm_cmd, "install", _NPM_SPEC, "--prefix", str(root), "--no-audit", "--no-fund"],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode != 0 or not bin_path.exists():
+ raise RuntimeError(f"npm install {_NPM_SPEC} failed: {result.stderr.strip()[:500]}")
+
+ logger.info("[Vercel] CLI installed at %s", bin_path)
+ return bin_path
+
+
+async def ensure_vercel_cli() -> Path:
+ """Return absolute path to the vercel binary, installing on miss.
+ Idempotent + concurrent-safe.
+
+ Resolution order (stripe idiom):
+ 1. Cached path from a prior call (in-process).
+ 2. ``shutil.which("vercel")`` — system install on PATH.
+ 3. Previously-installed shim in the shared npm tree.
+ 4. Fresh ``npm install`` into the shared tree.
+ """
+ global _cached_path
+ if _cached_path and _cached_path.exists():
+ return _cached_path
+
+ sys_path = shutil.which("vercel")
+ if sys_path:
+ _cached_path = Path(sys_path)
+ logger.info("[Vercel] using system CLI at %s", _cached_path)
+ return _cached_path
+
+ async with _install_lock:
+ if _cached_path and _cached_path.exists():
+ return _cached_path
+ target = _shared_tree_bin()
+ if target.exists():
+ _cached_path = target
+ return target
+ # npm install blocks for tens of seconds — keep the event loop free.
+ installed = await asyncio.to_thread(_npm_install)
+ _cached_path = installed
+ await _disable_telemetry(installed)
+ return installed
+
+
+async def _disable_telemetry(binary: Path) -> None:
+ """Best-effort one-shot ``vercel telemetry disable`` right after a
+ fresh install (ephemeral-runner hygiene). Non-fatal on any failure."""
+ try:
+ from ._service import global_argv, vercel_env
+
+ proc = await asyncio.create_subprocess_exec(
+ str(binary),
+ *global_argv(["telemetry", "disable"]),
+ stdout=asyncio.subprocess.DEVNULL,
+ stderr=asyncio.subprocess.DEVNULL,
+ env=vercel_env(),
+ )
+ await asyncio.wait_for(proc.wait(), timeout=30)
+ except Exception as e: # noqa: BLE001 — hygiene step, never blocks install
+ logger.debug("[Vercel] telemetry disable skipped: %s", e)
+
+
+__all__ = ["ensure_vercel_cli", "vercel_cli_path"]
diff --git a/server/nodes/vercel/_service.py b/server/nodes/vercel/_service.py
new file mode 100644
index 00000000..8a009ddb
--- /dev/null
+++ b/server/nodes/vercel/_service.py
@@ -0,0 +1,105 @@
+"""Shared Vercel plugin helpers — config-dir pinning, login sniff,
+env/argv builders, login-output parsing.
+
+Auth-state isolation: every ``vercel`` invocation passes
+``--global-config <DATA_DIR>/vercel/`` so the CLI's ``auth.json`` /
+``config.json`` live in a MachinaOs-owned directory instead of the
+platform-varying ``com.vercel.cli`` default. Same philosophy as
+``CLAUDE_CONFIG_DIR = data_path("claude")`` in
+``nodes/agent/claude_code_agent/_oauth.py`` — MachinaOs-managed auth
+never collides with the user's own system-wide ``vercel login``, and
+the pinned path makes :func:`is_logged_in` deterministic across
+platforms. Composed inline per the ``core.paths`` rule (generic
+helpers only — no plugin subpaths in ``core/paths.py``).
+"""
+
+from __future__ import annotations
+
+import os
+import re
+from pathlib import Path
+from typing import Dict, List, Optional
+
+from core.logging import get_logger
+from core.paths import data_path
+
+logger = get_logger(__name__)
+
+# api-key row holding the user's optional Vercel access token
+# (vercel.com/account/tokens). Injected as the VERCEL_TOKEN env var —
+# never argv, so it stays out of process lists.
+TOKEN_KEY = "vercel_token"
+
+
+def vercel_config_dir() -> Path:
+ """MachinaOs-pinned ``--global-config`` directory."""
+ p = data_path("vercel")
+ p.mkdir(parents=True, exist_ok=True)
+ return p
+
+
+def vercel_auth_path() -> Path:
+ return vercel_config_dir() / "auth.json"
+
+
+def is_logged_in() -> bool:
+ """Filesystem sniff — ``auth.json`` in the pinned config dir holds a
+ token. Cheap and sync (stripe's ``config.toml`` sniff idiom). True
+ for *any* prior login, which is why the login handler pairs it with
+ an mtime-advance check."""
+ auth = vercel_auth_path()
+ try:
+ return auth.exists() and "token" in auth.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ return False
+
+
+def global_argv(argv: List[str]) -> List[str]:
+ """Append the uniform global flags every invocation needs."""
+ return [*argv, "--global-config", str(vercel_config_dir()), "--no-color"]
+
+
+def vercel_env(token: Optional[str] = None) -> Dict[str, str]:
+ """Child environment: parent env + ``NO_COLOR`` (+ ``VERCEL_TOKEN``)."""
+ env = os.environ.copy()
+ env["NO_COLOR"] = "1"
+ if token:
+ env["VERCEL_TOKEN"] = token
+ return env
+
+
+async def stored_token() -> Optional[str]:
+ """The user's optional access token from the credentials DB."""
+ from services.plugin.deps import get_auth_service
+
+ return await get_auth_service().get_api_key(TOKEN_KEY)
+
+
+# --- Login-output parsing ----------------------------------------------------
+
+_ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)")
+_URL_RE = re.compile(r"https://\S+")
+# Device-flow user codes render as grouped alphanumerics, e.g. ABCD-EFGH.
+_CODE_RE = re.compile(r"\b([A-Z0-9]{4}-[A-Z0-9]{4})\b")
+
+
+def strip_ansi(text: str) -> str:
+ return _ANSI_RE.sub("", text)
+
+
+def extract_login_url(text: str) -> Optional[str]:
+ """First https URL in the CLI's login banner. Prefers a link that
+ embeds the device code (``code=`` query param) because the frontend
+ only opens ``url`` — it never renders a separate code."""
+ urls = [u.rstrip(".,;)'\"") for u in _URL_RE.findall(strip_ansi(text))]
+ if not urls:
+ return None
+ for url in urls:
+ if "code=" in url:
+ return url
+ return urls[0]
+
+
+def extract_verification_code(text: str) -> Optional[str]:
+ m = _CODE_RE.search(strip_ansi(text))
+ return m.group(1) if m else None
diff --git a/server/nodes/vercel/meta.json b/server/nodes/vercel/meta.json
new file mode 100644
index 00000000..edea0d56
--- /dev/null
+++ b/server/nodes/vercel/meta.json
@@ -0,0 +1 @@
+{"color": "#666666"}
diff --git a/server/nodes/vercel/vercel_action.py b/server/nodes/vercel/vercel_action.py
new file mode 100644
index 00000000..6e84c37a
--- /dev/null
+++ b/server/nodes/vercel/vercel_action.py
@@ -0,0 +1,341 @@
+"""Vercel Action — deploy / inspect / list over the Vercel CLI, plus a
+raw-command passthrough (stripe idiom).
+
+Parsing contract (vercel.com/docs/cli/deploy): for ``deploy`` stdout
+carries ONLY the deployment URL — progress and errors go to stderr.
+``list`` / ``inspect`` are human-readable text (no ``--json``); the raw
+text is returned in ``stdout`` and the AI tool works with it directly.
+"""
+
+from __future__ import annotations
+
+import os
+import shlex
+from pathlib import Path
+from typing import Any, Dict, List, Literal, Optional
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from services.events import run_cli_command
+from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue
+
+from ._credentials import VercelCredential
+
+_DEPLOY = {"displayOptions": {"show": {"operation": ["deploy"]}}}
+_INSPECT = {"displayOptions": {"show": {"operation": ["inspect"]}}}
+_LIST = {"displayOptions": {"show": {"operation": ["list"]}}}
+_CUSTOM = {"displayOptions": {"show": {"operation": ["custom"]}}}
+
+_DEPLOY_TIMEOUT = 600.0
+_ONESHOT_TIMEOUT = 60.0
+_INSPECT_WAIT_TIMEOUT = 300.0
+_STDERR_TAIL_CHARS = 2000
+
+
+class VercelActionParams(BaseModel):
+ operation: Literal["deploy", "inspect", "list", "custom"] = "deploy"
+
+ # deploy
+ path: str = Field(
+ default="",
+ json_schema_extra={
+ "placeholder": "Directory to deploy (defaults to the workflow workspace)",
+ **_DEPLOY,
+ },
+ )
+ prod: bool = Field(
+ default=False,
+ description="Deploy to production instead of a preview",
+ json_schema_extra={"displayOptions": {"show": {"operation": ["deploy", "list"]}}},
+ )
+ prebuilt: bool = Field(
+ default=False,
+ description="Deploy a prior 'vercel build' output (.vercel/output) without uploading source",
+ json_schema_extra=_DEPLOY,
+ )
+ archive: bool = Field(
+ default=False,
+ description="Compress the upload into a tarball (--archive=tgz) — avoids the files-count limit",
+ json_schema_extra=_DEPLOY,
+ )
+ scope: str = Field(
+ default="",
+ json_schema_extra={"placeholder": "Team slug (optional)", **_DEPLOY},
+ )
+ extra_args: str = Field(
+ default="",
+ json_schema_extra={
+ "placeholder": "Extra CLI flags, e.g. --env KEY=value --no-wait",
+ **_DEPLOY,
+ },
+ )
+
+ # deploy + list
+ project: str = Field(
+ default="",
+ description=(
+ "Vercel project name or id. Required for a first deploy from an unlinked directory — "
+ "lowercase letters, digits, '.', '_' and '-' only (Vercel rejects anything else)"
+ ),
+ json_schema_extra={
+ "placeholder": "my-site (lowercase)",
+ "displayOptions": {"show": {"operation": ["deploy", "list"]}},
+ },
+ )
+
+ # inspect
+ deployment: str = Field(
+ default="",
+ json_schema_extra={
+ "placeholder": "https://my-app-abc123.vercel.app or deployment id",
+ **_INSPECT,
+ },
+ )
+ logs: bool = Field(
+ default=False,
+ description="Print build logs instead of deployment info",
+ json_schema_extra=_INSPECT,
+ )
+ wait: bool = Field(
+ default=False,
+ description="Block until the deployment finishes",
+ json_schema_extra=_INSPECT,
+ )
+ timeout: str = Field(
+ default="3m",
+ description="How long --wait blocks (ms-style duration, e.g. 5m)",
+ json_schema_extra=_INSPECT,
+ )
+
+ # list
+ status: str = Field(
+ default="",
+ json_schema_extra={
+ "placeholder": "READY,BUILDING,ERROR (comma-separated, optional)",
+ **_LIST,
+ },
+ )
+
+ # custom
+ command: str = Field(
+ default="",
+ description="Vercel CLI command, exactly as typed after 'vercel '",
+ json_schema_extra={
+ "placeholder": "env ls | logs <url> --json | rollback <url>",
+ **_CUSTOM,
+ },
+ )
+
+ model_config = ConfigDict(extra="ignore")
+
+
+class VercelActionOutput(BaseModel):
+ operation: Optional[str] = None
+ success: Optional[bool] = None
+ url: Optional[str] = None
+ result: Optional[Any] = None
+ stdout: Optional[str] = None
+ stderr_tail: Optional[str] = None
+
+ model_config = ConfigDict(extra="allow")
+
+
+class VercelActionNode(ActionNode):
+ type = "vercelAction"
+ display_name = "Vercel"
+ subtitle = "CLI"
+ group = ("deployment", "tool")
+ description = "Deploy to Vercel and inspect deployments via the Vercel CLI (deploy / inspect / list / custom command)"
+ component_kind = "square"
+ tool_name = "vercel"
+ tool_description = (
+ "Interact with Vercel via its CLI. Operations: deploy (deploy a directory as a preview or "
+ "production deployment; returns the deployment URL), inspect (details/build logs for a "
+ "deployment URL or id), list (recent deployments for a project), custom (run any other "
+ "Vercel CLI command — pass 'command' exactly as you would type after 'vercel ', e.g. "
+ "'env ls', 'logs <url> --json', 'rollback <url>', 'promote <url>', 'domains ls', "
+ "'project ls --format=json'). A first deploy from an unlinked directory requires the "
+ "'project' field — a Vercel project name in lowercase letters/digits/'.'/'_'/'-'. "
+ "Reference: https://vercel.com/docs/cli"
+ )
+ handles = (
+ {"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},
+ {"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},
+ )
+ annotations = {"destructive": False, "readonly": False, "open_world": True}
+ credentials = (VercelCredential,)
+ task_queue = TaskQueue.REST_API
+ usable_as_tool = True
+
+ Params = VercelActionParams
+ Output = VercelActionOutput
+
+ # ---- shared plumbing -------------------------------------------------
+
+ async def _preflight(self) -> Optional[str]:
+ """Ensure one auth path is live; return the stored token (or None
+ when relying on CLI login). Raises an annotated PermissionError
+ so the framework emits the credential envelope + the
+ ``credential.oauth.runtime_failed`` broadcast."""
+ from ._service import is_logged_in, stored_token
+
+ token = await stored_token()
+ if token or is_logged_in():
+ return token
+ err = PermissionError("Vercel not connected. Open Credentials → Vercel and click Login, or paste an access token (vercel.com/account/tokens).")
+ err.provider = "vercel" # type: ignore[attr-defined]
+ err.reason = "missing" # type: ignore[attr-defined]
+ err.auth = "oauth2" # type: ignore[attr-defined]
+ raise err
+
+ async def _run(
+ self,
+ argv: List[str],
+ *,
+ token: Optional[str],
+ cwd: Optional[str] = None,
+ timeout: float = _ONESHOT_TIMEOUT,
+ ) -> Dict[str, Any]:
+ from ._install import ensure_vercel_cli
+ from ._service import global_argv, vercel_env
+
+ try:
+ binary = str(await ensure_vercel_cli())
+ except Exception as e:
+ raise RuntimeError(f"Vercel CLI install failed: {e}") from e
+
+ result = await run_cli_command(
+ binary=binary,
+ argv=global_argv(argv),
+ timeout=timeout,
+ env=vercel_env(token),
+ cwd=cwd,
+ )
+ if not result.get("success"):
+ stderr = (result.get("stderr") or "").strip()
+ detail = stderr[-_STDERR_TAIL_CHARS:] if stderr else (result.get("error") or "Vercel CLI invocation failed")
+ raise NodeUserError(f"vercel {argv[0]} failed: {detail}")
+ return result
+
+ def _resolve_deploy_cwd(self, ctx: NodeContext, path: str) -> str:
+ """Deploy directory: explicit param (absolute, or relative to the
+ per-workflow workspace) falling back to the workspace itself."""
+ workspace = ctx.workspace_dir
+ if path:
+ p = Path(path)
+ if not p.is_absolute():
+ if not workspace:
+ raise NodeUserError(f"Relative path {path!r} needs a workflow workspace — run inside a workflow or pass an absolute path")
+ p = Path(workspace) / p
+ if not p.is_dir():
+ raise NodeUserError(f"Deploy path does not exist or is not a directory: {p}")
+ return str(p)
+ if not workspace:
+ raise NodeUserError("No deploy path given and no workflow workspace available — set the 'path' parameter")
+ return str(workspace)
+
+ @staticmethod
+ def _shape(operation: str, result: Dict[str, Any], *, url: Optional[str] = None) -> Dict[str, Any]:
+ stderr = (result.get("stderr") or "").strip()
+ return {
+ "operation": operation,
+ "success": True,
+ "url": url,
+ "result": result.get("result"),
+ "stdout": result.get("stdout"),
+ "stderr_tail": stderr[-_STDERR_TAIL_CHARS:] or None,
+ }
+
+ # ---- operations ------------------------------------------------------
+
+ @staticmethod
+ def _require_project_target(cwd: str, params: "VercelActionParams") -> None:
+ """First deploys from an unlinked directory need an explicit
+ project target, otherwise Vercel derives the name from the cwd —
+ which for workflow workspaces (``AI_Assistant_1``) violates its
+ naming rules and 400s late, after the upload. Fail fast with the
+ remediation instead; Vercel stays the authority on what names
+ are valid."""
+ if params.project.strip():
+ return
+ if (Path(cwd) / ".vercel" / "project.json").exists():
+ return # already linked — Vercel knows the project
+ if os.environ.get("VERCEL_PROJECT_ID"):
+ return
+ if "--project" in shlex.split(params.extra_args or ""):
+ return
+ raise NodeUserError(
+ "First deploy from this directory needs a project target: set the 'project' "
+ "parameter (lowercase letters, digits, '.', '_', '-'; see "
+ "https://vercel.com/docs/projects/overview#project-name), or link the directory "
+ "once with the custom operation: command='link --yes --project <name>'."
+ )
+
+ @Operation("deploy", cost={"service": "vercel", "action": "deploy", "count": 1})
+ async def deploy(self, ctx: NodeContext, params: "VercelActionParams") -> Any:
+ token = await self._preflight()
+ cwd = self._resolve_deploy_cwd(ctx, params.path.strip())
+ self._require_project_target(cwd, params)
+ argv = ["deploy", "--yes"]
+ if params.prod:
+ argv.append("--prod")
+ if params.prebuilt:
+ argv.append("--prebuilt")
+ if params.archive:
+ argv.append("--archive=tgz")
+ if params.project.strip():
+ argv.extend(["--project", params.project.strip()])
+ if params.scope.strip():
+ argv.extend(["--scope", params.scope.strip()])
+ if params.extra_args.strip():
+ argv.extend(shlex.split(params.extra_args))
+ result = await self._run(argv, token=token, cwd=cwd, timeout=_DEPLOY_TIMEOUT)
+ # Deploy prints exactly the deployment URL on stdout.
+ stdout = (result.get("stdout") or "").strip()
+ url = stdout if stdout.startswith("http") else None
+ return self._shape("deploy", result, url=url)
+
+ @Operation("inspect", cost={"service": "vercel", "action": "inspect", "count": 1})
+ async def inspect(self, ctx: NodeContext, params: "VercelActionParams") -> Any:
+ token = await self._preflight()
+ deployment = params.deployment.strip()
+ if not deployment:
+ raise NodeUserError("deployment is required (a deployment URL or id, e.g. https://my-app-abc123.vercel.app)")
+ argv = ["inspect", deployment]
+ if params.logs:
+ argv.append("--logs")
+ if params.wait:
+ argv.append("--wait")
+ if params.timeout.strip():
+ argv.extend(["--timeout", params.timeout.strip()])
+ timeout = _INSPECT_WAIT_TIMEOUT if params.wait else _ONESHOT_TIMEOUT
+ result = await self._run(argv, token=token, timeout=timeout)
+ return self._shape("inspect", result)
+
+ @Operation("list", cost={"service": "vercel", "action": "list", "count": 1})
+ async def list_deployments(self, ctx: NodeContext, params: "VercelActionParams") -> Any:
+ token = await self._preflight()
+ argv = ["list"]
+ if params.project.strip():
+ argv.append(params.project.strip())
+ if params.prod:
+ argv.append("--prod")
+ if params.status.strip():
+ argv.extend(["--status", params.status.strip()])
+ argv.append("--yes")
+ result = await self._run(argv, token=token)
+ return self._shape("list", result)
+
+ @Operation("custom", cost={"service": "vercel", "action": "custom", "count": 1})
+ async def custom(self, ctx: NodeContext, params: "VercelActionParams") -> Any:
+ token = await self._preflight()
+ cmd = params.command.strip()
+ if not cmd:
+ raise NodeUserError("command is required (e.g. 'env ls', 'logs <url> --json', 'domains ls')")
+ argv = shlex.split(cmd)
+ # Directory-scoped commands (env/link/pull/...) run in the
+ # workflow workspace when one exists.
+ result = await self._run(argv, token=token, cwd=ctx.workspace_dir, timeout=_DEPLOY_TIMEOUT)
+ stdout = (result.get("stdout") or "").strip()
+ url = stdout if stdout.startswith("http") and "\n" not in stdout else None
+ return self._shape("custom", result, url=url)
diff --git a/server/nodes/visuals.json b/server/nodes/visuals.json
index fec53257..24ce12b4 100644
--- a/server/nodes/visuals.json
+++ b/server/nodes/visuals.json
@@ -308,6 +308,10 @@
"vectorStore": {
"icon": "🗄️"
},
+ "vercelAction": {
+ "icon": "lobehub:Vercel",
+ "skill": "vercel-skill"
+ },
"web_agent": {
"icon": "🌐"
},
diff --git a/server/services/events/cli.py b/server/services/events/cli.py
index 7cf678eb..ff10f68b 100644
--- a/server/services/events/cli.py
+++ b/server/services/events/cli.py
@@ -24,12 +24,17 @@ async def run_cli_command(
timeout: float = 30.0,
env: Optional[Dict[str, str]] = None,
stdin: Optional[int] = None,
+ cwd: Optional[str] = None,
) -> Dict[str, Any]:
"""Run ``<binary> <argv> [api_key_arg <key>]`` once, return parsed JSON.
``env``: optional process environment override. When None, the child
inherits the parent's environment (asyncio default).
+ ``cwd``: optional working directory for the child. Needed by CLIs
+ whose commands are directory-scoped (``vercel deploy`` deploys the
+ cwd). ``None`` inherits the parent's cwd.
+
``stdin``: optional override for the child's stdin handle. ``None``
(default) inherits the parent's stdin — what most one-shot CLI
invocations want. Pass :data:`asyncio.subprocess.PIPE` (left
@@ -74,6 +79,7 @@ async def run_cli_command(
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env=env,
+ cwd=cwd,
)
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
except asyncio.TimeoutError:
diff --git a/server/skills/vercel/vercel-skill/SKILL.md b/server/skills/vercel/vercel-skill/SKILL.md
new file mode 100644
index 00000000..4d631f94
--- /dev/null
+++ b/server/skills/vercel/vercel-skill/SKILL.md
@@ -0,0 +1,186 @@
+---
+name: vercel-skill
+description: Deploy sites and apps to Vercel, inspect deployments, stream logs, and manage projects/env/domains via the Vercel CLI. Deploy a directory and get back the live deployment URL; everything else the CLI supports is available through the custom command passthrough.
+allowed-tools: "vercel"
+metadata:
+ author: machina
+ version: "1.0"
+ category: deployment
+
+---
+
+# Vercel Skill
+
+Wrapper over the official [Vercel CLI](https://vercel.com/docs/cli).
+Four operations: `deploy`, `inspect`, `list`, and a `custom`
+passthrough that runs any other CLI command — env vars, logs,
+rollback, promote, domains, aliases, projects.
+
+## Tool: vercel
+
+### Operations
+
+| Operation | Purpose | Key fields |
+|---|---|---|
+| `deploy` | Deploy a directory; returns the live deployment URL | `path`, `project`, `prod`, `prebuilt`, `archive`, `scope`, `extra_args` |
+| `inspect` | Details or build logs for one deployment | `deployment` (URL or id), `logs`, `wait`, `timeout` |
+| `list` | Recent deployments for a project | `project`, `prod`, `status` |
+| `custom` | Any other CLI command | `command` — exactly what you would type after `vercel ` |
+
+### Response
+
+```json
+{
+ "operation": "deploy",
+ "success": true,
+ "url": "https://my-site-abc123.vercel.app",
+ "result": null,
+ "stdout": "https://my-site-abc123.vercel.app",
+ "stderr_tail": "… build output …"
+}
+```
+
+For `deploy`, `url` is the live deployment URL (stdout carries only
+the URL; progress goes to stderr — `stderr_tail` keeps the last part
+for context). `list` / `inspect` return human-readable text in
+`stdout`. `custom` commands that support `--json` / `--format=json`
+(`logs`, `project ls`, `teams ls`, `domains verify`) return parsed
+JSON in `result`.
+
+On CLI failure the tool raises an error carrying Vercel's own
+message — surface it verbatim; Vercel's errors are precise.
+
+## Project naming — read before your first deploy
+
+A **first deploy from an unlinked directory MUST set `project`**.
+Vercel project names allow lowercase letters, digits, `.`, `_`, `-`
+(no uppercase, no spaces, no `---` sequence). Workflow workspace
+directories often violate this (`AI_Assistant_1`), so the tool
+refuses an unlinked no-project deploy up front rather than failing
+after the upload.
+
+```json
+{ "operation": "deploy", "project": "my-site" }
+```
+
+Once a directory is linked (`.vercel/project.json` exists — created
+by the first successful deploy, or by
+`custom: "link --yes --project my-site"`), later deploys may omit
+`project`.
+
+## Common workflows
+
+### Deploy files from the workflow workspace
+
+Write your site files (e.g. `index.html`) into the workspace, then:
+
+```json
+{ "operation": "deploy", "project": "my-site" }
+```
+
+`path` defaults to the per-workflow workspace directory. Preview
+deploy by default; add `"prod": true` for production. The returned
+`url` is live immediately.
+
+### Deploy a specific directory
+
+```json
+{ "operation": "deploy", "path": "dist", "project": "my-site", "prod": true }
+```
+
+Relative `path` resolves against the workflow workspace; absolute
+paths are used as-is.
+
+### Wait for a deployment to finish building
+
+```json
+{ "operation": "inspect", "deployment": "https://my-site-abc123.vercel.app", "wait": true, "timeout": "5m" }
+```
+
+Add `"logs": true` to see build logs instead of the summary.
+
+### List recent deployments
+
+```json
+{ "operation": "list", "project": "my-site", "status": "READY,ERROR" }
+```
+
+### Runtime logs (JSON)
+
+```json
+{ "operation": "custom", "command": "logs https://my-site-abc123.vercel.app --json" }
+```
+
+### Environment variables
+
+```json
+{ "operation": "custom", "command": "env ls" }
+{ "operation": "custom", "command": "env rm API_KEY production --yes" }
+```
+
+Adding env values non-interactively needs stdin, which the
+passthrough does not provide — set values at deploy time instead via
+`extra_args` (`--env KEY=value` for runtime, `--build-env KEY=value`
+for build time):
+
+```json
+{ "operation": "deploy", "project": "my-site", "extra_args": "--env API_URL=https://api.example.com" }
+```
+
+### Rollback / promote production
+
+```json
+{ "operation": "custom", "command": "rollback https://my-site-abc123.vercel.app" }
+{ "operation": "custom", "command": "promote https://my-site-abc123.vercel.app" }
+```
+
+### Projects, domains, aliases
+
+```json
+{ "operation": "custom", "command": "project ls --format=json" }
+{ "operation": "custom", "command": "domains ls" }
+{ "operation": "custom", "command": "alias set https://my-site-abc123.vercel.app www.example.com" }
+```
+
+## Quoting and escaping
+
+`command` and `extra_args` are parsed with `shlex.split`. Quote
+arguments containing spaces with single quotes. Never put an access
+token in `command` — auth is injected automatically as the
+`VERCEL_TOKEN` environment variable.
+
+## Timeouts and long builds
+
+`deploy` waits up to 10 minutes for the build. For longer builds pass
+`--no-wait` in `extra_args` (returns the URL immediately while the
+build continues) and poll with `inspect` + `"wait": true` afterwards.
+
+## Authentication
+
+Two independent paths (either is enough), configured in the
+Credentials Modal → Vercel:
+
+1. **Login with Vercel** — browser device flow driven through the
+ CLI. The CLI is auto-installed via npm on first use and keeps its
+ auth state in a MachinaOs-owned config directory.
+2. **Access token** — paste a token from
+ [vercel.com/account/tokens](https://vercel.com/account/tokens).
+ Injected as `VERCEL_TOKEN` on every call; takes precedence over
+ CLI login and works headless.
+
+If neither is configured the tool raises a credential error telling
+the user which panel to open.
+
+## Best practices
+
+1. **Always pass a lowercase `project` on first deploys** (naming
+ rules above).
+2. **Default to preview deploys**; set `"prod": true` only when the
+ user explicitly wants production.
+3. **Return the deployment URL to the user** — it is live the moment
+ `deploy` succeeds.
+4. **Use the `archive` field** when deploying directories with
+ thousands of files.
+5. **Surface Vercel error messages verbatim** — don't paraphrase.
+6. **Prefer `--json` / `--format=json` variants** in `custom`
+ commands when you need to read fields programmatically.
diff --git a/server/tests/test_vercel_plugin.py b/server/tests/test_vercel_plugin.py
new file mode 100644
index 00000000..8ca3a149
--- /dev/null
+++ b/server/tests/test_vercel_plugin.py
@@ -0,0 +1,292 @@
+"""Vercel plugin contract tests.
+
+Locks the plugin's load-bearing seams: argv building (config-dir
+pinning, token-in-env-never-argv), device-flow banner parsing, the
+marker-token + CloudEvents broadcast contract (``inspect.getsource``
+introspection, ``test_credential_broadcasts`` style), install
+resolution order, the annotated PermissionError pre-flight, and the
+catalogue entry shape.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import inspect
+import json
+from pathlib import Path
+
+import pytest
+
+import nodes.vercel._handlers as vercel_handlers
+import nodes.vercel._install as vercel_install
+import nodes.vercel._service as vercel_service
+import nodes.vercel.vercel_action as vercel_action_mod
+from nodes.vercel import WS_HANDLERS
+from nodes.vercel._credentials import VercelCredential
+from nodes.vercel.vercel_action import VercelActionNode, VercelActionParams
+from services.plugin import NodeContext
+from services.plugin.base import NodeUserError
+
+PLUGIN_DIR = Path(vercel_service.__file__).parent
+CONFIG_PATH = Path(vercel_service.__file__).parents[2] / "config" / "credential_providers.json"
+
+
+# --- _service helpers ---------------------------------------------------------
+
+
+def test_global_argv_pins_config_dir_and_disables_color(monkeypatch, tmp_path):
+ monkeypatch.setattr(vercel_service, "data_path", lambda name: tmp_path / name)
+ argv = vercel_service.global_argv(["deploy", "--yes"])
+ assert argv[:2] == ["deploy", "--yes"]
+ assert "--global-config" in argv
+ cfg = argv[argv.index("--global-config") + 1]
+ assert cfg == str(tmp_path / "vercel")
+ assert argv[-1] == "--no-color"
+
+
+def test_vercel_env_puts_token_in_env_never_argv(monkeypatch, tmp_path):
+ monkeypatch.setattr(vercel_service, "data_path", lambda name: tmp_path / name)
+ env = vercel_service.vercel_env("vcp_secret123")
+ assert env["VERCEL_TOKEN"] == "vcp_secret123"
+ assert env["NO_COLOR"] == "1"
+ # The token must never leak into argv (process lists are world-readable).
+ assert all("vcp_secret123" not in part for part in vercel_service.global_argv(["whoami"]))
+ assert "VERCEL_TOKEN" not in vercel_service.vercel_env(None)
+
+
+def test_is_logged_in_sniffs_pinned_auth_json(monkeypatch, tmp_path):
+ monkeypatch.setattr(vercel_service, "data_path", lambda name: tmp_path / name)
+ assert vercel_service.is_logged_in() is False
+ vercel_service.vercel_auth_path().write_text('{"token": "vcp_abc"}', encoding="utf-8")
+ assert vercel_service.is_logged_in() is True
+
+
+def test_extract_login_url_prefers_code_embedding_link():
+ banner = (
+ "\x1b[36m> Visit \x1b[1mhttps://vercel.com/oauth/device?user_code=ABCD-EFGH\x1b[0m"
+ " to authenticate.\nDocs: https://vercel.com/docs/cli/login\n"
+ "> Your code is \x1b[1mABCD-EFGH\x1b[0m"
+ )
+ assert vercel_service.extract_login_url(banner) == "https://vercel.com/oauth/device?user_code=ABCD-EFGH"
+ assert vercel_service.extract_verification_code(banner) == "ABCD-EFGH"
+
+
+def test_extract_login_url_falls_back_to_first_url():
+ banner = "Visit https://vercel.com/device to log in."
+ assert vercel_service.extract_login_url(banner) == "https://vercel.com/device"
+ assert vercel_service.extract_login_url("no links here") is None
+
+
+# --- _install resolution ------------------------------------------------------
+
+
+async def test_ensure_vercel_cli_prefers_system_path(monkeypatch, tmp_path):
+ fake = tmp_path / "vercel"
+ fake.write_text("#!/bin/sh\n", encoding="utf-8")
+ monkeypatch.setattr(vercel_install, "_cached_path", None)
+ monkeypatch.setattr(vercel_install.shutil, "which", lambda name: str(fake))
+ resolved = await vercel_install.ensure_vercel_cli()
+ assert resolved == fake
+ # cached for subsequent calls without re-resolving
+ monkeypatch.setattr(vercel_install.shutil, "which", lambda name: None)
+ assert await vercel_install.ensure_vercel_cli() == fake
+
+
+def test_npm_spec_is_pinned():
+ # `@latest` makes cold installs non-reproducible (whatsapp precedent).
+ assert "@" in vercel_install._NPM_SPEC
+ version = vercel_install._NPM_SPEC.rsplit("@", 1)[1]
+ assert version and version != "latest"
+
+
+# --- pre-flight / operations --------------------------------------------------
+
+
+async def test_preflight_raises_annotated_permission_error(monkeypatch):
+ async def no_token():
+ return None
+
+ monkeypatch.setattr(vercel_service, "stored_token", no_token)
+ monkeypatch.setattr(vercel_service, "is_logged_in", lambda: False)
+ node = VercelActionNode()
+ with pytest.raises(PermissionError) as exc:
+ await node._preflight()
+ err = exc.value
+ assert err.provider == "vercel"
+ assert err.reason == "missing"
+ assert err.auth == "oauth2"
+
+
+async def test_deploy_builds_argv_env_and_cwd(monkeypatch, tmp_path):
+ async def token():
+ return "vcp_tok123"
+
+ async def fake_ensure():
+ return tmp_path / "vercel"
+
+ captured = {}
+
+ async def fake_run(**kwargs):
+ captured.update(kwargs)
+ return {"success": True, "result": None, "stdout": "https://my-app-abc123.vercel.app", "stderr": "Build ok", "error": None}
+
+ monkeypatch.setattr(vercel_service, "stored_token", token)
+ monkeypatch.setattr(vercel_service, "data_path", lambda name: tmp_path / name)
+ monkeypatch.setattr(vercel_install, "ensure_vercel_cli", fake_ensure)
+ monkeypatch.setattr(vercel_action_mod, "run_cli_command", fake_run)
+
+ node = VercelActionNode()
+ ctx = NodeContext(node_id="v1", node_type="vercelAction", workspace_dir=str(tmp_path))
+ params = VercelActionParams(operation="deploy", prod=True, project="my-app", extra_args="--no-wait")
+ out = await node.deploy(ctx, params)
+
+ argv = captured["argv"]
+ assert argv[:2] == ["deploy", "--yes"]
+ assert "--prod" in argv
+ assert argv[argv.index("--project") + 1] == "my-app"
+ assert "--no-wait" in argv
+ assert "--global-config" in argv and "--no-color" in argv
+ assert captured["env"]["VERCEL_TOKEN"] == "vcp_tok123"
+ assert captured["cwd"] == str(tmp_path)
+ assert out["url"] == "https://my-app-abc123.vercel.app"
+ assert out["operation"] == "deploy"
+ assert out["success"] is True
+
+
+async def test_deploy_missing_path_and_workspace_is_user_error(monkeypatch, tmp_path):
+ async def token():
+ return "vcp_tok123"
+
+ monkeypatch.setattr(vercel_service, "stored_token", token)
+ node = VercelActionNode()
+ ctx = NodeContext(node_id="v1", node_type="vercelAction", workspace_dir=None)
+ with pytest.raises(NodeUserError):
+ await node.deploy(ctx, VercelActionParams(operation="deploy"))
+
+
+async def test_cli_failure_surfaces_as_node_user_error(monkeypatch, tmp_path):
+ async def token():
+ return "vcp_tok123"
+
+ async def fake_ensure():
+ return tmp_path / "vercel"
+
+ async def fake_run(**kwargs):
+ return {"success": False, "stdout": "", "stderr": "Error: project not found", "error": "exit 1"}
+
+ monkeypatch.setattr(vercel_service, "stored_token", token)
+ monkeypatch.setattr(vercel_service, "data_path", lambda name: tmp_path / name)
+ monkeypatch.setattr(vercel_install, "ensure_vercel_cli", fake_ensure)
+ monkeypatch.setattr(vercel_action_mod, "run_cli_command", fake_run)
+
+ node = VercelActionNode()
+ ctx = NodeContext(node_id="v1", node_type="vercelAction", workspace_dir=str(tmp_path))
+ with pytest.raises(NodeUserError, match="project not found"):
+ await node.list_deployments(ctx, VercelActionParams(operation="list"))
+
+
+async def test_custom_requires_command(monkeypatch, tmp_path):
+ async def token():
+ return "vcp_tok123"
+
+ monkeypatch.setattr(vercel_service, "stored_token", token)
+ node = VercelActionNode()
+ ctx = NodeContext(node_id="v1", node_type="vercelAction", workspace_dir=str(tmp_path))
+ with pytest.raises(NodeUserError):
+ await node.custom(ctx, VercelActionParams(operation="custom", command=" "))
+
+
+# --- login handler ------------------------------------------------------------
+
+
+async def test_login_answers_within_budget_when_flow_stalls(monkeypatch):
+ """Regression: the first-ever login pays a cold `npm install vercel`
+ inside the handler, which blew past the frontend's 30s WS request
+ timeout ("Request timeout: vercel_login") even though the login
+ itself succeeded. The handler must answer within its response
+ budget with a pending success and keep the flow going."""
+
+ async def stalled_flow():
+ await asyncio.sleep(30)
+ return {"success": True, "url": "https://vercel.com/late"}
+
+ monkeypatch.setattr(vercel_handlers, "_start_login_flow", stalled_flow)
+ monkeypatch.setattr(vercel_handlers, "_RESPONSE_BUDGET_SECONDS", 0.05)
+ res = await vercel_handlers.handle_vercel_login({}, websocket=None)
+ assert res["success"] is True
+ assert res.get("pending") is True
+
+
+async def test_login_fast_path_returns_url(monkeypatch):
+ async def instant_flow():
+ return {"success": True, "url": "https://vercel.com/oauth/device?user_code=ABCD-EFGH", "verification_code": "ABCD-EFGH"}
+
+ monkeypatch.setattr(vercel_handlers, "_start_login_flow", instant_flow)
+ res = await vercel_handlers.handle_vercel_login({}, websocket=None)
+ assert res["success"] is True
+ assert "user_code=" in res["url"]
+
+
+# --- marker-token + broadcast contract (source introspection) -----------------
+
+
+def test_login_success_persists_marker_and_broadcasts():
+ src = inspect.getsource(vercel_handlers._mark_logged_in)
+ assert "store_oauth_tokens" in src
+ assert 'provider="vercel"' in src
+ complete = inspect.getsource(vercel_handlers._complete_login)
+ assert "_mark_logged_in" in complete
+ assert "credential.oauth.connected" in complete
+ # exit code alone is never trusted — mtime advance gates success
+ assert "pre_mtime" in complete and "is_logged_in" in complete
+
+
+def test_logout_removes_marker_and_broadcasts():
+ src = inspect.getsource(vercel_handlers.handle_vercel_logout)
+ assert "_mark_logged_out" in src
+ assert "credential.oauth.disconnected" in src
+ marker = inspect.getsource(vercel_handlers._mark_logged_out)
+ assert 'remove_oauth_tokens("vercel")' in marker
+
+
+def test_ws_handlers_registered():
+ assert set(WS_HANDLERS) == {"vercel_login", "vercel_logout", "vercel_status"}
+
+
+# --- catalogue + assets -------------------------------------------------------
+
+
+def test_catalogue_entry_shape():
+ config = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
+ assert "deployment" in config["categories"]
+ vercel = config["providers"]["vercel"]
+ assert vercel["kind"] == "oauth"
+ assert vercel["category"] == "deployment"
+ assert vercel["ws"] == {"login": "vercel_login", "logout": "vercel_logout", "status": "vercel_status"}
+ (token_field,) = vercel["fields"]
+ assert token_field["key"] == "vercel_token"
+ # optional — must NOT gate the Login button (OAuthConnect gates on required fields only)
+ assert token_field["required"] is False
+
+
+def test_credential_class_shape():
+ assert VercelCredential.id == "vercel"
+ assert VercelCredential.auth == "custom"
+
+
+def test_plugin_folder_assets():
+ # Icon comes from the official lobehub brand set via visuals.json —
+ # a co-located icon.svg would silently override it (first hit in
+ # get_plugin_icon_path), so its absence is part of the contract.
+ assert not (PLUGIN_DIR / "icon.svg").exists()
+ assert not (PLUGIN_DIR / "icon.dark.svg").exists()
+ meta = json.loads((PLUGIN_DIR / "meta.json").read_text(encoding="utf-8"))
+ assert meta["color"].startswith("#")
+
+ visuals = json.loads((PLUGIN_DIR.parent / "visuals.json").read_text(encoding="utf-8"))
+ entry = visuals["vercelAction"]
+ assert entry["icon"] == "lobehub:Vercel"
+ assert entry["skill"] == "vercel-skill"
+
+ skill_md = PLUGIN_DIR.parents[1] / "skills" / "vercel" / "vercel-skill" / "SKILL.md"
+ assert skill_md.exists()