Skip to content

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

removed legacy code

Alishahryar1245faff9fdce
diff --git a/bot/telegram_bot.py b/bot/telegram_bot.py
deleted file mode 100644
index b9d8694c..00000000
--- a/bot/telegram_bot.py
+++ /dev/null
@@ -1,208 +0,0 @@
-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/config/settings.py b/config/settings.py
index 5786dcbf..2ac87fa1 100644
--- a/config/settings.py
+++ b/config/settings.py
@@ -67,7 +67,6 @@ class Settings(BaseSettings):
claude_workspace: str = "./agent_workspace"
allowed_dir: str = ""
max_cli_sessions: int = 10
- wrapper_ws_url: str = "ws://localhost:8083/ws"
# ==================== Server ====================
host: str = "0.0.0.0"
diff --git a/wrapper/api.py b/wrapper/api.py
deleted file mode 100644
index 8283e686..00000000
--- a/wrapper/api.py
+++ /dev/null
@@ -1,83 +0,0 @@
-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)
-
-
-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"}
-
-
-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_list = CLIParser.parse_event(event)
- if parsed_list:
- for parsed in parsed_list:
- 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.py
deleted file mode 100644
index 3b66d3b2..00000000
--- a/wrapper/cli_session.py
+++ /dev/null
@@ -1,115 +0,0 @@
-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)])
-
- prompt_preview = prompt[:100].replace("\n", " ") + (
- "..." if len(prompt) > 100 else ""
- )
- logger.info(
- f'CLI_TASK: workspace={normalized_workspace} prompt_len={len(prompt)} preview="{prompt_preview}"'
- )
-
- self.process = await asyncio.create_subprocess_exec(
- *cmd,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- cwd=normalized_workspace,
- env=env,
- )
-
- # Read stdout in chunks to handle long lines
- buffer = bytearray()
- while True:
- chunk = await self.process.stdout.read(65536)
- if not chunk:
- if buffer:
- line_str = buffer.decode("utf-8", errors="replace").strip()
- if line_str:
- async for event in self._handle_line_gen(line_str):
- yield event
- break
-
- buffer.extend(chunk)
- while True:
- newline_pos = buffer.find(b"\n")
- if newline_pos == -1:
- break
- line = buffer[:newline_pos]
- buffer = buffer[newline_pos + 1 :]
- line_str = line.decode("utf-8", errors="replace").strip()
- if line_str:
- async for event in self._handle_line_gen(line_str):
- yield event
-
- async def _handle_line_gen(self, line_str: str) -> AsyncGenerator[dict, None]:
- 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.py
deleted file mode 100644
index 2eda44d4..00000000
--- a/wrapper/parser.py
+++ /dev/null
@@ -1,40 +0,0 @@
-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