Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor(cli_agent): Phase 3 — split _handlers.py, drop dead router refs
trohitg02fa5978aa08
diff --git a/server/nodes/agent/claude_code_agent/__init__.py b/server/nodes/agent/claude_code_agent/__init__.pyindex 98bfcbc1..5d9333eb 100644--- a/server/nodes/agent/claude_code_agent/__init__.py+++ b/server/nodes/agent/claude_code_agent/__init__.py@@ -51,6 +51,9 @@ from services.cli_agent.factory import ( # noqa: E402register_session_pool,register_skill_materialiser,)+from services.ws_handler_registry import register_ws_handlers # noqa: E402++from ._handlers import WS_HANDLERS as _CLAUDE_WS_HANDLERS # noqa: E402from ._pool import get_session_pool as _claude_get_session_pool # noqa: E402from ._provider import AnthropicClaudeProvider # noqa: E402from ._skills import materialise_skills as _claude_materialise_skills # noqa: E402@@ -58,6 +61,7 @@ from ._skills import materialise_skills as _claude_materialise_skills # noqa: Eregister_provider("claude", AnthropicClaudeProvider)register_session_pool("claude", _claude_get_session_pool)register_skill_materialiser("claude", _claude_materialise_skills)+register_ws_handlers(_CLAUDE_WS_HANDLERS)# Claude Code-supported models. Perdiff --git a/server/nodes/agent/claude_code_agent/_handlers.py b/server/nodes/agent/claude_code_agent/_handlers.pynew file mode 100644index 00000000..98fc5e91--- /dev/null+++ b/server/nodes/agent/claude_code_agent/_handlers.py@@ -0,0 +1,166 @@+"""WebSocket handlers for claude code CLI-managed OAuth.++Self-registered into ``services.ws_handler_registry`` from this+plugin's ``__init__.py``. Wire format matches the prior unified+handlers (``claude_code_login`` / ``claude_code_logout``) — frontend+dispatches with an empty payload.++Claude flow uses the documented CLI subcommands from+https://code.claude.com/docs/en/cli-reference (``claude auth login`` /+``status`` / ``logout``). Every subprocess invocation goes through+``services.events.cli.run_cli_command`` (Stripe precedent — see+``nodes/stripe/_handlers.py``); the CLI owns its own credentials file+and we never touch it.++Login lifecycle:++1. ``handle_claude_code_login`` schedules ``run_claude_login`` as an+ ``asyncio.create_task`` (mirrors Stripe's ``stripe login --complete``)+ and returns immediately. The CLI opens the user's browser; up to+ 10 minutes are allowed for the flow to complete.+2. When the task resolves, ``_finalize_claude_login`` reads+ ``claude auth status``, stores the synthetic ``"cli-managed"``+ marker along with the user's ``email``/``orgName`` via+ ``auth_service.store_oauth_tokens()``, and fires+ ``broadcast_credential_event("credential.oauth.connected", ...)`` —+ the frontend's ``WebSocketContext`` re-fetches the catalogue.++Logout runs ``claude auth logout`` (CLI clears its own credentials),+drops the catalogue marker, and broadcasts ``.disconnected``.++Shared cli-managed-marker helpers (``_mark_logged_in`` /+``_mark_logged_out`` / ``_broadcast_credential_event``) live in+:mod:`services.cli_agent._cli_auth` so codex's own handlers can+reuse them — they're CLI-agnostic plumbing, not claude-specific.+"""++from __future__ import annotations++import asyncio+from typing import Any, Awaitable, Callable, Dict++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 ._oauth import (+ claude_auth_logout,+ claude_auth_status_info,+ run_claude_login,+)++logger = get_logger(__name__)+++_CATALOGUE_KEY = "claude_code"+++async def _finalize_claude_login() -> None:+ """Run ``claude auth login`` to completion, then store user info ++ broadcast on success."""+ try:+ envelope = await run_claude_login()+ if not envelope.get("success"):+ logger.warning(+ "[claude_code_login] CLI exited unsuccessfully: %s",+ envelope.get("error") or envelope.get("stderr"),+ )+ return++ info = await claude_auth_status_info()+ if not info.get("loggedIn"):+ logger.warning(+ "[claude_code_login] CLI exited cleanly but auth status "+ "reports not logged in: %s", info,+ )+ return++ email = info.get("email")+ org_name = info.get("orgName")+ await mark_logged_in(_CATALOGUE_KEY, email=email, name=org_name)+ await broadcast_credential_event(+ "credential.oauth.connected", provider=_CATALOGUE_KEY,+ )+ logger.info(+ "[claude_code_login] connected as %s (%s · %s)",+ email or "unknown",+ org_name or "unknown org",+ info.get("subscriptionType") or "unknown plan",+ )+ except asyncio.CancelledError:+ raise+ except Exception as exc: # pragma: no cover — defensive+ logger.exception("[claude_code_login] finalize failed: %s", exc)+++async def handle_claude_code_login(+ data: Dict[str, Any], # noqa: ARG001 — frontend sends {}+ websocket: WebSocket, # noqa: ARG001 — registry signature+) -> Dict[str, Any]:+ """Spawn ``claude auth login`` in the background; let the CLI open+ the user's browser. Idempotent re-click syncs the marker without+ re-running the flow."""+ info = await claude_auth_status_info()+ if info.get("loggedIn"):+ try:+ await mark_logged_in(+ _CATALOGUE_KEY,+ email=info.get("email"),+ name=info.get("orgName"),+ )+ await broadcast_credential_event(+ "credential.oauth.connected", provider=_CATALOGUE_KEY,+ )+ except Exception as exc:+ logger.warning("[claude_code_login] mark/broadcast failed: %s", exc)+ return {+ "success": True,+ "already_logged_in": True,+ "email": info.get("email"),+ "org_name": info.get("orgName"),+ "subscription_type": info.get("subscriptionType"),+ "message": "Already authenticated; refreshed status.",+ }++ asyncio.create_task(_finalize_claude_login(), name="claude_code_login")+ return {+ "success": True,+ "message": "Claude is opening your browser to authenticate.",+ }+++async def handle_claude_code_logout(+ data: Dict[str, Any], # noqa: ARG001+ websocket: WebSocket, # noqa: ARG001+) -> Dict[str, Any]:+ """Run ``claude auth logout`` (CLI clears its own credentials), drop+ the catalogue marker, broadcast ``.disconnected``."""+ try:+ await claude_auth_logout()+ await mark_logged_out(_CATALOGUE_KEY)+ await broadcast_credential_event(+ "credential.oauth.disconnected", provider=_CATALOGUE_KEY,+ )+ except Exception as exc:+ logger.warning("[claude_code_logout] failed: %s", exc)+ return {"success": False, "error": str(exc)}+ return {"success": True}+++# ---------------------------------------------------------------------------+# Registry payload — plugin __init__.py registers these into+# services.ws_handler_registry on package import.+# ---------------------------------------------------------------------------++WSHandler = Callable[[Dict[str, Any], WebSocket], Awaitable[Dict[str, Any]]]++WS_HANDLERS: Dict[str, WSHandler] = {+ "claude_code_login": handle_claude_code_login,+ "claude_code_logout": handle_claude_code_logout,+}diff --git a/server/routers/websocket.py b/server/routers/websocket.pyindex dd80d7e8..a350b9b6 100644--- a/server/routers/websocket.py+++ b/server/routers/websocket.py@@ -2767,9 +2767,13 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {"save_api_key": handle_save_api_key,"delete_api_key": handle_delete_api_key,- # Claude OAuth operations- "claude_oauth_login": handle_claude_oauth_login,- "claude_oauth_status": handle_claude_oauth_status,+ # Claude/Codex login handlers live in the plugin folders + framework:+ # - ``claude_code_login`` / ``claude_code_logout`` registered by+ # ``nodes/agent/claude_code_agent/__init__.py``.+ # - ``codex_cli_login`` / ``codex_cli_logout`` registered by+ # ``services/cli_agent/__init__.py``.+ # Both go through ``services.ws_handler_registry``; nothing to+ # mount in MESSAGE_HANDLERS here.# Twitter OAuth operationsdiff --git a/server/services/cli_agent/_cli_auth.py b/server/services/cli_agent/_cli_auth.pynew file mode 100644index 00000000..b9cc0768--- /dev/null+++ b/server/services/cli_agent/_cli_auth.py@@ -0,0 +1,57 @@+"""Shared cli-managed-marker auth helpers for CLI plugins.++Used by both claude (``nodes/agent/claude_code_agent/_handlers.py``)+and codex (``services/cli_agent/_handlers.py`` until ``codex_agent``+adopts the plugin-folder layout). The marker token + storage ++broadcast plumbing is CLI-agnostic — each provider just decides+when to call ``mark_logged_in`` / ``mark_logged_out`` /+``broadcast_credential_event`` based on its own CLI status flow.++Pattern matches Stripe (``nodes/stripe/_handlers.py``): the catalogue's+generic ``stored`` check flips when the synthetic ``"cli-managed"``+marker is present in ``auth_service``, so the FE Credentials modal+shows "Connected" without per-provider FE code.+"""++from __future__ import annotations++from typing import Optional++# Synthetic marker stored in ``auth_service`` after a successful CLI+# login. Matches ``nodes/stripe/_handlers.py::_MARKER_TOKEN``.+MARKER_TOKEN = "cli-managed"+++async def mark_logged_in(+ catalogue_key: str,+ *,+ email: Optional[str] = None,+ name: Optional[str] = None,+) -> None:+ """Store the cli-managed marker for ``catalogue_key``.++ Lazy-imports the container so this module stays a leaf service.+ """+ from core.container import container+ await container.auth_service().store_oauth_tokens(+ provider=catalogue_key,+ access_token=MARKER_TOKEN,+ refresh_token=MARKER_TOKEN,+ email=email,+ name=name,+ )+++async def mark_logged_out(catalogue_key: str) -> None:+ """Drop the cli-managed marker for ``catalogue_key``."""+ from core.container import container+ await container.auth_service().remove_oauth_tokens(catalogue_key)+++async def broadcast_credential_event(event_type: str, provider: str) -> None:+ """Fire a CloudEvents-shaped catalogue-invalidation. Frontend listens+ via ``WebSocketContext`` and re-fetches the catalogue."""+ from services.status_broadcaster import get_status_broadcaster+ await get_status_broadcaster().broadcast_credential_event(+ event_type, provider=provider,+ )diff --git a/server/services/cli_agent/_handlers.py b/server/services/cli_agent/_handlers.pyindex 618fd64e..0fcb5046 100644--- a/server/services/cli_agent/_handlers.py+++ b/server/services/cli_agent/_handlers.py@@ -1,191 +1,32 @@-"""Per-provider WebSocket handlers for CLI-managed OAuth.+"""WebSocket handlers for CLI providers that still live under the+generic framework.Self-registered into ``services.ws_handler_registry`` from-``services/cli_agent/__init__.py``. Naming convention matches Twitter /-Google / Stripe — each provider gets its own message type-(``claude_code_login`` / ``claude_code_logout`` / ``codex_cli_login`` /-``codex_cli_logout``); the frontend dispatches with an empty payload.--Claude flow uses the documented CLI subcommands from-https://code.claude.com/docs/en/cli-reference (``claude auth login`` /-``status`` / ``logout``). Every subprocess invocation goes through-``services.events.cli.run_cli_command`` (Stripe precedent — see-``nodes/stripe/_handlers.py``); the CLI owns its own credentials file-and we never touch it.--Login lifecycle:--1. ``handle_claude_code_login`` schedules ``run_claude_login`` as an- ``asyncio.create_task`` (mirrors Stripe's ``stripe login --complete``)- and returns immediately. The CLI opens the user's browser; up to- 10 minutes are allowed for the flow to complete.-2. When the task resolves, ``_finalize_claude_login`` reads- ``claude auth status``, stores the synthetic ``"cli-managed"`` marker- along with the user's ``email``/``orgName`` via- ``auth_service.store_oauth_tokens()``, and fires- ``broadcast_credential_event("credential.oauth.connected", ...)`` —- the frontend's ``WebSocketContext`` re-fetches the catalogue.--Logout runs ``claude auth logout`` (CLI clears its own credentials),-drops the catalogue marker, and broadcasts ``.disconnected``.--Codex login is not yet wired (no ``codex_oauth.py``); the handler returns-a graceful error pointing the user at the manual flow.+``services/cli_agent/__init__.py``. Currently only codex stays here —+claude's handlers moved to ``nodes/agent/claude_code_agent/_handlers.py``+per the canonical plugin-folder pattern. Once ``codex_agent`` adopts+the per-folder layout this whole module goes with it.++Shared cli-managed-marker plumbing (``mark_logged_in`` /+``mark_logged_out`` / ``broadcast_credential_event``) lives in+:mod:`services.cli_agent._cli_auth` and is CLI-agnostic — both+claude and codex handlers consume it."""from __future__ import annotations-import asyncio-from typing import Any, Awaitable, Callable, Dict, Optional+from typing import Any, Awaitable, Callable, Dictfrom fastapi import WebSocketfrom core.logging import get_logger-logger = get_logger(__name__)---# Synthetic marker stored in `auth_service` after a successful CLI login,-# matching `nodes/stripe/_handlers.py:_MARKER_TOKEN`. Lets the catalogue's-# generic `stored` check flip without per-provider code in the catalogue-# handler.-_MARKER_TOKEN = "cli-managed"---# ----------------------------------------------------------------------------# Marker-token + credential-event broadcast (Stripe pattern)-# -----------------------------------------------------------------------------async def _mark_logged_in(- catalogue_key: str,- *,- email: Optional[str] = None,- name: Optional[str] = None,-) -> None:- from core.container import container- await container.auth_service().store_oauth_tokens(- provider=catalogue_key,- access_token=_MARKER_TOKEN,- refresh_token=_MARKER_TOKEN,- email=email,- name=name,- )---async def _mark_logged_out(catalogue_key: str) -> None:- from core.container import container- await container.auth_service().remove_oauth_tokens(catalogue_key)+from services.cli_agent._cli_auth import (+ broadcast_credential_event,+ mark_logged_out,+)--async def _broadcast_credential_event(event_type: str, provider: str) -> None:- """Fire a CloudEvents-shaped catalogue-invalidation. Frontend listens- via ``WebSocketContext`` and re-fetches the catalogue."""- from services.status_broadcaster import get_status_broadcaster- await get_status_broadcaster().broadcast_credential_event(- event_type, provider=provider,- )---# ----------------------------------------------------------------------------# Claude — `claude auth login` / `auth status` / `auth logout`-# -----------------------------------------------------------------------------async def _finalize_claude_login() -> None:- """Run ``claude auth login`` to completion, then store user info +- broadcast on success."""- from nodes.agent.claude_code_agent._oauth import claude_auth_status_info, run_claude_login-- try:- envelope = await run_claude_login()- if not envelope.get("success"):- logger.warning(- "[claude_code_login] CLI exited unsuccessfully: %s",- envelope.get("error") or envelope.get("stderr"),- )- return-- info = await claude_auth_status_info()- if not info.get("loggedIn"):- logger.warning(- "[claude_code_login] CLI exited cleanly but auth status "- "reports not logged in: %s", info,- )- return-- email = info.get("email")- org_name = info.get("orgName")- await _mark_logged_in("claude_code", email=email, name=org_name)- await _broadcast_credential_event(- "credential.oauth.connected", provider="claude_code",- )- logger.info(- "[claude_code_login] connected as %s (%s · %s)",- email or "unknown",- org_name or "unknown org",- info.get("subscriptionType") or "unknown plan",- )- except asyncio.CancelledError:- raise- except Exception as exc: # pragma: no cover — defensive- logger.exception("[claude_code_login] finalize failed: %s", exc)---async def handle_claude_code_login(- data: Dict[str, Any], # noqa: ARG001 — frontend sends {}- websocket: WebSocket, # noqa: ARG001 — registry signature-) -> Dict[str, Any]:- """Spawn ``claude auth login`` in the background; let the CLI open- the user's browser. Idempotent re-click syncs the marker without- re-running the flow."""- from nodes.agent.claude_code_agent._oauth import claude_auth_status_info-- info = await claude_auth_status_info()- if info.get("loggedIn"):- try:- await _mark_logged_in(- "claude_code",- email=info.get("email"),- name=info.get("orgName"),- )- await _broadcast_credential_event(- "credential.oauth.connected", provider="claude_code",- )- except Exception as exc:- logger.warning("[claude_code_login] mark/broadcast failed: %s", exc)- return {- "success": True,- "already_logged_in": True,- "email": info.get("email"),- "org_name": info.get("orgName"),- "subscription_type": info.get("subscriptionType"),- "message": "Already authenticated; refreshed status.",- }-- asyncio.create_task(_finalize_claude_login(), name="claude_code_login")- return {- "success": True,- "message": "Claude is opening your browser to authenticate.",- }---async def handle_claude_code_logout(- data: Dict[str, Any], # noqa: ARG001- websocket: WebSocket, # noqa: ARG001-) -> Dict[str, Any]:- """Run ``claude auth logout`` (CLI clears its own credentials), drop- the catalogue marker, broadcast ``.disconnected``."""- from nodes.agent.claude_code_agent._oauth import claude_auth_logout-- try:- await claude_auth_logout()- await _mark_logged_out("claude_code")- await _broadcast_credential_event(- "credential.oauth.disconnected", provider="claude_code",- )- except Exception as exc:- logger.warning("[claude_code_logout] failed: %s", exc)- return {"success": False, "error": str(exc)}- return {"success": True}+logger = get_logger(__name__)# ---------------------------------------------------------------------------@@ -212,8 +53,8 @@ async def handle_codex_cli_logout(websocket: WebSocket, # noqa: ARG001) -> Dict[str, Any]:try:- await _mark_logged_out("codex_cli")- await _broadcast_credential_event(+ await mark_logged_out("codex_cli")+ await broadcast_credential_event("credential.oauth.disconnected", provider="codex_cli",)except Exception as exc:@@ -223,15 +64,13 @@ async def handle_codex_cli_logout(# ----------------------------------------------------------------------------# Registry payload — `services/cli_agent/__init__.py` registers these-# into `services.ws_handler_registry` on package import.+# Registry payload — ``services/cli_agent/__init__.py`` registers these+# into ``services.ws_handler_registry`` on package import.# ---------------------------------------------------------------------------WSHandler = Callable[[Dict[str, Any], WebSocket], Awaitable[Dict[str, Any]]]WS_HANDLERS: Dict[str, WSHandler] = {- "claude_code_login": handle_claude_code_login,- "claude_code_logout": handle_claude_code_logout,"codex_cli_login": handle_codex_cli_login,"codex_cli_logout": handle_codex_cli_logout,}