Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(nodes): add cloudflare node wrapping the official cf CLI
trohitg5d44e15bd493
diff --git a/client/src/assets/icons/index.ts b/client/src/assets/icons/index.tsindex 0a382307..c4825c01 100644--- a/client/src/assets/icons/index.ts+++ b/client/src/assets/icons/index.ts@@ -50,6 +50,7 @@ import Ollama from '@lobehub/icons/es/Ollama';import LmStudio from '@lobehub/icons/es/LmStudio';import Vercel from '@lobehub/icons/es/Vercel';import Github from '@lobehub/icons/es/Github';+import Cloudflare from '@lobehub/icons/es/Cloudflare';import VertexAI from '@lobehub/icons/es/VertexAI';import GoogleCloud from '@lobehub/icons/es/GoogleCloud';@@ -158,6 +159,7 @@ const LOBEHUB_BRANDS: Readonly<Record<string, any>> = {lmstudio: LmStudio,vercel: Vercel,github: Github,+ cloudflare: Cloudflare,vertexai: VertexAI,googlecloud: GoogleCloud,};diff --git a/server/config/credential_providers.json b/server/config/credential_providers.jsonindex 363febd0..a0663c79 100644--- a/server/config/credential_providers.json+++ b/server/config/credential_providers.json@@ -546,6 +546,21 @@"status": "github_status"},"instructions": "Click 'Login with GitHub' — the gh CLI (auto-installed) opens github.com/login/device in your browser and the one-time code is shown here. The token is stored by gh in your system credential store; OpenCompany never keeps it. After login, 'gh auth setup-git' runs so git remotes authenticate too. Alternative: run 'gh auth login' (or pipe a Personal Access Token to 'gh auth login --with-token') in a terminal on this machine."+ },++ "cloudflare": {+ "name": "Cloudflare",+ "category": "deployment",+ "category_label": "Deployment",+ "color": "dracula.orange",+ "kind": "oauth",+ "icon_ref": "lobehub:Cloudflare",+ "ws": {+ "login": "cloudflare_login",+ "logout": "cloudflare_logout",+ "status": "cloudflare_status"+ },+ "instructions": "Click 'Login with Cloudflare' — the cf CLI (auto-installed via npm) opens the Cloudflare dashboard OAuth page and completes via a localhost callback, so the browser must run on this machine. The token is stored by cf in its own user-level config; OpenCompany never keeps it. Alternatives: run 'cf auth login' in a terminal, or set CLOUDFLARE_API_TOKEN in the server environment for headless use (dash.cloudflare.com/profile/api-tokens)."}}}diff --git a/server/nodes/cloudflare/__init__.py b/server/nodes/cloudflare/__init__.pynew file mode 100644index 00000000..5cac49dd--- /dev/null+++ b/server/nodes/cloudflare/__init__.py@@ -0,0 +1,30 @@+"""Plugin for the 'deployment' palette group — Cloudflare via the+official cf CLI.++Self-contained CLI-managed-auth plugin (Stripe/gh pattern): the cf CLI+owns its auth end-to-end — ``cf auth login`` (PKCE OAuth with a+loopback callback on localhost:8877) driven from the credentials modal+(or the user's own terminal), token in cf's user-level config, a+synthetic ``cli-managed`` marker OAuth row for the catalogue badge.+OpenCompany never stores or injects a token. Headless alternative: an+ambient ``CLOUDFLARE_API_TOKEN`` env var (cf's documented first-priority+credential source) works for ops without any login.+"""++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 CloudflareCredential+from ._handlers import WS_HANDLERS+from .cloudflare_action import CloudflareActionNode, CloudflareActionOutput++register_ws_handlers(WS_HANDLERS)+register_output_schema("cloudflareAction", CloudflareActionOutput)++__all__ = [+ "CloudflareCredential",+ "CloudflareActionNode",+ "WS_HANDLERS",+]diff --git a/server/nodes/cloudflare/_credentials.py b/server/nodes/cloudflare/_credentials.pynew file mode 100644index 00000000..d22ab7e4--- /dev/null+++ b/server/nodes/cloudflare/_credentials.py@@ -0,0 +1,31 @@+"""Cloudflare credential — thin marker (Stripe idiom, github shape).++The cf CLI manages its own auth state: ``cf auth login`` (driven by the+modal's Login button or run by the user in a terminal) stores the OAuth+token in cf's user-level config (``auth.jsonc``, or the OS keyring when+``CLOUDFLARE_AUTH_USE_KEYRING`` is set) and ``cf auth logout`` revokes+it. OpenCompany stores no token — the credentials modal's connected+badge is driven by the synthetic ``cli-managed`` marker OAuth row+written by ``_handlers.py`` after a successful login.+"""++from __future__ import annotations++from typing import Any, Dict++from services.plugin.credential import Credential+++class CloudflareCredential(Credential):+ id = "cloudflare"+ display_name = "Cloudflare"+ category = "Deployment"+ auth = "custom"+ docs_url = "https://developers.cloudflare.com"++ @classmethod+ async def resolve(cls, *, user_id: str = "owner") -> Dict[str, Any]:+ """Nothing to resolve — auth lives in the cf CLI's own config+ (or an ambient ``CLOUDFLARE_API_TOKEN`` env var, per cf's own+ documented precedence)."""+ return {}diff --git a/server/nodes/cloudflare/_handlers.py b/server/nodes/cloudflare/_handlers.pynew file mode 100644index 00000000..85d4dea0--- /dev/null+++ b/server/nodes/cloudflare/_handlers.py@@ -0,0 +1,274 @@+"""Cloudflare WebSocket handlers — the cf CLI owns its own auth (gh /+Stripe CLI pattern).++``cloudflare_login`` spawns cf's official browser login::++ cf auth login++Source-verified behavior (cf 0.2.0 ``dist/auth-*.mjs`` + live headless+capture): the flow runs a PKCE OAuth against+``dash.cloudflare.com/oauth2/auth`` with a loopback callback server on+``localhost:8877``, self-opens the browser, and prints to **stderr**+(status stream; stdout is reserved for JSON)::++ Attempting to login via OAuth...+ Opening a link in your default browser: https://dash.cloudflare.com/oauth2/auth?...++(or ``Visit this link to authenticate: <url>`` when it can't open a+browser). There is NO device code — the loopback callback completes the+flow, so the handler returns ``{success, url}`` only and the modal just+opens the url. Success gate: ``cf auth whoami`` reporting+``authenticated: true`` (cf exits 0 in both states, so exit codes are+never trusted). On success we write the synthetic ``cli-managed``+marker OAuth row (flips the catalogue's ``stored`` badge, with the+whoami email as the account label) and broadcast the generic+catalogue-invalidation event. Marker + broadcast plumbing is the shared+:mod:`services.cli_agent._cli_auth` module (claude/codex/github all use+it).++cf delta vs gh: when a session already exists, ``cf auth login``+(without ``--force``) exits without printing an authorize URL — the+handler detects the early exit, confirms via whoami, and reports+success immediately.++OpenCompany never stores or reads the actual token — it stays in cf's+user-level config (``auth.jsonc`` / OS keyring).+"""++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.cli_agent._cli_auth import broadcast_credential_event, mark_logged_in, mark_logged_out+from services.events import run_cli_command++from ._install import ensure_cf_cli+from ._service import extract_login_url, login_env, whoami_snapshot++logger = get_logger(__name__)++_LOGIN_ARGS = ["auth", "login"]+_LOGIN_TIMEOUT_SECONDS = 600+# How long to wait for the authorize URL on the CLI's output before+# giving up on this attempt.+_BANNER_DEADLINE_SECONDS = 20+# The frontend drops WS requests after 30s. A first-ever login pays a+# cold npm install inside this handler — answer within this budget no+# matter what and let the flow continue in the background.+_RESPONSE_BUDGET_SECONDS = 22+++# Strong refs for fire-and-forget tasks — asyncio holds only weak refs+# (the documented discard-set pattern from the asyncio docs).+_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], List[str]]:+ """Read the login process's early output until the authorize URL+ shows up (or deadline / EOF). Chunk-based, not ``readline()`` —+ spinner frames repaint via ``\\r`` with no newline. The pumps+ deliberately OUTLIVE this function: they keep draining both pipes+ for the process lifetime so cf never blocks on a full pipe buffer+ while its callback server waits (~10 min); 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+ loop = asyncio.get_running_loop()+ deadline = loop.time() + _BANNER_DEADLINE_SECONDS+ while True:+ url = extract_login_url("".join(buf))+ if url is not None 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 "".join(buf).splitlines() if ln.strip()]+ return url, tail+++async def _start_login_flow() -> Dict[str, Any]:+ """Install (if needed) + spawn cf's browser login + parse the+ banner + schedule completion. Never raises — returns the WS+ response dict."""+ try:+ try:+ binary = str(await ensure_cf_cli())+ except Exception as e:+ logger.warning("[Cloudflare] cf CLI install failed: %s", e)+ return {+ "success": False,+ "error": f"cf CLI install failed ({e}). Manual install: npm i -g cf",+ }++ # stdin=PIPE left un-written: cf's prompts auto-disable when+ # stdio is not a TTY, and a pipe keeps any stray stdin read+ # from seeing instant EOF.+ proc = await asyncio.create_subprocess_exec(+ binary,+ *_LOGIN_ARGS,+ stdin=asyncio.subprocess.PIPE,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ env=login_env(),+ )++ url, lines = await _read_login_banner(proc)+ if url is None:+ # cf delta: with a live session, `cf auth login` exits+ # without printing an authorize URL — confirm via whoami+ # and mark immediately instead of treating it as a failure.+ if proc.returncode is not None:+ info = await whoami_snapshot()+ if info:+ email = info.get("email")+ await mark_logged_in("cloudflare", email=email)+ await broadcast_credential_event("credential.oauth.connected", provider="cloudflare")+ logger.info("[Cloudflare] already logged in as %s — marker refreshed", email or "<unknown>")+ return {"success": True, "message": f"Already logged in{f' as {email}' if email else ''}."}+ proc.kill()+ banner = " | ".join(lines[-5:]) or "(no output)"+ logger.warning("[Cloudflare] login banner had no authorize URL within %ss: %s", _BANNER_DEADLINE_SECONDS, banner)+ return {+ "success": False,+ "error": (+ f"Could not start cf's browser login. CLI said: {banner} — "+ "you can also run 'cf auth login' in a terminal on this machine."+ ),+ }++ logger.info(+ "[Cloudflare] OAuth authorize URL issued — opening on frontend; awaiting loopback callback in background (timeout=%ss)",+ _LOGIN_TIMEOUT_SECONDS,+ )+ _spawn_background(_complete_login(proc))+ return {"success": True, "url": url}+ except Exception as e:+ logger.exception("[Cloudflare] login flow raised unexpectedly: %s", e)+ return {"success": False, "error": f"Cloudflare login failed: {e}"}+++async def handle_cloudflare_login(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Answer within the frontend's request window no matter what+ (vercel's cold-install pending pattern)."""+ logger.info("[Cloudflare] login flow starting (cf auth login)")+ flow = _spawn_background(_start_login_flow())+ try:+ return await asyncio.wait_for(asyncio.shield(flow), timeout=_RESPONSE_BUDGET_SECONDS)+ except asyncio.TimeoutError:+ logger.info(+ "[Cloudflare] login still preparing after %ss (cold cf install) — continuing in background",+ _RESPONSE_BUDGET_SECONDS,+ )+ return {+ "success": True,+ "pending": True,+ "message": "cf CLI is being installed — click Login again in a few seconds.",+ }+++async def _complete_login(proc: asyncio.subprocess.Process) -> None:+ """Await cf's loopback-callback flow; gate success on ``cf auth+ whoami`` (exit codes are not trusted — cf exits 0 either way); then+ the marker + broadcast."""+ try:+ try:+ returncode = await asyncio.wait_for(proc.wait(), timeout=_LOGIN_TIMEOUT_SECONDS)+ except asyncio.TimeoutError:+ proc.kill()+ logger.warning("[Cloudflare] login timed out after %ss — user never completed the browser flow", _LOGIN_TIMEOUT_SECONDS)+ return+ except Exception as e:+ logger.exception("[Cloudflare] login wait raised unexpectedly: %s", e)+ return++ info = await whoami_snapshot()+ if not info:+ logger.warning(+ "[Cloudflare] login exited (code=%s) but 'cf auth whoami' reports no session — user likely closed the browser before authorising",+ returncode,+ )+ return++ email = info.get("email")+ await mark_logged_in("cloudflare", email=email)+ logger.info("[Cloudflare] connected as %s — catalogue marker persisted", email or "<unknown>")+ await broadcast_credential_event("credential.oauth.connected", provider="cloudflare")+++async def handle_cloudflare_logout(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """``cf auth logout`` (best-effort, revokes the OAuth token), drop+ the catalogue marker, broadcast so the modal flips immediately."""+ logger.info("[Cloudflare] logout starting")+ from ._service import resolve_cf_light++ binary = resolve_cf_light()+ result: Dict[str, Any] = {"success": True}+ if binary:+ result = await run_cli_command(+ binary=binary,+ argv=["auth", "logout"],+ timeout=15.0,+ env=login_env(),+ )+ if not result.get("success"):+ logger.warning("[Cloudflare] 'cf auth logout' failed (marker still removed): %s", result.get("error"))+ result = {"success": True, "message": "cf reported no stored session; catalogue marker removed"}+ await mark_logged_out("cloudflare")+ await broadcast_credential_event("credential.oauth.disconnected", provider="cloudflare")+ logger.info("[Cloudflare] logout complete: marker removed + catalogue broadcast sent")+ return result+++async def handle_cloudflare_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """Session snapshot straight from the CLI — no side effects."""+ info = await whoami_snapshot()+ connected = info is not None+ status: Dict[str, Any] = {"connected": connected, "logged_in": connected}+ if info and info.get("email"):+ status["email"] = info["email"]+ return {"success": True, "status": status}+++WS_HANDLERS = {+ "cloudflare_login": handle_cloudflare_login,+ "cloudflare_logout": handle_cloudflare_logout,+ "cloudflare_status": handle_cloudflare_status,+}diff --git a/server/nodes/cloudflare/_install.py b/server/nodes/cloudflare/_install.pynew file mode 100644index 00000000..e01727d2--- /dev/null+++ b/server/nodes/cloudflare/_install.py@@ -0,0 +1,105 @@+"""Cloudflare CLI (`cf`) auto-installer — npm, pinned, project-local.++The official Cloudflare CLI ships as the npm package ``cf`` (a+Technical Preview — "the next version of Wrangler"). It lands in the+shared OpenCompany npm tree at :func:`core.paths.packages_dir`+(``<DATA_DIR>/packages/``), the same single ``package.json`` ++``node_modules/`` that holds ``@anthropic-ai/claude-code`` / ``vercel``+/ ``agent-browser``. ``npm install <pkg> --prefix <packages_dir>``+extends the shared tree idempotently.++Unlike the vercel installer, the system-global ``cf`` is deliberately+NEVER consulted (the gh philosophy): the preview CLI's command surface+is schema-generated and shifts between versions (0.0.5's ``--ndjson``+is gone in 0.2.0; write ops changed shape), and this plugin's argv+builders are verified against the pinned version only. Auth state is+unaffected by which binary runs — cf's config paths are user-level and+shared, so a session created by the user's own ``cf auth login`` in a+terminal is visible to this pinned binary too.++Pin ``_NPM_SPEC`` when bumping and re-verify every wrapped command via+``cf <cmd> --help-full`` (whatsapp precedent — ``@latest`` makes cold+installs non-reproducible). cf requires Node >= 22, which is already+OpenCompany's engines floor.+"""++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 cf_cli_path() -> Optional[Path]:+ """Sync getter for the project-local binary — the already-installed+ shim, without installing. ``None`` when never installed."""+ global _cached_path+ if _cached_path and _cached_path.exists():+ return _cached_path+ target = _shared_tree_bin()+ if target.exists():+ _cached_path = target+ return target+ return None+++def _shared_tree_bin() -> Path:+ bin_name = "cf.cmd" if sys.platform == "win32" else "cf"+ 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 22+ (the cf CLI ships via npm)")++ logger.info("[Cloudflare] 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("[Cloudflare] cf CLI installed at %s", bin_path)+ return bin_path+++async def ensure_cf_cli() -> Path:+ """Return absolute path to the project-local cf binary, installing+ the pinned npm release on miss. Idempotent + concurrent-safe."""+ global _cached_path+ existing = cf_cli_path()+ if existing:+ return existing++ async with _install_lock:+ existing = cf_cli_path()+ if existing:+ return existing+ # npm install blocks for tens of seconds — keep the event loop free.+ installed = await asyncio.to_thread(_npm_install)+ _cached_path = installed+ return installed+++__all__ = ["ensure_cf_cli", "cf_cli_path"]diff --git a/server/nodes/cloudflare/_service.py b/server/nodes/cloudflare/_service.pynew file mode 100644index 00000000..55882f2b--- /dev/null+++ b/server/nodes/cloudflare/_service.py@@ -0,0 +1,116 @@+"""Shared Cloudflare plugin helpers — subprocess env builders, cf+session probe, login-output parsing.++Auth model — **the cf CLI owns its own auth** (gh/Stripe pattern):+``cf auth login`` (driven by the modal's Login button or run by the+user in a terminal) is a PKCE OAuth flow against+``dash.cloudflare.com/oauth2/*`` with a loopback callback server on+``localhost:8877``; the token lands in cf's user-level config+(``auth.jsonc``) or the OS keyring. OpenCompany never stores or injects+a token — a synthetic ``cli-managed`` marker OAuth row flips the+catalogue's ``stored`` badge, exactly like gh. Ambient+``CLOUDFLARE_API_TOKEN`` in the server's own environment is left+untouched for ops (cf documents env tokens as taking precedence over+the stored OAuth session — this is also the headless path on remote+deployments where the loopback callback is unreachable) — but it MUST+be stripped for ``cf auth login`` / ``whoami`` / ``logout`` (see+:func:`login_env`).+"""++from __future__ import annotations++import os+import re+from typing import Any, Dict, Optional++# cf resolves credentials env-first (source-verified against cf 0.2.0's+# auth chunk): CLOUDFLARE_API_TOKEN/CF_API_TOKEN, then the legacy+# global-key pair. All of them mask the OAuth session for login/whoami.+_AMBIENT_CREDENTIAL_VARS = (+ "CLOUDFLARE_API_TOKEN",+ "CF_API_TOKEN",+ "CLOUDFLARE_API_KEY",+ "CF_API_KEY",+ "CLOUDFLARE_EMAIL",+ "CF_EMAIL",+)+++def cf_env() -> Dict[str, str]:+ """Child env for cf op invocations. No token handling: cf reads its+ own config (or an ambient env token, per its own documented+ precedence). ``NO_COLOR`` keeps the chalk-based status output free+ of ANSI codes."""+ env = os.environ.copy()+ env["NO_COLOR"] = "1"+ return env+++def login_env() -> Dict[str, str]:+ """Env for ``cf auth login`` / ``cf auth whoami`` / ``cf auth+ logout`` — the CLI must consult its OWN stored session, so ambient+ credential env vars are stripped: with ``CLOUDFLARE_API_TOKEN`` set,+ ``cf auth whoami`` reports the env token (``authSource: env``)+ instead of the OAuth session, and login would short-circuit."""+ env = cf_env()+ for var in _AMBIENT_CREDENTIAL_VARS:+ env.pop(var, None)+ return env+++def resolve_cf_light() -> Optional[str]:+ """The project-local cf binary WITHOUT triggering an install.+ ``None`` when it has never been installed (status then reports+ disconnected; login / ops install on demand). The system-global cf+ is deliberately never consulted."""+ from ._install import cf_cli_path++ cached = cf_cli_path()+ return str(cached) if cached else None+++async def whoami_snapshot() -> Optional[Dict[str, Any]]:+ """The parsed ``cf auth whoami`` JSON when a stored OAuth session is+ live, else ``None``. cf exits 0 in BOTH states (verified on 0.2.0:+ logged-out prints ``{"authenticated": false, "error": "Not logged+ in"}`` with exit 0) — the ``authenticated`` field is the only+ signal, so exit codes are never consulted. Best-effort: ``None``+ when cf isn't installed."""+ from services.events import run_cli_command++ binary = resolve_cf_light()+ if not binary:+ return None+ result = await run_cli_command(+ binary=binary,+ argv=["auth", "whoami"],+ timeout=15.0,+ env=login_env(),+ )+ info = result.get("result")+ if not isinstance(info, dict) or not info.get("authenticated"):+ return None+ if info.get("tokenValid") is False:+ return None+ return info+++# --- Login-output parsing ----------------------------------------------------++_ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)")+# cf 0.2.0 prints the authorize URL on stderr (source-verified, both+# variants carry the same URL):+# Opening a link in your default browser: https://dash.cloudflare.com/oauth2/auth?...+# Visit this link to authenticate: https://dash.cloudflare.com/oauth2/auth?...+_URL_RE = re.compile(r"https://dash\.(?:staging\.)?cloudflare\.com/oauth2/auth\S+")+++def strip_ansi(text: str) -> str:+ return _ANSI_RE.sub("", text)+++def extract_login_url(text: str) -> Optional[str]:+ """The OAuth authorize URL from cf's login banner, or ``None``+ while still waiting for it."""+ m = _URL_RE.search(strip_ansi(text))+ return m.group(0).rstrip(".,;)'\"") if m else Nonediff --git a/server/nodes/cloudflare/cloudflare_action.py b/server/nodes/cloudflare/cloudflare_action.pynew file mode 100644index 00000000..459c6af2--- /dev/null+++ b/server/nodes/cloudflare/cloudflare_action.py@@ -0,0 +1,289 @@+"""Cloudflare Action — typed core operations over the `cf` CLI, plus a+raw-command passthrough.++The cf CLI owns its own auth (Stripe/gh pattern): no pre-flight check+and no token injection here — cf reads its stored OAuth session+(populated by ``cf auth login``) or an ambient ``CLOUDFLARE_API_TOKEN``+env token, and its own "Not logged in" error surfaces through the+``NodeUserError`` wrap.++cf 0.2.0 prints JSON to stdout by default (status noise goes to+stderr), so parsed results flow straight into the output panel's JSON+tree. Argv shapes below are verified against the pinned 0.2.0 (`cf+<cmd> --help-full`): zone selection is the global ``-z/--zone`` flag,+``dns records create`` takes ``--body`` (raw JSON request body — the+schema-stable escape hatch; per-field flags churn between preview+versions), and ``dns records delete`` takes the record id as a+positional.+"""++from __future__ import annotations++import json+import shlex+from typing import Any, Dict, List, Literal, Optional++from pydantic import BaseModel, ConfigDict, Field, field_validator++from services.events import run_cli_command+from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue++from ._credentials import CloudflareCredential++_ZONES_LIST = {"displayOptions": {"show": {"operation": ["zones_list"]}}}+_DNS_ANY = {"displayOptions": {"show": {"operation": ["dns_records_list", "dns_record_create", "dns_record_delete"]}}}+_CREATE = {"displayOptions": {"show": {"operation": ["dns_record_create"]}}}+_DELETE = {"displayOptions": {"show": {"operation": ["dns_record_delete"]}}}+_CUSTOM = {"displayOptions": {"show": {"operation": ["custom"]}}}++_ONESHOT_TIMEOUT = 120.0+_CUSTOM_TIMEOUT = 300.0+_STDERR_TAIL_CHARS = 2000+++class CloudflareActionParams(BaseModel):+ operation: Literal[+ "whoami", "zones_list", "dns_records_list", "dns_record_create", "dns_record_delete", "custom"+ ] = "whoami"++ # Shared zone target for the DNS operations (global -z/--zone flag).+ zone: str = Field(+ default="",+ description="Zone ID or domain name",+ json_schema_extra={"placeholder": "example.com or zone ID", **_DNS_ANY},+ )++ # zones_list+ name_filter: str = Field(+ default="",+ description="Filter zones by domain name",+ json_schema_extra={"placeholder": "example.com (optional)", **_ZONES_LIST},+ )+ account_id: str = Field(+ default="",+ description="Filter zones by account ID",+ json_schema_extra={"placeholder": "Account ID (optional)", **_ZONES_LIST},+ )++ # dns_record_create+ record_body: str = Field(+ default="",+ description="DNS record as a raw JSON request body (--body)",+ json_schema_extra={+ "rows": 4,+ "placeholder": '{"type":"A","name":"www","content":"192.0.2.1","ttl":1,"proxied":false}',+ **_CREATE,+ },+ )++ # dns_record_delete+ record_id: str = Field(+ default="",+ description="DNS record ID to delete",+ json_schema_extra={"placeholder": "023e105f4ecef8ad9ca31a8372d0c353", **_DELETE},+ )++ # custom+ command: str = Field(+ default="",+ description="cf CLI command, exactly as typed after 'cf '",+ json_schema_extra={+ "placeholder": "accounts list | dns records get <id> --zone example.com | agent-context dns",+ **_CUSTOM,+ },+ )++ model_config = ConfigDict(extra="ignore")++ @field_validator("record_body", mode="before")+ @classmethod+ def _coerce_record_body(cls, v: Any) -> Any:+ """LLM tool calls may pass the record as a real JSON object —+ coerce to the string the CLI flag expects (canonical+ field_validator(mode="before") rule)."""+ if isinstance(v, (dict, list)):+ return json.dumps(v)+ return v+++class CloudflareActionOutput(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 CloudflareActionNode(ActionNode):+ type = "cloudflareAction"+ display_name = "Cloudflare"+ subtitle = "cf CLI"+ group = ("deployment", "tool")+ description = "Cloudflare via the official cf CLI — check auth, list zones, manage DNS records, or run any cf command"+ component_kind = "square"+ tool_name = "cloudflare"+ tool_description = (+ "Interact with Cloudflare via the official cf CLI. Operations: whoami (auth status + "+ "identity), zones_list (list/filter zones), dns_records_list (records for a zone), "+ "dns_record_create (pass 'record_body' as the raw JSON record, e.g. "+ '{"type":"A","name":"www","content":"192.0.2.1","ttl":1}), dns_record_delete (by record '+ "id), custom (any other cf command — pass 'command' exactly as typed after 'cf ', e.g. "+ "'accounts list', 'dns records get <id> --zone example.com', 'registrar domains list', "+ "'agent-context dns' for deep per-product docs, 'schema <cmd>' for request shapes). "+ "DNS operations take 'zone' as a zone ID or domain name. Output is JSON. "+ "Auth is managed by the cf CLI itself — connect via Credentials -> Cloudflare (Login "+ "button) or run 'cf auth login' in a terminal; a CLOUDFLARE_API_TOKEN env var also works. "+ "Reference: https://developers.cloudflare.com"+ )+ 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}+ # OutputPanel renders textual output preformatted (cf status text /+ # custom-command output is terminal text, not markdown).+ ui_hints = {"outputMode": "terminal"}+ credentials = (CloudflareCredential,)+ task_queue = TaskQueue.REST_API+ usable_as_tool = True++ Params = CloudflareActionParams+ Output = CloudflareActionOutput++ # ---- shared plumbing -------------------------------------------------++ async def _run(+ self,+ argv: List[str],+ *,+ timeout: float = _ONESHOT_TIMEOUT,+ ) -> Dict[str, Any]:+ """No auth pre-flight (Stripe pattern) — cf authenticates from+ its own config (or an ambient env token), and its error+ (including "Not logged in") surfaces via the NodeUserError wrap+ below."""+ from ._install import ensure_cf_cli+ from ._service import cf_env++ try:+ binary = str(await ensure_cf_cli())+ except Exception as e:+ raise RuntimeError(f"cf CLI install failed: {e}") from e++ result = await run_cli_command(+ binary=binary,+ argv=argv,+ timeout=timeout,+ env=cf_env(),+ )+ if not result.get("success"):+ stderr = (result.get("stderr") or "").strip()+ detail = stderr[-_STDERR_TAIL_CHARS:] if stderr else (result.get("error") or "cf invocation failed")+ raise NodeUserError(f"cf {argv[0]} failed: {detail}")+ return result++ @staticmethod+ def _zone_flag(params: "CloudflareActionParams") -> List[str]:+ zone = params.zone.strip()+ if not zone:+ raise NodeUserError("zone is required (a zone ID or domain name)")+ return ["--zone", zone]++ @staticmethod+ def _parse_ndjson(stdout: str) -> Optional[List[Any]]:+ """Multi-object stdout (one JSON document per line) defeats+ run_cli_command's single ``json.loads`` — recover it here.+ ``None`` when the text isn't NDJSON."""+ lines = [ln for ln in (s.strip() for s in stdout.splitlines()) if ln]+ if len(lines) < 2:+ return None+ parsed: List[Any] = []+ for ln in lines:+ try:+ parsed.append(json.loads(ln))+ except ValueError:+ return None+ return parsed++ @classmethod+ def _shape(cls, operation: str, result: Dict[str, Any], *, url: Optional[str] = None) -> Dict[str, Any]:+ """Output-panel shaping: when cf returned JSON (its default+ stdout contract), the parsed data IS the payload — the raw+ stdout string would just duplicate it as an unreadable blob+ (and pre-stringified JSON violates the output contract). Keys+ are omitted (not None'd) when empty so the panel shows only+ meaningful fields (`exclude_unset` preserves this)."""+ shaped: Dict[str, Any] = {"operation": operation, "success": True}+ if url:+ shaped["url"] = url+ parsed = result.get("result")+ stdout = (result.get("stdout") or "").strip()+ if parsed is None and stdout:+ parsed = cls._parse_ndjson(stdout)+ if parsed is not None:+ shaped["result"] = parsed+ elif stdout:+ shaped["stdout"] = stdout+ stderr = (result.get("stderr") or "").strip()+ if stderr:+ shaped["stderr_tail"] = stderr[-_STDERR_TAIL_CHARS:]+ return shaped++ # ---- operations ------------------------------------------------------++ @Operation("whoami", cost={"service": "cloudflare", "action": "whoami", "count": 1})+ async def whoami(self, ctx: NodeContext, params: CloudflareActionParams) -> Any:+ result = await self._run(["auth", "whoami"])+ return self._shape("whoami", result)++ @Operation("zones_list", cost={"service": "cloudflare", "action": "zones_list", "count": 1})+ async def zones_list(self, ctx: NodeContext, params: CloudflareActionParams) -> Any:+ argv = ["zones", "list"]+ if params.name_filter.strip():+ argv += ["--name", params.name_filter.strip()]+ if params.account_id.strip():+ argv += ["--account-id", params.account_id.strip()]+ result = await self._run(argv)+ return self._shape("zones_list", result)++ @Operation("dns_records_list", cost={"service": "cloudflare", "action": "dns_records_list", "count": 1})+ async def dns_records_list(self, ctx: NodeContext, params: CloudflareActionParams) -> Any:+ argv = ["dns", "records", "list", *self._zone_flag(params)]+ result = await self._run(argv)+ return self._shape("dns_records_list", result)++ @Operation("dns_record_create", cost={"service": "cloudflare", "action": "dns_record_create", "count": 1})+ async def dns_record_create(self, ctx: NodeContext, params: CloudflareActionParams) -> Any:+ body = params.record_body.strip()+ if not body:+ raise NodeUserError('record_body is required (raw JSON, e.g. {"type":"A","name":"www","content":"192.0.2.1","ttl":1})')+ try:+ json.loads(body)+ except ValueError as e:+ raise NodeUserError(f"record_body is not valid JSON: {e}") from e+ argv = ["dns", "records", "create", *self._zone_flag(params), "--body", body]+ result = await self._run(argv)+ return self._shape("dns_record_create", result)++ @Operation("dns_record_delete", cost={"service": "cloudflare", "action": "dns_record_delete", "count": 1})+ async def dns_record_delete(self, ctx: NodeContext, params: CloudflareActionParams) -> Any:+ record_id = params.record_id.strip()+ if not record_id:+ raise NodeUserError("record_id is required (find it via dns_records_list)")+ argv = ["dns", "records", "delete", record_id, *self._zone_flag(params)]+ result = await self._run(argv)+ return self._shape("dns_record_delete", result)++ @Operation("custom", cost={"service": "cloudflare", "action": "custom", "count": 1})+ async def custom(self, ctx: NodeContext, params: CloudflareActionParams) -> Any:+ cmd = params.command.strip()+ if not cmd:+ raise NodeUserError("command is required (e.g. 'accounts list', 'dns records get <id> --zone example.com', 'agent-context dns')")+ argv = shlex.split(cmd)+ result = await self._run(argv, timeout=_CUSTOM_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/cloudflare/meta.json b/server/nodes/cloudflare/meta.jsonnew file mode 100644index 00000000..efd7cd91--- /dev/null+++ b/server/nodes/cloudflare/meta.json@@ -0,0 +1 @@+{"color": "#F38020"}diff --git a/server/nodes/visuals.json b/server/nodes/visuals.jsonindex 6b1e416d..e9ec2ed6 100644--- a/server/nodes/visuals.json+++ b/server/nodes/visuals.json@@ -69,6 +69,14 @@"claude_code_agent": {"icon": "lobehub:Claude"},+ "cloudflare": {+ "icon": "lobehub:Cloudflare",+ "color": "#F38020"+ },+ "cloudflareAction": {+ "icon": "lobehub:Cloudflare",+ "skill": "cloudflare-skill"+ },"codex_agent": {"icon": "lobehub:OpenAI"},diff --git a/server/skills/cloudflare/cloudflare-skill/SKILL.md b/server/skills/cloudflare/cloudflare-skill/SKILL.mdnew file mode 100644index 00000000..08df352b--- /dev/null+++ b/server/skills/cloudflare/cloudflare-skill/SKILL.md@@ -0,0 +1,126 @@+---+name: cloudflare-skill+description: Work with Cloudflare via the official cf CLI — check auth identity, list zones, list/create/delete DNS records, and run any other cf command (accounts, registrar, per-product schemas). Output is parsed JSON.+allowed-tools: "cloudflare"+metadata:+ author: opencompany+ version: "1.0"+ category: deployment++---++# Cloudflare Skill++Wrapper over the official [Cloudflare CLI](https://blog.cloudflare.com/cf-cli-local-explorer/)+(`cf`, a Technical Preview — "the next version of Wrangler"). Typed+operations for the core flows plus a `custom` passthrough that covers+the entire cf surface. cf prints JSON to stdout by default, so results+come back parsed in `result`.++## Tool: cloudflare++### Operations++| Operation | Purpose | Key fields |+|---|---|---|+| `whoami` | Auth status + identity (email, scopes) | — |+| `zones_list` | List/filter zones (parsed JSON) | `name_filter`, `account_id` (both optional) |+| `dns_records_list` | DNS records for a zone (parsed JSON) | `zone` (zone ID or domain) |+| `dns_record_create` | Create a DNS record | `zone`, `record_body` (raw JSON record) |+| `dns_record_delete` | Delete a DNS record by id | `zone`, `record_id` |+| `custom` | Any other cf command | `command` — exactly what you would type after `cf ` |++### Response++```json+{+ "operation": "zones_list",+ "success": true,+ "result": [{ "id": "023e105f4ecef8ad9ca31a8372d0c353", "name": "example.com", "status": "active" }],+ "stdout": null,+ "stderr_tail": null+}+```++Parsed JSON lands in `result`; plain text (rare) lands in `stdout`.+On failure the tool raises an error carrying cf's own message —+surface it verbatim; cf's errors are precise (including "Not logged+in", which tells the user exactly how to authenticate).++## DNS records++`record_body` is the raw JSON request body (the API's DNS record+shape — stable across cf versions, unlike per-field flags):++```json+{ "operation": "dns_record_create", "zone": "example.com", "record_body": "{\"type\":\"A\",\"name\":\"www\",\"content\":\"192.0.2.1\",\"ttl\":1,\"proxied\":false}" }+```++Common record fields: `type` (A/AAAA/CNAME/TXT/MX/NS/SRV), `name`+(record name; `@` for the zone apex), `content`, `ttl` (`1` = auto),+`proxied` (orange-cloud), `priority` (MX/SRV). Get record ids from+`dns_records_list` before deleting:++```json+{ "operation": "dns_records_list", "zone": "example.com" }+{ "operation": "dns_record_delete", "zone": "example.com", "record_id": "023e105f4ecef8ad9ca31a8372d0c353" }+```++To update a record, use `custom` with `--body`:++```json+{ "operation": "custom", "command": "dns records update <record-id> --zone example.com --body '{\"content\":\"192.0.2.2\"}'" }+```++## The full cf surface via custom++```json+{ "operation": "custom", "command": "accounts list" }+{ "operation": "custom", "command": "dns records get <record-id> --zone example.com" }+{ "operation": "custom", "command": "registrar domains list" }+{ "operation": "custom", "command": "zones get --zone example.com" }+{ "operation": "custom", "command": "dns analytics report --zone example.com" }+```++Discovery helpers when unsure of a command's shape:++- `{ "operation": "custom", "command": "agent-context dns" }` — cf's+ built-in per-product agent context (also `agent-context --list` for+ the product catalogue).+- `{ "operation": "custom", "command": "schema zones list" }` — the+ API schema behind a command.+- Append `--dry-run` to any write command to validate without+ executing.++## Quoting and escaping++`command` is parsed with `shlex.split` — wrap JSON bodies in single+quotes: `custom: "dns records create --zone example.com --body '{\"type\":\"A\",...}'"`.++## Authentication++The cf CLI owns its auth — OpenCompany never stores a token. Three+equivalent ways to connect (any one is enough):++1. **Credentials Modal → Cloudflare → Login with Cloudflare** — cf+ (auto-installed) opens the Cloudflare dashboard OAuth page and+ completes via a localhost callback (browser must be on the same+ machine as the server).+2. **`cf auth login`** in a terminal on this machine.+3. **`CLOUDFLARE_API_TOKEN`** set in the server environment+ (create at dash.cloudflare.com/profile/api-tokens) — cf's+ documented first-priority credential source; works headless.++If a command fails with an authentication error, tell the user to+connect via one of these; don't ask them for a token.++## Best practices++1. **Run `whoami` first** when auth state is unknown — it returns the+ authenticated email and scopes without side effects.+2. **Pass `zone` as the domain name** (cf resolves it to the zone ID).+3. **Preview writes with `--dry-run`** via `custom` when the user's+ intent is ambiguous.+4. **Destructive operations** (zone deletes, record deletes) — confirm+ with the user before running unless they explicitly asked.+5. **Surface cf error messages verbatim** — don't paraphrase.diff --git a/server/tests/fixtures/tool_names_snapshot.json b/server/tests/fixtures/tool_names_snapshot.jsonindex 739e0e84..4507cb07 100644--- a/server/tests/fixtures/tool_names_snapshot.json+++ b/server/tests/fixtures/tool_names_snapshot.json@@ -69,6 +69,7 @@"emailSend": "email_send","emailRead": "email_read","stripeAction": "stripe_action",+ "cloudflareAction": "cloudflare","typescriptExecutor": "typescript_code","apifyActor": "apify_actor","agentBuilder": "agent_builder",diff --git a/server/tests/test_cloudflare_plugin.py b/server/tests/test_cloudflare_plugin.pynew file mode 100644index 00000000..5fa03639--- /dev/null+++ b/server/tests/test_cloudflare_plugin.py@@ -0,0 +1,456 @@+"""Cloudflare plugin contract tests.++Locks the plugin's load-bearing seams under the CLI-owns-auth (Stripe /+gh) pattern: env builders (no token handling; login env strips ambient+Cloudflare credential vars so whoami reflects the OAuth session), the+login-banner URL parser (source-verified cf 0.2.0 output), install+resolution (pinned npm spec into the shared packages tree; system cf+never consulted), the marker-token + CloudEvents broadcast contract+(``inspect.getsource`` introspection, ``test_credential_broadcasts``+style), op argv building (verified against cf 0.2.0 ``--help-full``),+NDJSON recovery, and the catalogue entry shape (fieldless — cf owns the+token).+"""++from __future__ import annotations++import asyncio+import inspect+import json+from pathlib import Path++import pytest++import nodes.cloudflare._handlers as cf_handlers+import nodes.cloudflare._install as cf_install+import nodes.cloudflare._service as cf_service+import nodes.cloudflare.cloudflare_action as cf_action_mod+from nodes.cloudflare import WS_HANDLERS+from nodes.cloudflare._credentials import CloudflareCredential+from nodes.cloudflare.cloudflare_action import CloudflareActionNode, CloudflareActionParams+from services.plugin import NodeContext+from services.plugin.base import NodeUserError++PLUGIN_DIR = Path(cf_service.__file__).parent+CONFIG_PATH = Path(cf_service.__file__).parents[2] / "config" / "credential_providers.json"+++# --- _service env builders ----------------------------------------------------+++def test_cf_env_keeps_ambient_token_for_ops(monkeypatch):+ monkeypatch.setenv("CLOUDFLARE_API_TOKEN", "cf_ambient")+ env = cf_service.cf_env()+ assert env["NO_COLOR"] == "1"+ # Ambient env token is left alone for ops — cf's documented precedence+ # (and the headless path on remote deployments).+ assert env["CLOUDFLARE_API_TOKEN"] == "cf_ambient"+++def test_login_env_strips_ambient_credential_vars(monkeypatch):+ """With CLOUDFLARE_API_TOKEN set, `cf auth whoami` reports the env+ token (authSource: env) instead of the stored OAuth session — the+ login/status/logout paths must consult cf's OWN store."""+ for var in cf_service._AMBIENT_CREDENTIAL_VARS:+ monkeypatch.setenv(var, "ambient")+ env = cf_service.login_env()+ for var in cf_service._AMBIENT_CREDENTIAL_VARS:+ assert var not in env+ assert env["NO_COLOR"] == "1"+++# --- login banner parsing (source-verified cf 0.2.0 output) ---------------------+++def test_extract_login_url_from_browser_banner():+ # Live-captured cf 0.2.0 stderr shape.+ banner = (+ "Attempting to login via OAuth...\n"+ "Opening a link in your default browser: "+ "https://dash.cloudflare.com/oauth2/auth?response_type=code&client_id=abc&redirect_uri=http%3A%2F%2Flocalhost%3A8877%2Foauth%2Fcallback&scope=openid\n"+ )+ url = cf_service.extract_login_url(banner)+ assert url is not None+ assert url.startswith("https://dash.cloudflare.com/oauth2/auth?response_type=code")+ assert "8877" in url+++def test_extract_login_url_from_headless_banner():+ # The no-browser variant carries the same URL.+ banner = "Visit this link to authenticate: https://dash.cloudflare.com/oauth2/auth?response_type=code&client_id=abc\n"+ assert cf_service.extract_login_url(banner) == (+ "https://dash.cloudflare.com/oauth2/auth?response_type=code&client_id=abc"+ )+++def test_extract_login_url_waits_until_url_present():+ assert cf_service.extract_login_url("Attempting to login via OAuth...\n") is None+ assert cf_service.extract_login_url("") is None+++def test_extract_login_url_strips_ansi():+ banner = "\x1b[36mOpening a link in your default browser:\x1b[0m https://dash.cloudflare.com/oauth2/auth?x=1\x1b[0m\n"+ assert cf_service.extract_login_url(banner) == "https://dash.cloudflare.com/oauth2/auth?x=1"+++# --- _install resolution --------------------------------------------------------+++def test_npm_spec_is_pinned():+ # Preview CLI: @latest would make cold installs non-reproducible and+ # silently change the argv surface this plugin was verified against.+ assert cf_install._NPM_SPEC.startswith("cf@")+ assert "latest" not in cf_install._NPM_SPEC+++async def test_ensure_cf_cli_installs_into_shared_tree(monkeypatch, tmp_path):+ """The system-global cf is never consulted — the binary comes from+ the pinned npm install in the shared packages tree."""+ bin_dir = tmp_path / "node_modules" / ".bin"+ bin_dir.mkdir(parents=True)+ fake_bin = bin_dir / ("cf.cmd" if cf_install.sys.platform == "win32" else "cf")++ calls = {"installs": 0}++ def fake_install():+ calls["installs"] += 1+ fake_bin.write_text("", encoding="utf-8")+ return fake_bin++ monkeypatch.setattr(cf_install, "_cached_path", None)+ monkeypatch.setattr(cf_install, "packages_dir", lambda: tmp_path)+ monkeypatch.setattr(cf_install, "_npm_install", fake_install)++ resolved = await cf_install.ensure_cf_cli()+ assert resolved == fake_bin+ assert calls["installs"] == 1+ # cached for subsequent calls without re-installing+ assert await cf_install.ensure_cf_cli() == fake_bin+ assert calls["installs"] == 1+++def test_cf_binary_never_resolved_from_system_path():+ # Project-local contract: PATH lookup is allowed for npm itself,+ # never for the cf binary.+ src_install = inspect.getsource(cf_install)+ src_service = inspect.getsource(cf_service)+ assert 'which("cf")' not in src_install+ assert "which(" not in src_service+ # resolution goes through the shared-tree shim only+ assert "node_modules" in inspect.getsource(cf_install._shared_tree_bin)+++# --- operations (no auth pre-flight — Stripe pattern) ---------------------------+++def _wire(monkeypatch, tmp_path, run_impl):+ async def fake_ensure():+ return tmp_path / "cf"++ monkeypatch.setattr(cf_install, "ensure_cf_cli", fake_ensure)+ monkeypatch.setattr(cf_action_mod, "run_cli_command", run_impl)+++def _ctx(tmp_path) -> NodeContext:+ return NodeContext(node_id="cf1", node_type="cloudflareAction", workspace_dir=str(tmp_path))+++async def test_whoami_argv_and_env(monkeypatch, tmp_path):+ captured = {}++ async def fake_run(**kwargs):+ captured.update(kwargs)+ return {"success": True, "result": {"authenticated": True, "email": "[email protected]"}, "stdout": "{}", "stderr": "", "error": None}++ _wire(monkeypatch, tmp_path, fake_run)+ node = CloudflareActionNode()+ out = await node.whoami(_ctx(tmp_path), CloudflareActionParams(operation="whoami"))++ assert captured["argv"] == ["auth", "whoami"]+ # env comes from cf_env() — no token was resolved or injected anywhere+ assert captured["env"]["NO_COLOR"] == "1"+ assert out["result"] == {"authenticated": True, "email": "[email protected]"}+++async def test_zones_list_builds_filter_argv(monkeypatch, tmp_path):+ captured = {}++ async def fake_run(**kwargs):+ captured.update(kwargs)+ return {"success": True, "result": [{"name": "example.com"}], "stdout": "[]", "stderr": "", "error": None}++ _wire(monkeypatch, tmp_path, fake_run)+ node = CloudflareActionNode()++ await node.zones_list(_ctx(tmp_path), CloudflareActionParams(operation="zones_list"))+ assert captured["argv"] == ["zones", "list"]++ out = await node.zones_list(+ _ctx(tmp_path),+ CloudflareActionParams(operation="zones_list", name_filter="example.com", account_id="acct1"),+ )+ argv = captured["argv"]+ assert argv[:2] == ["zones", "list"]+ assert argv[argv.index("--name") + 1] == "example.com"+ assert argv[argv.index("--account-id") + 1] == "acct1"+ assert out["result"] == [{"name": "example.com"}]+++async def test_dns_records_list_requires_zone(monkeypatch, tmp_path):+ captured = {}++ async def fake_run(**kwargs):+ captured.update(kwargs)+ return {"success": True, "result": [{"id": "r1"}], "stdout": "[]", "stderr": "", "error": None}++ _wire(monkeypatch, tmp_path, fake_run)+ node = CloudflareActionNode()++ with pytest.raises(NodeUserError, match="zone"):+ await node.dns_records_list(_ctx(tmp_path), CloudflareActionParams(operation="dns_records_list"))++ await node.dns_records_list(_ctx(tmp_path), CloudflareActionParams(operation="dns_records_list", zone="example.com"))+ argv = captured["argv"]+ assert argv[:3] == ["dns", "records", "list"]+ assert argv[argv.index("--zone") + 1] == "example.com"+++async def test_dns_record_create_validates_body_and_builds_argv(monkeypatch, tmp_path):+ captured = {}++ async def fake_run(**kwargs):+ captured.update(kwargs)+ return {"success": True, "result": {"id": "new1"}, "stdout": "{}", "stderr": "", "error": None}++ _wire(monkeypatch, tmp_path, fake_run)+ node = CloudflareActionNode()+ body = '{"type":"A","name":"www","content":"192.0.2.1","ttl":1}'++ with pytest.raises(NodeUserError, match="record_body"):+ await node.dns_record_create(_ctx(tmp_path), CloudflareActionParams(operation="dns_record_create", zone="example.com"))++ with pytest.raises(NodeUserError, match="not valid JSON"):+ await node.dns_record_create(+ _ctx(tmp_path),+ CloudflareActionParams(operation="dns_record_create", zone="example.com", record_body="{oops"),+ )++ await node.dns_record_create(+ _ctx(tmp_path),+ CloudflareActionParams(operation="dns_record_create", zone="example.com", record_body=body),+ )+ argv = captured["argv"]+ assert argv[:3] == ["dns", "records", "create"]+ assert argv[argv.index("--zone") + 1] == "example.com"+ assert argv[argv.index("--body") + 1] == body+++def test_record_body_coerces_llm_dict_args():+ # LLM tool calls may pass the record as a real JSON object.+ params = CloudflareActionParams(+ operation="dns_record_create",+ zone="example.com",+ record_body={"type": "A", "name": "www"},+ )+ assert json.loads(params.record_body) == {"type": "A", "name": "www"}+++async def test_dns_record_delete_uses_positional_id(monkeypatch, tmp_path):+ captured = {}++ async def fake_run(**kwargs):+ captured.update(kwargs)+ return {"success": True, "result": {"id": "r1"}, "stdout": "{}", "stderr": "", "error": None}++ _wire(monkeypatch, tmp_path, fake_run)+ node = CloudflareActionNode()++ with pytest.raises(NodeUserError, match="record_id"):+ await node.dns_record_delete(_ctx(tmp_path), CloudflareActionParams(operation="dns_record_delete", zone="example.com"))++ await node.dns_record_delete(+ _ctx(tmp_path),+ CloudflareActionParams(operation="dns_record_delete", zone="example.com", record_id="r1"),+ )+ # cf 0.2.0: `cf dns records delete <dns-record-id>` — the id is positional.+ assert captured["argv"][:4] == ["dns", "records", "delete", "r1"]+ assert captured["argv"][captured["argv"].index("--zone") + 1] == "example.com"+++async def test_cf_auth_error_surfaces_verbatim_as_node_user_error(monkeypatch, tmp_path):+ """No pre-flight: cf's own 'Not logged in' error IS the auth error."""++ async def fake_run(**kwargs):+ return {"success": False, "stdout": "", "stderr": "Not logged in. Run 'cf auth login' to authenticate.", "error": "exit 1"}++ _wire(monkeypatch, tmp_path, fake_run)+ node = CloudflareActionNode()+ with pytest.raises(NodeUserError, match="cf auth login"):+ await node.zones_list(_ctx(tmp_path), CloudflareActionParams(operation="zones_list"))+++async def test_custom_requires_command_and_shlex_splits(monkeypatch, tmp_path):+ captured = {}++ async def fake_run(**kwargs):+ captured.update(kwargs)+ return {"success": True, "result": {"ok": True}, "stdout": "{}", "stderr": "", "error": None}++ _wire(monkeypatch, tmp_path, fake_run)+ node = CloudflareActionNode()++ with pytest.raises(NodeUserError):+ await node.custom(_ctx(tmp_path), CloudflareActionParams(operation="custom", command=" "))++ await node.custom(+ _ctx(tmp_path),+ CloudflareActionParams(operation="custom", command="dns records update r1 --zone example.com --body '{\"content\":\"192.0.2.2\"}'"),+ )+ assert captured["argv"] == ["dns", "records", "update", "r1", "--zone", "example.com", "--body", '{"content":"192.0.2.2"}']+ assert captured["timeout"] == cf_action_mod._CUSTOM_TIMEOUT+++def test_parse_ndjson_recovers_multi_object_stdout():+ ndjson = '{"id": 1}\n{"id": 2}\n'+ assert CloudflareActionNode._parse_ndjson(ndjson) == [{"id": 1}, {"id": 2}]+ # Single document and non-JSON text are not NDJSON.+ assert CloudflareActionNode._parse_ndjson('{"id": 1}') is None+ assert CloudflareActionNode._parse_ndjson("plain\ntext") is None+++def test_shape_prefers_parsed_result_then_ndjson_then_stdout():+ shaped = CloudflareActionNode._shape("op", {"result": {"a": 1}, "stdout": '{"a": 1}', "stderr": ""})+ assert shaped["result"] == {"a": 1}+ assert "stdout" not in shaped++ shaped = CloudflareActionNode._shape("op", {"result": None, "stdout": '{"id": 1}\n{"id": 2}', "stderr": ""})+ assert shaped["result"] == [{"id": 1}, {"id": 2}]+ assert "stdout" not in shaped++ shaped = CloudflareActionNode._shape("op", {"result": None, "stdout": "plain text", "stderr": "warn"})+ assert shaped["stdout"] == "plain text"+ assert "result" not in shaped+ assert shaped["stderr_tail"] == "warn"+++def test_node_has_no_auth_preflight():+ # Stripe-strict: the CLI owns auth; the node must not pre-check it.+ assert not hasattr(CloudflareActionNode, "_preflight")+ src = inspect.getsource(cf_action_mod)+ assert "PermissionError" not in src+++# --- login handler --------------------------------------------------------------+++async def test_login_answers_within_budget_when_flow_stalls(monkeypatch):+ async def stalled_flow():+ await asyncio.sleep(30)+ return {"success": True, "url": "https://dash.cloudflare.com/oauth2/auth?x=1"}++ monkeypatch.setattr(cf_handlers, "_start_login_flow", stalled_flow)+ monkeypatch.setattr(cf_handlers, "_RESPONSE_BUDGET_SECONDS", 0.05)+ res = await cf_handlers.handle_cloudflare_login({}, websocket=None)+ assert res["success"] is True+ assert res.get("pending") is True+++async def test_login_fast_path_returns_authorize_url(monkeypatch):+ async def instant_flow():+ return {"success": True, "url": "https://dash.cloudflare.com/oauth2/auth?x=1"}++ monkeypatch.setattr(cf_handlers, "_start_login_flow", instant_flow)+ res = await cf_handlers.handle_cloudflare_login({}, websocket=None)+ assert res["success"] is True+ assert res["url"] == "https://dash.cloudflare.com/oauth2/auth?x=1"+ # cf's loopback flow has no device code — nothing to render in the modal.+ assert "verification_code" not in res+++def test_login_flow_handles_already_logged_in_exit():+ # cf delta vs gh: with a live session, `cf auth login` exits without+ # printing an authorize URL — the flow must confirm via whoami and+ # succeed instead of reporting a failure.+ src = inspect.getsource(cf_handlers._start_login_flow)+ assert "whoami_snapshot" in src+ assert "Already logged in" in src+++# --- marker-token + broadcast contract (source introspection) -------------------+++def test_login_success_gates_on_whoami_then_marks_and_broadcasts():+ # Marker + broadcast plumbing is the SHARED module (claude/codex/github/cloudflare).+ assert cf_handlers.mark_logged_in.__module__ == "services.cli_agent._cli_auth"+ complete = inspect.getsource(cf_handlers._complete_login)+ # exit code alone is never trusted — cf exits 0 logged-in AND logged-out;+ # `cf auth whoami` JSON is the gate (and the account-label email source).+ assert "whoami_snapshot" in complete+ assert 'mark_logged_in("cloudflare"' in complete+ assert "credential.oauth.connected" in complete+ snapshot = inspect.getsource(cf_service.whoami_snapshot)+ assert '"auth", "whoami"' in snapshot+ assert "authenticated" in snapshot+++def test_logout_removes_marker_and_broadcasts():+ assert cf_handlers.mark_logged_out.__module__ == "services.cli_agent._cli_auth"+ src = inspect.getsource(cf_handlers.handle_cloudflare_logout)+ assert 'mark_logged_out("cloudflare")' in src+ assert "credential.oauth.disconnected" in src+++def test_login_uses_stripped_env():+ # login/status/logout must consult cf's OWN store, never env tokens.+ for fn in (cf_handlers._start_login_flow, cf_handlers.handle_cloudflare_logout):+ assert "login_env" in inspect.getsource(fn)+ assert "login_env" in inspect.getsource(cf_service.whoami_snapshot)+++def test_ws_handlers_registered():+ assert set(WS_HANDLERS) == {"cloudflare_login", "cloudflare_logout", "cloudflare_status"}+++# --- catalogue + assets ----------------------------------------------------------+++def test_catalogue_entry_is_fieldless_stripe_shape():+ config = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))+ assert "deployment" in config["categories"]+ cloudflare = config["providers"]["cloudflare"]+ assert cloudflare["kind"] == "oauth"+ assert cloudflare["category"] == "deployment"+ assert cloudflare["icon_ref"] == "lobehub:Cloudflare"+ assert cloudflare["ws"] == {+ "login": "cloudflare_login",+ "logout": "cloudflare_logout",+ "status": "cloudflare_status",+ }+ # cf owns the token — the modal stores nothing (Stripe shape).+ assert "fields" not in cloudflare+++def test_credential_class_shape():+ assert CloudflareCredential.id == "cloudflare"+ assert CloudflareCredential.auth == "custom"+++def test_plugin_folder_assets():+ # Icon is the official lobehub brand glyph via visuals.json — a+ # co-located icon.svg would silently override it.+ assert not (PLUGIN_DIR / "icon.svg").exists()+ meta = json.loads((PLUGIN_DIR / "meta.json").read_text(encoding="utf-8"))+ assert meta["color"] == "#F38020"++ visuals = json.loads((PLUGIN_DIR.parent / "visuals.json").read_text(encoding="utf-8"))+ entry = visuals["cloudflareAction"]+ assert entry["icon"] == "lobehub:Cloudflare"+ assert entry["skill"] == "cloudflare-skill"+ # tool_name ("cloudflare") != snake_case(node type) — the lowercase+ # alias carries icon + color for the Master Skill row.+ alias = visuals["cloudflare"]+ assert alias["icon"] == "lobehub:Cloudflare"+ assert alias["color"].startswith("#")++ skill_md = PLUGIN_DIR.parents[1] / "skills" / "cloudflare" / "cloudflare-skill" / "SKILL.md"+ assert skill_md.exists()diff --git a/server/tests/test_plugin_self_containment.py b/server/tests/test_plugin_self_containment.pyindex dfd1c9c6..718fb742 100644--- a/server/tests/test_plugin_self_containment.py+++ b/server/tests/test_plugin_self_containment.py@@ -59,6 +59,7 @@ from services import ws_handler_registry_MIGRATED_PLUGINS = ("android","browser",+ "cloudflare","code","email","github",@@ -74,6 +75,7 @@ _MIGRATED_PLUGINS = (# ``register_ws_handlers`` from its package ``__init__.py``._PLUGINS_WITH_HANDLERS = ("android",+ "cloudflare","github","google","stripe",