Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)
Python
Added initial telegram support for cc-nim
Alishahryar156635433ba53
diff --git a/.env.example b/.env.exampleindex c96a4f6d..d3dc3964 100644--- a/.env.example+++ b/.env.example@@ -44,4 +44,12 @@ NVIDIA_NIM_REQUEST_ID=""# Thinking/Reasoning Parameters (passed via extra_body)NVIDIA_NIM_REASONING_EFFORT=high-NVIDIA_NIM_INCLUDE_REASONING=true\ No newline at end of file+NVIDIA_NIM_INCLUDE_REASONING=true++# ==================== Bot Wrapper Config ====================+TELEGRAM_API_ID="123456"+TELEGRAM_API_HASH="abcdef123456..."+ALLOWED_TELEGRAM_USER_ID="YOUR_TELEGRAM_USER_ID"+CLAUDE_WORKSPACE="./agent_workspace"+WRAPPER_WS_URL="ws://localhost:8083/ws"+ALLOWED_DIRS="C:\Users\alish\Desktop\projects"\ No newline at end of filediff --git a/.gitignore b/.gitignoreindex 6799302e..0058b85e 100644--- a/.gitignore+++ b/.gitignore@@ -40,4 +40,9 @@ ENV/*.swp*.swo.claude-.serena\ No newline at end of file+.serena++# Claude Code CLI+agent_workspace/+*.session+*-journal\ No newline at end of filediff --git a/README.md b/README.mdindex 9c423d2b..016eef01 100644--- a/README.md+++ b/README.md@@ -27,7 +27,7 @@ BIG_MODEL=moonshotai/kimi-k2-instructSMALL_MODEL=moonshotai/kimi-k2-instruct```-### 3. Run+### 3. Run (Terminal Mode)**Terminal 1 - Start the proxy:**@@ -43,6 +43,55 @@ ANTHROPIC_BASE_URL=http://localhost:8082 claudeThat's it! Claude Code now uses NVIDIA NIM for free.+---++## Telegram Bot Integration++Control Claude Code remotely via Telegram! Send tasks from your phone and watch Claude work.++### Setup++1. **Get Telegram API credentials** from [my.telegram.org](https://my.telegram.org):+ - Log in with your phone number+ - Go to "API Development Tools"+ - Create an app and copy your `api_id` and `api_hash`++2. **Add to `.env`:**++```dotenv+TELEGRAM_API_ID=12345678+TELEGRAM_API_HASH=your_api_hash_here+TELEGRAM_USER_ID=your_telegram_user_id+```++> 💡 To find your Telegram user ID, message [@userinfobot](https://t.me/userinfobot) on Telegram.++3. **Configure the workspace** (where Claude will operate):++```dotenv+CLAUDE_WORKSPACE=./agent_workspace+ALLOWED_DIRS=C:\Users\yourname\projects+```++4. **Start the server:**++```bash+uv run uvicorn server:app --host 0.0.0.0 --port 8082+```++5. **Authenticate Telegram** (first run only):+ - The server will prompt for your phone number and code+ - This creates a `claude_bot.session` file for future runs++### Usage++- **Send a message** to yourself on Telegram with a task+- Claude will respond with:+ - 💭 **Thinking tokens** (reasoning steps)+ - 🔧 **Tool calls** as they execute+ - ✅ **Final result** when complete+- Send `/stop` to cancel a running task+## Available ModelsSee [`nvidia_nim_models.json`](nvidia_nim_models.json) for the full list of supported models.diff --git a/bot/telegram_bot.py b/bot/telegram_bot.pynew file mode 100644index 00000000..b9d8694c--- /dev/null+++ b/bot/telegram_bot.py@@ -0,0 +1,208 @@+import os+import json+import asyncio+import logging+import websockets+from dotenv import load_dotenv+from telethon import TelegramClient, events++# Load .env from the root directory of the project+project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+load_dotenv(os.path.join(project_root, ".env"))++# Configuration+API_ID = os.getenv("TELEGRAM_API_ID")+API_HASH = os.getenv("TELEGRAM_API_HASH")+ALLOWED_USER_ID = os.getenv("ALLOWED_TELEGRAM_USER_ID")+WRAPPER_WS_URL = os.getenv("WRAPPER_WS_URL", "ws://localhost:8083/ws")++# Logging setup+logging.basicConfig(+ level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"+)+logger = logging.getLogger(__name__)++# Initialize Telethon Client+# Store the session file in the project root to avoid duplicates+session_path = os.path.join(project_root, "claude_bot.session")+print(f"DEBUG: Using session file at: {session_path}", flush=True)++client = TelegramClient(+ os.path.join(project_root, "claude_bot"), int(API_ID) if API_ID else 0, API_HASH+)+++# Global state to cache the owner info+my_info = None++[email protected](events.NewMessage())+async def handle_new_message(event):+ global my_info+ if not my_info:+ my_info = await client.get_me()++ # Handle /stop command+ if event.text == "/stop":+ import httpx++ try:+ # Derive HTTP URL from WS URL+ http_url = (+ WRAPPER_WS_URL.replace("ws://", "http://")+ .replace("wss://", "https://")+ .replace("/ws", "/stop")+ )+ async with httpx.AsyncClient() as hclient:+ r = await hclient.post(http_url)+ await event.reply(+ f"⏹ **Stop signal sent.**\nResult: `{r.json().get('status')}`"+ )+ except Exception as e:+ await event.reply(f"❌ Failed to send stop signal: {e}")+ return++ # DEBUG: Simple message detection+ print(+ f"DEBUG: Message detected in chat {event.chat_id}: '{event.text[:30]}...'",+ flush=True,+ )++ sender = await event.get_sender()+ if not sender:+ return++ user_id = str(sender.id)++ # Is it me or the authorized user?+ is_me = user_id == str(my_info.id)+ is_authorized = ALLOWED_USER_ID and user_id == str(ALLOWED_USER_ID)++ print(+ f"DEBUG: from_id={user_id} | is_me={is_me} | is_authorized={is_authorized}",+ flush=True,+ )++ # Security check+ if not is_me and not is_authorized:+ return++ # Skip empty, commands, or our own bot tokens+ if (+ not event.text+ or event.text.startswith("/")+ or any(event.text.startswith(p) for p in ["🤖", "🔧", "✅", "❌"])+ ):+ return++ print(f"DEBUG: ACCEPTED task from {user_id}: {event.text}", flush=True)+ logger.info(f"Accepted task from {user_id}: {event.text}")++ # Send initial status+ status_msg = await event.reply("🧠 **Claude is thinking...**")++ current_content = ""+ last_update_time = 0+ update_interval = 1.0 # Update every 1 second to avoid rate limits++ async def update_telegram_ui(text, status_prefix=""):+ nonlocal last_update_time+ import time++ now = time.time()+ if now - last_update_time < update_interval:+ return++ try:+ # Format: [Status] + Content+ display_text = f"{status_prefix}\n\n{text}" if status_prefix else text+ # Telegram limit check (simple)+ if len(display_text) > 4000:+ display_text = display_text[-4000:] # Show last 4k chars++ await status_msg.edit(display_text, parse_mode="markdown")+ last_update_time = now+ except Exception as ui_e:+ logger.debug(f"UI Update failed: {ui_e}")++ try:+ async with websockets.connect(WRAPPER_WS_URL) as ws:+ await ws.send(json.dumps({"task": event.text}))++ async for message in ws:+ data = json.loads(message)+ etype = data.get("type")++ if etype == "content":+ chunk = data.get("text", "")+ current_content += chunk+ await update_telegram_ui(+ current_content, "🧠 **Claude is writing...**"+ )++ elif etype == "tool_start":+ tools = data.get("tools", [])+ tool_names = [t.get("name") for t in tools]+ await update_telegram_ui(+ current_content, f"🔧 **Running:** `{', '.join(tool_names)}`"+ )++ elif etype == "complete":+ # Final update+ final_text = (+ current_content+ if current_content+ else "Task finished with no output."+ )+ await status_msg.edit(+ f"✅ **Task Complete**\n\n{final_text}", parse_mode="markdown"+ )+ break++ elif etype == "error":+ await event.reply(f"❌ **Claude Error:**\n{data.get('message')}")+ break++ except Exception as e:+ logger.error(f"Error: {e}")+ print(f"DEBUG: Exception during WebSocket communication: {e}", flush=True)+ await event.reply(+ f"💥 **Connection failed:** {e}\n_Is the wrapper running on port 8083?_"+ )+++async def main():+ print("Starting Telegram Client...", flush=True)+ await client.start()++ # Get and cache owner info+ global my_info+ my_info = await client.get_me()++ print(f"--- BOT STARTED ---", flush=True)+ print(+ f"Logged in as: {my_info.first_name} (@{my_info.username if my_info.username else 'No Username'})",+ flush=True,+ )+ print(f"Your User ID is: {my_info.id}", flush=True)++ # TEST: Send a message to Saved Messages to see if we're alive+ try:+ await client.send_message(+ "me",+ "🚀 **Claude Agent is now online!**\nSend me a task right here in Saved Messages to begin.",+ )+ print("DEBUG: Sent startup message to Saved Messages ('me').", flush=True)+ except Exception as e:+ print(f"DEBUG: Failed to send startup message: {e}", flush=True)++ print("Client is running. Listening for ALL messages...", flush=True)+ await client.run_until_disconnected()+++if __name__ == "__main__":+ if not API_ID or not API_HASH:+ print("Error: TELEGRAM_API_ID or TELEGRAM_API_HASH not set in .env")+ exit(1)++ asyncio.run(main())diff --git a/providers/claude_cli.py b/providers/claude_cli.pynew file mode 100644index 00000000..673d4bc7--- /dev/null+++ b/providers/claude_cli.py@@ -0,0 +1,191 @@+import asyncio+import os+import json+import logging+from typing import AsyncGenerator, Optional, Dict, List++logger = logging.getLogger(__name__)+++class CLIParser:+ """Helper to structure raw CLI events."""++ @staticmethod+ def parse_event(event: Dict) -> Optional[Dict]:+ if not isinstance(event, dict):+ return None++ etype = event.get("type")++ # 1. Handle full messages (assistant or result)+ msg_obj = None+ if etype == "assistant":+ msg_obj = event.get("message")+ elif etype == "result":+ # Safely get message from result which might be a list or dict+ res = event.get("result")+ if isinstance(res, dict):+ msg_obj = res.get("message")+ if not msg_obj:+ msg_obj = event.get("message")++ if msg_obj and isinstance(msg_obj, dict):+ content = msg_obj.get("content", [])+ if isinstance(content, list):+ parts = []+ thinking_parts = []+ tool_calls = []+ for c in content:+ if not isinstance(c, dict):+ continue+ ctype = c.get("type")+ if ctype == "text":+ parts.append(c.get("text", ""))+ elif ctype == "thinking":+ thinking_parts.append(c.get("thinking", ""))+ elif ctype == "tool_use":+ tool_calls.append(c)++ if tool_calls:+ # Check for subagents (Task tool)+ subagents = [+ t.get("input", {}).get("description", "Subagent")+ for t in tool_calls+ if t.get("name") == "Task"+ ]+ if subagents:+ return {"type": "subagent_start", "tasks": subagents}+ return {"type": "tool_start", "tools": tool_calls}++ if thinking_parts:+ return {"type": "thinking", "text": "\n".join(thinking_parts)}+ if parts:+ return {"type": "content", "text": "".join(parts)}++ # 2. Handle streaming deltas+ if etype == "content_block_delta":+ delta = event.get("delta", {})+ if not isinstance(delta, dict):+ return None+ if delta.get("type") == "text_delta":+ return {"type": "content", "text": delta.get("text", "")}+ if delta.get("type") == "thinking_delta":+ return {"type": "thinking", "text": delta.get("thinking", "")}++ # 3. Handle tool usage start+ if etype == "content_block_start":+ block = event.get("content_block", {})+ if isinstance(block, dict) and block.get("type") == "tool_use":+ if block.get("name") == "Task":+ desc = block.get("input", {}).get("description", "Subagent")+ return {"type": "subagent_start", "tasks": [desc]}+ return {"type": "tool_start", "tools": [block]}++ # 4. Handle errors and exit+ if etype == "error":+ err = event.get("error")+ msg = err.get("message") if isinstance(err, dict) else str(err)+ return {"type": "error", "message": msg}+ elif etype == "exit":+ return {+ "type": "complete",+ "status": "success" if event.get("code") == 0 else "failed",+ }+ return None+++class CLISession:+ """Manages a single persistent Claude Code CLI subprocess."""++ def __init__(+ self,+ workspace_path: str,+ api_url: str,+ allowed_dirs: Optional[List[str]] = None,+ ):+ self.workspace = os.path.normpath(os.path.abspath(workspace_path))+ self.api_url = api_url+ self.allowed_dirs = [os.path.normpath(d) for d in (allowed_dirs or [])]+ self.process: Optional[asyncio.subprocess.Process] = None++ async def start_task(self, prompt: str) -> AsyncGenerator[dict, None]:+ env = os.environ.copy()++ # Ensure we have a dummy key if none exists, as CLI often requires it+ if "ANTHROPIC_API_KEY" not in env:+ env["ANTHROPIC_API_KEY"] = "sk-placeholder-key-for-proxy"++ env["ANTHROPIC_API_URL"] = self.api_url+ if self.api_url.endswith("/v1"):+ env["ANTHROPIC_BASE_URL"] = self.api_url[:-3]+ else:+ env["ANTHROPIC_BASE_URL"] = self.api_url++ # Force non-interactive non-TTY+ env["TERM"] = "dumb"+ env["PYTHONIOENCODING"] = "utf-8"++ cmd = [+ "claude",+ "-p",+ prompt,+ "--output-format",+ "stream-json",+ "--dangerously-skip-permissions",+ "--verbose",+ ]++ if self.allowed_dirs:+ for d in self.allowed_dirs:+ cmd.extend(["--add-dir", d])++ logger.info(f"Launching Claude CLI in {self.workspace}")++ self.process = await asyncio.create_subprocess_exec(+ *cmd,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ cwd=self.workspace,+ env=env,+ )++ if not self.process or not self.process.stdout:+ logger.error("Claude CLI process failed to start or stdout not captured.")+ yield {"type": "exit", "code": 1}+ return++ while True:+ line = await self.process.stdout.readline()+ if not line:+ break++ line_str = line.decode("utf-8", errors="replace").strip()+ if not line_str:+ continue++ try:+ event = json.loads(line_str)+ yield event+ except json.JSONDecodeError:+ logger.debug(f"Non-JSON output: {line_str}")+ yield {"type": "raw", "content": line_str}++ if self.process.stderr:+ stderr_output = await self.process.stderr.read()+ if stderr_output:+ logger.error(+ f"Claude CLI Stderr: {stderr_output.decode('utf-8', errors='replace')}"+ )++ return_code = await self.process.wait()+ yield {"type": "exit", "code": return_code}++ async def stop(self):+ if self.process and self.process.returncode is None:+ try:+ self.process.terminate()+ await self.process.wait()+ return True+ except:+ return False+ return Falsediff --git a/pyproject.toml b/pyproject.tomlindex 5b89c329..546d0ef5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -11,6 +11,8 @@ dependencies = ["pydantic>=2.0.0","python-dotenv>=1.0.0","tiktoken>=0.7.0",+ "websockets>=13.0",+ "telethon>=1.35.0",][dependency-groups]diff --git a/server.py b/server.pyindex d8fa147b..33b83b03 100644--- a/server.py+++ b/server.py@@ -10,10 +10,11 @@ enabling Claude Code CLI to utilize NIM models with full support for:- Fast prefix detection for CLI policy specifications"""+import time+import asyncioimport osimport jsonimport logging-import uuidfrom typing import List, Dict, Any, Optional, Union, Literalfrom pydantic import BaseModel, field_validator, model_validatorfrom providers.nvidia_nim import NvidiaNimProvider, ProviderConfig@@ -24,6 +25,14 @@ from contextlib import asynccontextmanagerfrom fastapi import FastAPI, Request, HTTPException, Dependsfrom fastapi.responses import StreamingResponse, JSONResponseimport tiktoken+from providers.claude_cli import CLISession, CLIParser++# Optional: telethon for the bot+try:+ from telethon import TelegramClient, events+except ImportError:+ TelegramClient = None+ events = None# Initialize tokenizerENCODER = tiktoken.get_encoding("cl100k_base")@@ -35,7 +44,7 @@ load_dotenv()logging.basicConfig(level=logging.DEBUG,format="%(asctime)s - %(levelname)s - %(message)s",- handlers=[logging.FileHandler("server.log", encoding="utf-8", mode="a")],+ handlers=[logging.FileHandler("server.log", encoding="utf-8", mode="w")],)logger = logging.getLogger(__name__)@@ -228,17 +237,175 @@ def get_provider() -> NvidiaNimProvider:# FastAPI App# =============================================================================+tele_client: Optional["TelegramClient"] = None+@asynccontextmanagerasync def lifespan(app: FastAPI):- logger.info("Server starting up...")+ global tele_client+ try:+ api_id = os.getenv("TELEGRAM_API_ID")+ api_hash = os.getenv("TELEGRAM_API_HASH")+ if TelegramClient and api_id and api_hash:+ logger.info("Starting Telegram Bot...")+ session_path = os.path.join(WORKSPACE_PATH, "claude_bot.session")+ tele_client = TelegramClient(session_path, int(api_id), api_hash)++ # Register handlers BEFORE starting+ register_bot_handlers(tele_client)++ await tele_client.start()+ asyncio.create_task(tele_client.run_until_disconnected())++ # Notify user+ try:+ await tele_client.send_message(+ "me", f"🚀 **Claude unified server is online!** (v{app.version})"+ )+ except:+ pass+ logger.info("Bot started and online message sent.")+ except Exception as e:+ logger.error(f"Bot failed to start: {e}")+ tele_client = None+yield+ if tele_client:+ await tele_client.disconnect()logger.info("Server shutting down...")global _providerif _provider and hasattr(_provider, "_client"):await _provider._client.aclose()+# =============================================================================+# Telegram Bot & CLI Configuration+# =============================================================================++WORKSPACE_PATH = os.path.abspath(os.getenv("CLAUDE_WORKSPACE", "agent_workspace"))+ALLOWED_DIRS = []+raw_dirs = os.getenv("ALLOWED_DIRS", "")+if raw_dirs:+ # Handle Windows backslash corrosion (\a, \b etc) by replacing them+ for d in raw_dirs.split(","):+ d = d.strip()+ if not d:+ continue+ # If it looks like a Windows path with corrupted escapes, try to fix+ fixed = (+ d.replace("\a", "\\a")+ .replace("\b", "\\b")+ .replace("\f", "\\f")+ .replace("\n", "\\n")+ .replace("\r", "\\r")+ .replace("\t", "\\t")+ .replace("\v", "\\v")+ )+ ALLOWED_DIRS.append(os.path.normpath(fixed))+# Internal URL for the CLI to use (points to this server)+INTERNAL_API_URL = "http://localhost:8082/v1"++# Initialize Global Instances+cli_session = CLISession(WORKSPACE_PATH, INTERNAL_API_URL, ALLOWED_DIRS)+++def register_bot_handlers(client: "TelegramClient"):+ ALLOWED_USER_ID = os.getenv("ALLOWED_TELEGRAM_USER_ID")+ logger.info(f"DEBUG: Registering bot handlers. Allowed user ID: {ALLOWED_USER_ID}")++ @client.on(events.NewMessage())+ async def handle_telegram_message(event):+ sender_id = str(event.sender_id)+ logger.info(f"BOT_EVENT: From {sender_id} | Text: {event.text[:50]}")++ target_id = str(ALLOWED_USER_ID).strip()+ if sender_id != target_id:+ logger.debug(f"BOT_SECURITY: Ignored message from {sender_id}")+ return++ # 1. Handle Commands+ if event.text == "/stop":+ await cli_session.stop()+ await event.reply("⏹ **Claude process stopped.**")+ return++ # 2. Filter out bot's own status messages and empty text+ if not event.text or any(event.text.startswith(p) for p in ["⏳", "�", "🔧", "✅", "❌", "🚀", "🤖"]):+ return++ logger.info(f"BOT_TASK: {event.text}")+ status_msg = await event.reply("⏳ **Launching Claude CLI...**")++ current_content = ""+ last_ui_update = 0++ async def update_bot_ui(text, status=None):+ nonlocal last_ui_update+ if not text and not status:+ return+ now = time.time()+ if now - last_ui_update < 0.8: # Slightly faster+ return+ try:+ display = f"{status}\n\n{text}" if status else text+ if len(display) > 4000:+ display = "..." + display[-3997:]+ await status_msg.edit(display, parse_mode="markdown")+ last_ui_update = now+ except:+ pass++ try:+ async for event_data in cli_session.start_task(event.text):+ if not isinstance(event_data, dict):+ continue++ parsed = CLIParser.parse_event(event_data)++ if event_data.get("type") == "raw":+ raw_line = event_data.get("content")+ if not raw_line: continue+ if "login" in raw_line.lower():+ await event.reply("⚠️ **Claude requires login. Run `claude` in terminal.**")+ continue++ if not parsed:+ continue++ if parsed["type"] == "thinking":+ # Display thinking tokens with special prefix+ thinking_text = parsed["text"]+ await event.reply(f"💭 **Thinking:**\n```\n{thinking_text[:1500]}{'...' if len(thinking_text) > 1500 else ''}\n```", parse_mode="markdown")++ elif parsed["type"] == "content":+ current_content += parsed["text"]+ await update_bot_ui(current_content, "🧠 **Claude is working...**")++ elif parsed["type"] == "tool_start":+ names = [t.get("name") for t in parsed["tools"]]+ # Send a SEPARATE message for tool calls as requested+ await event.reply(f"🔧 **Running Tools:** `{', '.join(names)}`")+ # Update status message to show we're working+ await update_bot_ui(current_content, "⏳ **Executing tools...**")++ elif parsed["type"] == "subagent_start":+ tasks = parsed["tasks"]+ await event.reply(f"🤖 **Subagent Task:** {', '.join(tasks)}")+ await update_bot_ui(current_content, "🔎 **Subagent working...**")++ elif parsed["type"] == "complete":+ if parsed.get("status") == "failed":+ await status_msg.edit(f"❌ **Failed**\n\n{current_content}", parse_mode="markdown")+ else:+ await status_msg.edit(f"✅ **Complete**\n\n{current_content or 'Done.'}", parse_mode="markdown")++ elif parsed["type"] == "error":+ await event.reply(f"❌ **Error:** {parsed['message']}")+ except Exception as e:+ logger.error(f"Bot failed: {e}")+ await event.reply(f"💥 **Failed:** {e}")++FAST_PREFIX_DETECTION = os.getenv("FAST_PREFIX_DETECTION", "true").lower() == "true"@@ -521,7 +688,13 @@ async def root():@app.get("/health")async def health():- return {"status": "healthy"}+ return {"status": "healthy", "bot_running": tele_client is not None}++[email protected]("/stop")+async def stop_cli():+ stopped = await cli_session.stop()+ return {"status": "terminated" if stopped else "no_active_process"}if __name__ == "__main__":diff --git a/uv.lock b/uv.lockindex 78223450..68586b01 100644--- a/uv.lock+++ b/uv.lock@@ -50,8 +50,10 @@ dependencies = [{ name = "httpx" },{ name = "pydantic" },{ name = "python-dotenv" },+ { name = "telethon" },{ name = "tiktoken" },{ name = "uvicorn" },+ { name = "websockets" },][package.dev-dependencies]@@ -67,8 +69,10 @@ requires-dist = [{ name = "httpx", specifier = ">=0.25.0" },{ name = "pydantic", specifier = ">=2.0.0" },{ name = "python-dotenv", specifier = ">=1.0.0" },+ { name = "telethon", specifier = ">=1.35.0" },{ name = "tiktoken", specifier = ">=0.7.0" },{ name = "uvicorn", specifier = ">=0.34.0" },+ { name = "websockets", specifier = ">=13.0" },][package.metadata.requires-dev]@@ -379,24 +383,62 @@ standard = [name = "h11"version = "0.14.0"source = { registry = "https://pypi.org/simple" }+resolution-markers = [+ "python_full_version == '3.13.*'",+ "python_full_version >= '3.11' and python_full_version < '3.13'",+ "python_full_version < '3.11'",+]sdist = { url = "https://files.pythonhosted.org/packages/f5/38/3af3d3633a34a3316095b39c8e8fb4853a28a536e55d347bd8d8e9a14b03/h11-0.14.0.tar.gz", hash = "sha256:8f19fbbe99e72420ff35c00b27a34cb9937e902a8b810e2c88300c6f0a3b699d", size = 100418, upload-time = "2022-09-25T15:40:01.519Z" }wheels = [{ url = "https://files.pythonhosted.org/packages/95/04/ff642e65ad6b90db43e668d70ffb6736436c7ce41fcc549f4e9472234127/h11-0.14.0-py3-none-any.whl", hash = "sha256:e3fe4ac4b851c468cc8363d500db52c2ead036020723024a109d37346efaa761", size = 58259, upload-time = "2022-09-25T15:39:59.68Z" },]+[[package]]+name = "h11"+version = "0.16.0"+source = { registry = "https://pypi.org/simple" }+resolution-markers = [+ "python_full_version >= '3.14'",+]+sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" },+]+[[package]]name = "httpcore"version = "1.0.7"source = { registry = "https://pypi.org/simple" }+resolution-markers = [+ "python_full_version == '3.13.*'",+ "python_full_version >= '3.11' and python_full_version < '3.13'",+ "python_full_version < '3.11'",+]dependencies = [- { name = "certifi" },- { name = "h11" },+ { name = "certifi", marker = "python_full_version < '3.14'" },+ { name = "h11", version = "0.14.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14'" },]sdist = { url = "https://files.pythonhosted.org/packages/6a/41/d7d0a89eb493922c37d343b607bc1b5da7f5be7e383740b4753ad8943e90/httpcore-1.0.7.tar.gz", hash = "sha256:8551cb62a169ec7162ac7be8d4817d561f60e08eaa485234898414bb5a8a0b4c", size = 85196, upload-time = "2024-11-15T12:30:47.531Z" }wheels = [{ url = "https://files.pythonhosted.org/packages/87/f5/72347bc88306acb359581ac4d52f23c0ef445b57157adedb9aee0cd689d2/httpcore-1.0.7-py3-none-any.whl", hash = "sha256:a3fff8f43dc260d5bd363d9f9cf1830fa3a458b332856f34282de498ed420edd", size = 78551, upload-time = "2024-11-15T12:30:45.782Z" },]+[[package]]+name = "httpcore"+version = "1.0.9"+source = { registry = "https://pypi.org/simple" }+resolution-markers = [+ "python_full_version >= '3.14'",+]+dependencies = [+ { name = "certifi", marker = "python_full_version >= '3.14'" },+ { name = "h11", version = "0.16.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" },+]+[[package]]name = "httptools"version = "0.6.4"@@ -440,7 +482,8 @@ source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "anyio" },{ name = "certifi" },- { name = "httpcore" },+ { name = "httpcore", version = "1.0.7", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14'" },+ { name = "httpcore", version = "1.0.9", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" },{ name = "idna" },]sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" }@@ -575,6 +618,21 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" },]+[[package]]+name = "pyaes"+version = "1.6.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/44/66/2c17bae31c906613795711fc78045c285048168919ace2220daa372c7d72/pyaes-1.6.1.tar.gz", hash = "sha256:02c1b1405c38d3c370b085fb952dd8bea3fadcee6411ad99f312cc129c536d8f", size = 28536, upload-time = "2017-09-20T21:17:54.23Z" }++[[package]]+name = "pyasn1"+version = "0.6.2"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/fe/b6/6e630dff89739fcd427e3f72b3d905ce0acb85a45d4ec3e2678718a3487f/pyasn1-0.6.2.tar.gz", hash = "sha256:9b59a2b25ba7e4f8197db7686c09fb33e658b98339fadb826e9512629017833b", size = 146586, upload-time = "2026-01-16T18:04:18.534Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/44/b5/a96872e5184f354da9c84ae119971a0a4c221fe9b27a4d94bd43f2596727/pyasn1-0.6.2-py3-none-any.whl", hash = "sha256:1eb26d860996a18e9b6ed05e7aae0e9fc21619fcee6af91cca9bad4fbea224bf", size = 83371, upload-time = "2026-01-16T18:04:17.174Z" },+]+[[package]]name = "pydantic"version = "2.10.6"@@ -945,6 +1003,18 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/7e/1b/1c2f43af46456050b27810a7a013af8a7e12bc545a0cdc00eb0df55eb769/rich_toolkit-0.13.2-py3-none-any.whl", hash = "sha256:f3f6c583e5283298a2f7dbd3c65aca18b7f818ad96174113ab5bec0b0e35ed61", size = 13566, upload-time = "2025-01-13T19:29:59.795Z" },]+[[package]]+name = "rsa"+version = "4.9.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "pyasn1" },+]+sdist = { url = "https://files.pythonhosted.org/packages/da/8a/22b7beea3ee0d44b1916c0c1cb0ee3af23b700b6da9f04991899d0c555d4/rsa-4.9.1.tar.gz", hash = "sha256:e7bdbfdb5497da4c07dfd35530e1a902659db6ff241e39d9953cad06ebd0ae75", size = 29034, upload-time = "2025-04-16T09:51:18.218Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/64/8d/0133e4eb4beed9e425d9a98ed6e081a55d195481b7632472be1af08d2f6b/rsa-4.9.1-py3-none-any.whl", hash = "sha256:68635866661c6836b8d39430f97a996acbd61bfa49406748ea243539fe239762", size = 34696, upload-time = "2025-04-16T09:51:17.142Z" },+]+[[package]]name = "shellingham"version = "1.5.4"@@ -975,6 +1045,19 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/a0/4b/528ccf7a982216885a1ff4908e886b8fb5f19862d1962f56a3fce2435a70/starlette-0.46.1-py3-none-any.whl", hash = "sha256:77c74ed9d2720138b25875133f3a2dae6d854af2ec37dceb56aef370c1d8a227", size = 71995, upload-time = "2025-03-08T10:55:32.662Z" },]+[[package]]+name = "telethon"+version = "1.42.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "pyaes" },+ { name = "rsa" },+]+sdist = { url = "https://files.pythonhosted.org/packages/8c/10/8c8c9476bfce767a856d8aaf9eae8ea1869df4e970da16f1c5b638fd1b0c/telethon-1.42.0.tar.gz", hash = "sha256:032e95511261d5ead719f75494c6c85ece2ce71816b54f3c65d6ccc371d6994d", size = 672734, upload-time = "2025-11-05T19:15:19.849Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/e4/e4/8ce0ff55251381966a7c3f88bd5b34abda79b225a8e7fb51ddef3b849c94/telethon-1.42.0-py3-none-any.whl", hash = "sha256:cf361c94586bcacd6d0fc8959a2bce509d1bb37007fe6476a80c4fb4a2decc29", size = 748466, upload-time = "2025-11-05T19:15:18.241Z" },+]+[[package]]name = "tiktoken"version = "0.12.0"@@ -1129,7 +1212,8 @@ version = "0.34.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "click" },- { name = "h11" },+ { name = "h11", version = "0.14.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.14'" },+ { name = "h11", version = "0.16.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.14'" },{ name = "typing-extensions", marker = "python_full_version < '3.11'" },]sdist = { url = "https://files.pythonhosted.org/packages/4b/4d/938bd85e5bf2edeec766267a5015ad969730bb91e31b44021dfe8b22df6c/uvicorn-0.34.0.tar.gz", hash = "sha256:404051050cd7e905de2c9a7e61790943440b3416f49cb409f965d9dcd0fa73e9", size = 76568, upload-time = "2024-12-15T13:33:30.42Z" }diff --git a/wrapper/api.py b/wrapper/api.pynew file mode 100644index 00000000..beb5519a--- /dev/null+++ b/wrapper/api.py@@ -0,0 +1,82 @@+from fastapi import FastAPI, WebSocket, WebSocketDisconnect+from wrapper.cli_session import CLISession+from wrapper.parser import CLIParser+import os+import uvicorn+import logging+from dotenv import load_dotenv++# Load .env from the root directory+load_dotenv()++# Configure logging+logging.basicConfig(level=logging.INFO)+logger = logging.getLogger(__name__)++app = FastAPI()++# Configuration from environment+workspace_env = os.getenv("CLAUDE_WORKSPACE", "agent_workspace")+WORKSPACE = os.path.normpath(os.path.abspath(workspace_env))+print(f"--- WRAPPER CONFIG ---", flush=True)+print(f"WORKSPACE: {WORKSPACE}", flush=True)++# The proxy server is running on port 8082 based on user context+API_URL = os.getenv("ANTHROPIC_API_URL", "http://localhost:8082/v1")+ALLOWED_DIRS = os.getenv("ALLOWED_DIRS", "").split(",")+ALLOWED_DIRS = [os.path.normpath(d.strip()) for d in ALLOWED_DIRS if d.strip()]+print(f"ALLOWED_DIRS: {ALLOWED_DIRS}", flush=True)++session = CLISession(WORKSPACE, API_URL, ALLOWED_DIRS)++[email protected]("/stop")+async def stop_session():+ """Forcefully terminates the current Claude CLI process."""+ if session.process and session.process.returncode is None:+ logger.info("Forcefully terminating Claude process...")+ try:+ session.process.terminate()+ return {"status": "terminated"}+ except Exception as e:+ return {"status": "error", "message": str(e)}+ return {"status": "no_active_process"}++[email protected]("/ws")+async def websocket_endpoint(websocket: WebSocket):+ await websocket.accept()+ logger.info("Bot connected to WebSocket")++ try:+ while True:+ # Receive task from bot+ data = await websocket.receive_json()+ task = data.get("task")++ if not task:+ continue++ logger.info(f"Received task: {task}")++ # Start Claude session and stream events back+ async for event in session.start_task(task):+ parsed = CLIParser.parse_event(event)+ if parsed:+ await websocket.send_json(parsed)+ else:+ # Send raw for debugging if it's unknown but relevant+ if event.get("type") in ["system", "result"]:+ await websocket.send_json(+ {"type": "status", "data": event.get("subtype") or "update"}+ )++ except WebSocketDisconnect:+ logger.info("Bot disconnected")+ except Exception as e:+ logger.error(f"Error in WebSocket: {e}")+ await websocket.close()+++if __name__ == "__main__":+ uvicorn.run(app, host="0.0.0.0", port=8083)diff --git a/wrapper/cli_session.py b/wrapper/cli_session.pynew file mode 100644index 00000000..19ae314e--- /dev/null+++ b/wrapper/cli_session.py@@ -0,0 +1,97 @@+import asyncio+import os+import json+import logging+from typing import AsyncGenerator, Optional++logger = logging.getLogger(__name__)+++class CLISession:+ """Manages a single persistent Claude Code CLI subprocess."""++ def __init__(+ self,+ workspace_path: str,+ api_url: str,+ allowed_dirs: Optional[list[str]] = None,+ ):+ self.workspace = workspace_path+ self.api_url = api_url+ self.allowed_dirs = allowed_dirs or []+ self.process: Optional[asyncio.subprocess.Process] = None++ async def start_task(self, prompt: str) -> AsyncGenerator[dict, None]:+ """Runs a single prompt and yields JSON events from the CLI."""+ env = os.environ.copy()++ # FIX for 404:+ # ANTHROPIC_API_URL usually wants the full path to the API endpoint or version root+ env["ANTHROPIC_API_URL"] = self.api_url++ # ANTHROPIC_BASE_URL usually wants the server root, and the client appends /v1/messages+ # If self.api_url is "http://localhost:8082/v1", base should be "http://localhost:8082"+ if self.api_url.endswith("/v1"):+ env["ANTHROPIC_BASE_URL"] = self.api_url[:-3]+ else:+ env["ANTHROPIC_BASE_URL"] = self.api_url++ # Ensure we don't try to use interactive TTY features+ env["TERM"] = "dumb"+ # Ensure path is normalized for Windows to avoid \a (bell) character issues+ normalized_workspace = os.path.normpath(self.workspace)++ cmd = [+ "claude",+ "-p",+ prompt,+ "--output-format",+ "stream-json",+ "--dangerously-skip-permissions",+ "--verbose",+ ]++ if self.allowed_dirs:+ for d in self.allowed_dirs:+ cmd.extend(["--add-dir", os.path.normpath(d)])++ logger.info(+ f"Launching Claude CLI in {normalized_workspace} with API {self.api_url}"+ )++ self.process = await asyncio.create_subprocess_exec(+ *cmd,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ cwd=normalized_workspace,+ env=env,+ )++ # Read stdout line by line+ while True:+ line = await self.process.stdout.readline()+ if not line:+ break++ line_str = line.decode("utf-8").strip()+ if not line_str:+ continue++ try:+ event = json.loads(line_str)+ yield event+ except json.JSONDecodeError:+ # Log non-JSON lines for debugging but don't crash+ logger.debug(f"Non-JSON output: {line_str}")+ yield {"type": "raw", "content": line_str}++ # Capture remaining stderr if the process crashed+ stderr_output = await self.process.stderr.read()+ if stderr_output:+ logger.error(+ f"Claude CLI Stderr: {stderr_output.decode('utf-8', errors='replace')}"+ )++ return_code = await self.process.wait()+ logger.info(f"Claude CLI exited with code {return_code}")+ yield {"type": "exit", "code": return_code}diff --git a/wrapper/parser.py b/wrapper/parser.pynew file mode 100644index 00000000..2eda44d4--- /dev/null+++ b/wrapper/parser.py@@ -0,0 +1,40 @@+import json+from typing import Dict, Optional+++class CLIParser:+ """Helper to structure raw CLI events for the bot."""++ @staticmethod+ def parse_event(event: Dict) -> Optional[Dict]:+ """Filters and formats events for the bot client."""+ etype = event.get("type")++ # We are mainly interested in content updates, tool calls, and status+ if etype == "assistant":+ message = event.get("message", {})+ content = message.get("content", [])++ # Simple text content+ text_parts = [c["text"] for c in content if c.get("type") == "text"]+ if text_parts:+ return {"type": "content", "text": "".join(text_parts)}++ # Tool calls+ tool_calls = [c for c in content if c.get("type") == "tool_use"]+ if tool_calls:+ return {"type": "tool_start", "tools": tool_calls}++ elif etype == "tool_output":+ return {"type": "tool_result", "output": event.get("output")}++ elif etype == "error":+ return {"type": "error", "message": event.get("error")}++ elif etype == "exit":+ return {+ "type": "complete",+ "status": "success" if event.get("code") == 0 else "failed",+ }++ return None