Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(stripe): 3 root causes blocking OAuth + Nushell `&&` guard
trohitgafe4a761b782
diff --git a/server/config/credential_providers.json b/server/config/credential_providers.jsonindex 118ea1f5..cd4b8d7a 100644--- a/server/config/credential_providers.json+++ b/server/config/credential_providers.json@@ -447,7 +447,6 @@"color": "dracula.purple","kind": "oauth","icon_ref": "asset:stripe",- "status_hook": "stripe","ws": {"login": "stripe_login","logout": "stripe_logout",diff --git a/server/nodes/filesystem/shell.py b/server/nodes/filesystem/shell.pyindex 7c1253ad..c96160ee 100644--- a/server/nodes/filesystem/shell.py+++ b/server/nodes/filesystem/shell.py@@ -2,11 +2,21 @@from __future__ import annotations+import refrom typing import Any, Optionalfrom pydantic import BaseModel, ConfigDict, Field-from services.plugin import ActionNode, NodeContext, Operation, TaskQueue+from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue+++# Bash chain-operators (` && ` / ` || `) are explicitly rejected by the+# Nushell parser. Detect them up-front so the LLM gets a corrective+# message ("use `;` or `try { … }`") instead of nu's+# ``shell_andand`` / ``shell_oror`` parse error two layers down.+# Surrounding spaces ensure we don't flag valid nu syntax accidentally+# (closure params `|x|` never carry spaces around the pipe pair).+_BASH_CHAIN_RE = re.compile(r"\s(\&\&|\|\|)\s")class ShellParams(BaseModel):@@ -51,6 +61,19 @@ class ShellNode(ActionNode):from ._backend import get_backendlog = get_logger(__name__)++ # Pre-flight: catch the most common bash-style chain mistake before+ # Nushell's parser does, so the LLM sees an actionable hint instead+ # of ``nu::parser::shell_andand``. Documented in+ # ``server/skills/terminal/shell-skill/SKILL.md``.+ if (m := _BASH_CHAIN_RE.search(params.command)):+ op = m.group(1)+ replacement = "; (sequential)" if op == "&&" else "try { … } catch { … }"+ raise NodeUserError(+ f"Nushell does not support `{op}`. Use `{replacement}` instead. "+ "See shell-skill: https://www.nushell.sh/book/control_flow.html"+ )+backend = get_backend(params.model_dump(), ctx.raw)# "non-blocking" here only meant the asyncio event loop isn't# blocked (the call is offloaded via ``to_thread``). Thediff --git a/server/nodes/stripe/_handlers.py b/server/nodes/stripe/_handlers.pyindex c89a952c..c678e193 100644--- a/server/nodes/stripe/_handlers.py+++ b/server/nodes/stripe/_handlers.py@@ -23,6 +23,7 @@ from __future__ import annotationsimport asyncioimport json+import shlexfrom typing import Any, Dictfrom fastapi import WebSocket@@ -90,12 +91,20 @@ async def _mark_logged_out() -> None:await container.auth_service().remove_oauth_tokens("stripe")-async def _broadcast_catalogue_updated() -> None:- """Trigger the generic catalogue invalidation listener already wired- in WebSocketContext (`case 'credential_catalogue_updated'`). The- frontend refetches the catalogue and sees the new stored state."""+async def _broadcast_credential_event(event_type: str) -> None:+ """Emit a CloudEvents-shaped credential mutation broadcast.++ Wraps :class:`services.events.envelope.WorkflowEvent` via the canonical+ helper :func:`StatusBroadcaster.broadcast_credential_event` — same+ invariant that ``handle_save_api_key`` / ``handle_twitter_logout`` are+ locked to in ``tests/credentials/test_credential_broadcasts.py``. The+ frontend listens on ``case 'credential_catalogue_updated'`` (the+ helper's outer wire-format type) and invalidates the catalogue query.+ """from services.status_broadcaster import get_status_broadcaster- await get_status_broadcaster().broadcast({"type": "credential_catalogue_updated"})+ await get_status_broadcaster().broadcast_credential_event(+ event_type, provider="stripe",+ )async def handle_stripe_trigger(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:@@ -111,28 +120,60 @@ async def handle_stripe_trigger(data: Dict[str, Any], websocket: WebSocket) -> Dasync def handle_stripe_login(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:"""Step 1 of CLI OAuth: get the browser URL + verification code."""+ logger.info("[Stripe] login flow: step 1/2 (--non-interactive) starting")binary = await _resolved_binary()if not binary:+ logger.warning("[Stripe] login failed: CLI binary unavailable")return {"success": False,"error": "Stripe CLI install failed. Manual install: https://stripe.com/docs/stripe-cli#install",}+ logger.info("[Stripe] using binary: %s", binary)result = await run_cli_command(binary=binary, argv=["login", "--non-interactive"], timeout=10.0,)if not result["success"]:+ logger.warning(+ "[Stripe] login step 1 CLI failure: %s | stderr=%r",+ result.get("error"), (result.get("stderr") or "")[:300],+ )return resulttry:info = json.loads(result["stdout"])except json.JSONDecodeError as e:+ logger.warning("[Stripe] login step 1 unparseable stdout=%r", result["stdout"][:300])return {"success": False, "error": f"unparseable stripe login response: {e}"}- next_step = info.get("next_step")+ next_step_raw = info.get("next_step")url = info.get("browser_url") or info.get("url")- if not (url and next_step):+ if not (url and next_step_raw):+ logger.warning("[Stripe] login response missing url/next_step: keys=%s", list(info.keys()))return {"success": False, "error": "stripe login response missing browser_url / next_step"}- asyncio.create_task(_complete_login(binary, next_step))+ # ``next_step`` is the LITERAL shell command the user would otherwise+ # type, e.g.:+ # stripe login --complete 'https://dashboard.stripe.com/stripecli/auth/…?secret=…'+ # Feeding the whole string into ``--complete`` makes the CLI try to+ # URL-parse it and bail with "first path segment in URL cannot contain+ # colon". Tokenise it and pass just the auth URL (the last argument)+ # to ``--complete``.+ try:+ complete_url = shlex.split(next_step_raw)[-1]+ except (ValueError, IndexError):+ complete_url = next_step_raw+ if not complete_url.startswith("http"):+ logger.warning(+ "[Stripe] could not extract auth URL from next_step=%r — falling back to raw value",+ next_step_raw,+ )+ complete_url = next_step_raw++ logger.info(+ "[Stripe] login step 1 ok: code=%s, browser_url issued — opening on frontend; "+ "spawning step 2 (--complete) in background (timeout=%ss)",+ info.get("verification_code"), _LOGIN_TIMEOUT_SECONDS,+ )+ asyncio.create_task(_complete_login(binary, complete_url))return {"success": True,"url": url,@@ -146,15 +187,44 @@ async def _complete_login(binary: str, next_step: str) -> None:same kind of marker the Google / Twitter callbacks write so thecatalogue's stored-check flips, then auto-start the listendaemon and trigger the generic catalogue refresh on the frontend."""- await run_cli_command(- binary=binary, argv=["login", "--complete", next_step],- timeout=_LOGIN_TIMEOUT_SECONDS,+ logger.info("[Stripe] login step 2/2 polling for browser confirmation")+ try:+ result = await run_cli_command(+ binary=binary, argv=["login", "--complete", next_step],+ timeout=_LOGIN_TIMEOUT_SECONDS,+ )+ except Exception as e:+ # ``asyncio.create_task`` swallows exceptions silently — log them.+ # Nothing was persisted, so no broadcast: catalogue state is unchanged.+ logger.exception("[Stripe] login step 2 raised unexpectedly: %s", e)+ return++ if not result.get("success"):+ logger.warning(+ "[Stripe] login step 2 CLI failure: %s | stderr=%r",+ result.get("error"), (result.get("stderr") or "")[:300],+ )++ if not is_logged_in():+ logger.warning(+ "[Stripe] step 2 finished but ``is_logged_in()`` is False — config file %s missing/empty; "+ "user likely closed the browser before authorising",+ stripe_config_path(),+ )+ return++ logger.info(+ "[Stripe] auth successful — credentials written to %s; persisting catalogue marker + starting listen daemon",+ stripe_config_path(),)- if is_logged_in():- logger.info("[Stripe] login completed; auto-starting listen daemon")- await _mark_logged_in()- await get_listen_source().start()- await _broadcast_catalogue_updated()+ await _mark_logged_in()+ logger.info("[Stripe] catalogue marker token persisted (auth_service.store_oauth_tokens)")+ start_result = await get_listen_source().start()+ if start_result.get("success"):+ logger.info("[Stripe] listen daemon started (pid=%s)", start_result.get("status", {}).get("pid"))+ else:+ logger.warning("[Stripe] listen daemon failed to start: %s", start_result.get("error"))+ await _broadcast_credential_event("credential.oauth.connected")async def handle_stripe_logout(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:@@ -162,6 +232,7 @@ async def handle_stripe_logout(data: Dict[str, Any], websocket: WebSocket) -> Diclear ``~/.config/stripe/config.toml``. Mirror the Google/Twitterlogout shape: drop the catalogue marker token + broadcast thegeneric catalogue invalidation so the modal flips immediately."""+ logger.info("[Stripe] logout starting: stopping daemon + running 'stripe logout --all'")await get_listen_source().stop()cached = stripe_cli_path()if cached is None:@@ -169,10 +240,16 @@ async def handle_stripe_logout(data: Dict[str, Any], websocket: WebSocket) -> Diif cfg.exists():cfg.unlink(missing_ok=True)result: Dict[str, Any] = {"success": True, "message": "Logged out (CLI not yet installed; cleared config file)"}+ logger.info("[Stripe] logout fallback: CLI not installed; deleted %s", cfg)else:result = await run_cli_command(binary=str(cached), argv=["logout", "--all"], timeout=10.0)+ logger.info(+ "[Stripe] logout CLI result: success=%s err=%s",+ result.get("success"), result.get("error"),+ )await _mark_logged_out()- await _broadcast_catalogue_updated()+ await _broadcast_credential_event("credential.oauth.disconnected")+ logger.info("[Stripe] logout complete: marker token removed + catalogue broadcast sent")return resultdiff --git a/server/nodes/stripe/_source.py b/server/nodes/stripe/_source.pyindex 654ad669..f2d37273 100644--- a/server/nodes/stripe/_source.py+++ b/server/nodes/stripe/_source.py@@ -18,6 +18,7 @@ from __future__ import annotationsimport asyncioimport osimport re+import shlexfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Dict, Optional@@ -81,11 +82,13 @@ class StripeListenSource(DaemonEventSource):# (populated by `stripe login`). No --api-key flag here.# Binary path is resolved by `ensure_stripe_cli` (called from# the start() override below) and cached for sync access here.+ # ``shlex.quote`` so Windows backslashes survive ProcessService's+ # ``shlex.split`` round-trip (POSIX-mode parser eats raw ``\``).from core.config import Settingsfrom ._install import stripe_cli_pathport = int(Settings().port)- binary = str(stripe_cli_path() or "stripe")+ binary = shlex.quote(str(stripe_cli_path() or "stripe"))return (f"{binary} listen --forward-to http://localhost:{port}/webhook/stripe "f"--print-secret"@@ -96,8 +99,10 @@ class StripeListenSource(DaemonEventSource):framework's daemon-start path (which calls ``build_command``)."""from ._install import ensure_stripe_clitry:- await ensure_stripe_cli()+ path = await ensure_stripe_cli()+ logger.info("[Stripe] daemon start: CLI binary resolved at %s", path)except Exception as e:+ logger.warning("[Stripe] daemon start failed at install step: %s", e)return {"success": False, "error": f"Stripe CLI install failed: {e}"}return await super().start()@@ -109,6 +114,7 @@ class StripeListenSource(DaemonEventSource):def parse_line(self, stream: str, line: str) -> Optional[WorkflowEvent]:if stream == "stderr" and (m := _SECRET_RE.search(line)):secret = m.group(0)+ logger.info("[Stripe] whsec_… signing secret detected in daemon stderr — persisting")asyncio.create_task(self._persist_secret(secret))return None@@ -116,7 +122,10 @@ class StripeListenSource(DaemonEventSource):try:from core.container import containerawait container.auth_service().store_api_key(_SECRET_FIELD, secret, models=[])- logger.info("[Stripe] webhook signing secret captured and persisted")+ logger.info(+ "[Stripe] webhook signing secret persisted (key=%s, len=%d)",+ _SECRET_FIELD, len(secret),+ )except Exception as e:logger.warning("[Stripe] persist secret failed: %s", e)diff --git a/server/services/events/daemon.py b/server/services/events/daemon.pyindex 6c0c6df1..07979d60 100644--- a/server/services/events/daemon.py+++ b/server/services/events/daemon.py@@ -4,14 +4,18 @@ events into the framework.Used by stripe-listen, future telegram/whatsapp daemon migrations, andany plugin that wraps a CLI tool. The class delegates lifecycle to:class:`services.process_service.ProcessService` (already battle-tested:-PATHEXT-aware, ``kill_tree`` cleanup, log capture) and adds:--- typed event emission via :meth:`parse_line` (one event per stdout line,- optionally per stderr line)-- declarative ``build_command(secrets) -> str`` so credential resolution- is uniform across daemons-- pre-flight ``shutil.which`` check with a clear error if the binary- isn't on PATH+PATHEXT-aware, ``kill_tree`` cleanup, log capture, terminal broadcast)+and subscribes to its standard per-line callback hook for typed event+emission. We do NOT re-tail the on-disk log files — that's the same+data ProcessService already streamed to us via ``line_handler``.++Subclasses contribute:++- :meth:`build_command(secrets) -> str` — full command string+- :meth:`parse_line(stream, line) -> Optional[WorkflowEvent]` — turn one+ line into one event (or ``None`` for log-only lines)+- :attr:`binary_name` (optional) — pre-flight ``shutil.which`` check+ with a clear error if the binary isn't on PATH"""from __future__ import annotations@@ -51,7 +55,6 @@ class DaemonEventSource(EventSource):super().__init__()self._pid: Optional[int] = Noneself._lock = asyncio.Lock()- self._tail_task: Optional[asyncio.Task] = Noneself._queue: asyncio.Queue[WorkflowEvent] = asyncio.Queue()@property@@ -94,10 +97,21 @@ class DaemonEventSource(EventSource):async def start(self) -> Dict[str, Any]:async with self._lock:if self._started:+ logger.info("[%s] start() noop — already running (pid=%s)", self.type, self._pid)return {"success": True, "message": "already running", "status": await self.status()}+ logger.info("[%s] start() entered: resolving secrets + checking credential gate", self.type)secrets = await self._resolve_secrets()- if self.credential is not None and not secrets.get("api_key"):+ # Gate via :meth:`has_credential` so subclasses that authenticate+ # without an ``api_key`` field (Stripe — auth lives in the CLI's+ # config file, signalled by ``is_logged_in()``) can override the+ # check. The default ``has_credential`` still tests+ # ``secrets["api_key"]`` so api-key plugins keep working.+ if self.credential is not None and not await self.has_credential():+ logger.warning(+ "[%s] start() blocked: has_credential() returned False — refusing to spawn daemon",+ self.type,+ )return {"success": False, "error": f"{self.type}: credential required"}if self.binary_name and shutil.which(self.binary_name) is None:@@ -111,6 +125,7 @@ class DaemonEventSource(EventSource):command=cmd,workflow_id=self.workflow_namespace,working_directory=str(cwd),+ line_handler=self._on_line,)if not result.get("success"):return result@@ -118,20 +133,12 @@ class DaemonEventSource(EventSource):self._pid = (result.get("result") or {}).get("pid")self._started = Trueself._stopped = False- self._tail_task = asyncio.create_task(self._tail_logs(cwd))logger.info("[%s] daemon started pid=%s", self.type, self._pid)return {"success": True, "message": f"started (pid {self._pid})", "status": await self.status()}async def stop(self) -> Dict[str, Any]:async with self._lock:self._stopped = True- if self._tail_task and not self._tail_task.done():- self._tail_task.cancel()- try:- await self._tail_task- except asyncio.CancelledError:- pass- self._tail_task = Noneawait get_process_service().stop(name=self.process_name, workflow_id=self.workflow_namespace,)@@ -143,34 +150,12 @@ class DaemonEventSource(EventSource):await self.stop()return await self.start()- async def _tail_logs(self, cwd: Path) -> None:- """Tail both stdout.log and stderr.log; feed each new line to- :meth:`parse_line` and queue any returned events."""- await asyncio.gather(- self._tail_one(cwd / ".processes" / self.process_name / "stdout.log", "stdout"),- self._tail_one(cwd / ".processes" / self.process_name / "stderr.log", "stderr"),- )-- async def _tail_one(self, path: Path, stream: str) -> None:- offset = 0- try:- while not self._stopped:- if path.exists():- size = path.stat().st_size- if size > offset:- with path.open("r", encoding="utf-8", errors="replace") as f:- f.seek(offset)- for raw in f:- if not raw.endswith("\n"):- break- line = raw.rstrip("\n")- offset = f.tell()- event = self.parse_line(stream, line)- if event is not None:- await self._queue.put(event)- await asyncio.sleep(0.5)- except asyncio.CancelledError:- raise+ async def _on_line(self, stream: str, line: str) -> None:+ """ProcessService callback: one decoded stdout/stderr line.+ Subclasses' :meth:`parse_line` decides whether to emit an event."""+ event = self.parse_line(stream, line)+ if event is not None:+ await self._queue.put(event)async def emit(self) -> AsyncIterator[WorkflowEvent]:while not self._stopped:diff --git a/server/services/process_service.py b/server/services/process_service.pyindex 64245f4b..3354d014 100644--- a/server/services/process_service.py+++ b/server/services/process_service.py@@ -16,7 +16,7 @@ import shutilfrom dataclasses import dataclass, fieldfrom datetime import datetimefrom pathlib import Path-from typing import Any, Dict, List, Optional+from typing import Any, Awaitable, Callable, Dict, List, Optionalfrom core.logging import get_loggerfrom services._supervisor.util import kill_tree@@ -26,6 +26,10 @@ logger = get_logger(__name__)MAX_PROCESSES = 10 # Default limit, configurable via Settings panel+# (stream_name, line) -> awaitable. Invoked once per decoded stdout/stderr line.+LineHandler = Callable[[str, str], Awaitable[None]]++@dataclassclass ManagedProcess:name: str@@ -43,6 +47,11 @@ class ManagedProcess:exit_code: Optional[int] = Nonestdout_lines: int = 0stderr_lines: int = 0+ # Optional per-line callback: framework-level subscribers (e.g. the+ # generalised event source `DaemonEventSource`) install this to ingest+ # the daemon's stdout/stderr without re-tailing the log files we already+ # write for the Terminal tab.+ line_handler: Optional[LineHandler] = Noneclass ProcessService:@@ -70,8 +79,17 @@ class ProcessService:command: str,workflow_id: str = "default",working_directory: str = "",+ *,+ line_handler: Optional[LineHandler] = None,) -> Dict[str, Any]:- """Start a long-running process."""+ """Start a long-running process.++ ``line_handler``: optional ``async (stream_name, line) -> None``+ callback invoked for every decoded stdout/stderr line, AFTER the+ line has been written to the log file and broadcast to the+ Terminal tab. Used by ``DaemonEventSource`` to parse subprocess+ output into typed events without re-tailing the log files.+ """if not command:return {"success": False, "error": "command is required"}@@ -170,6 +188,7 @@ class ProcessService:working_directory=cwd,process=proc,log_dir=log_dir,+ line_handler=line_handler,)managed.stdout_task = asyncio.create_task(@@ -392,6 +411,16 @@ class ProcessService:"message": text,"source": source,})++ # Optional framework-level subscriber.+ if managed.line_handler is not None:+ try:+ await managed.line_handler(stream_name, text)+ except Exception as cb_err:+ logger.debug(+ "[Process] line_handler %s/%s raised: %s",+ managed.name, stream_name, cb_err,+ )except asyncio.CancelledError:passexcept Exception as e: