import json import os import re import shlex import subprocess import sys import threading import time import shutil import hashlib import base64 from pathlib import Path from datetime import datetime from getpass import getpass import requests from rich.console import Console from rich.markdown import Markdown from rich.panel import Panel from rich.table import Table from rich.text import Text from rich.live import Live from rich.rule import Rule from rich.align import Align from prompt_toolkit import prompt from prompt_toolkit.history import InMemoryHistory, FileHistory from prompt_toolkit.completion import Completer, Completion from prompt_toolkit.styles import Style as PtStyle # --- Config --- # Fix PATH for Termux and pip --user installs _extra_paths = [ os.path.expanduser("~/.local/bin"), os.path.expanduser("~/bin"), ] if os.path.exists("/data/data/com.termux"): _extra_paths.extend([ "/data/data/com.termux/files/usr/bin", "/data/data/com.termux/files/home/.local/bin", os.path.expanduser("~/.npm-global/bin"), ]) for _p in _extra_paths: if _p not in os.environ.get("PATH", "") and os.path.isdir(_p): os.environ["PATH"] = _p + os.pathsep + os.environ.get("PATH", "") OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://localhost:11434/api/chat") MODEL = "llama3.2" CHATS_DIR = Path.home() / ".codegpt" / "conversations" # --- Colorful palette ----------------------------------------------------- # Vivid neon hex palette for the CLI. Rich supports truecolor (24-bit) and # degrades gracefully to 256-color / 16-color on older terminals, so these # hex values work everywhere without breaking anything. CYBER = { "red": "#ff2b5e", # hot pink-red "orange": "#ff8c42", # neon orange "yellow": "#ffd93d", # bright yellow "lime": "#b3ff66", # electric lime "green": "#00ff9f", # mint neon "teal": "#00e5cc", # teal glow "cyan": "#00d9ff", # cyan pop "blue": "#4d8aff", # electric blue "indigo": "#6b5bff", # deep indigo "purple": "#b967ff", # neon purple "pink": "#ff77e9", # hot pink "magenta": "#ff4ad6", # vivid magenta "white": "#f5f5f5", # soft white "dim": "#6a6f77", # muted gray } # Ordered rainbow for gradient sweeps and per-char cycling. RAINBOW = [ "red", "orange", "yellow", "lime", "green", "teal", "cyan", "blue", "indigo", "purple", "pink", "magenta", ] def rainbow(text, bold=True, offset=0): """Render a string with each character painted a different rainbow hue. Uses Rich markup — each character gets its own color tag. `offset` lets callers shift the starting color so consecutive lines can animate/stagger. """ out = [] prefix = "bold " if bold else "" for i, ch in enumerate(text): if ch == " ": out.append(ch) continue hue = CYBER[RAINBOW[(i + offset) % len(RAINBOW)]] out.append(f"[{prefix}{hue}]{ch}[/]") return "".join(out) def gradient_rule(width=None, offset=0): """Return a Rich-markup string: a horizontal rule swept through the rainbow.""" from shutil import get_terminal_size w = width or get_terminal_size((80, 20)).columns out = [] for i in range(w): hue = CYBER[RAINBOW[(i + offset) % len(RAINBOW)]] out.append(f"[{hue}]─[/]") return "".join(out) # --- End colorful palette ------------------------------------------------- # --- Per-tool venv isolation ---------------------------------------------- # Some pip-based tools (aider, open-interpreter, mentat, gpt-engineer) pull # in heavy native deps like tiktoken. On Python 3.13 these can fail to build # in the global site-packages, AND when they DO succeed they pin clobber # CodeGPT's own dependency versions. Solution: each "isolated" tool gets its # own venv under ~/.codegpt/tool-venvs//, completely cut off from the # host Python. The launch path then runs the venv's bin instead of PATH lookup. TOOL_VENVS_DIR = Path.home() / ".codegpt" / "tool-venvs" # Single lock for all tool venv operations. Tool installs are minutes-long # and naturally serialized in single-user CLI flow, but features like /split # or /grid can spawn concurrent install paths from different threads. One # global lock eliminates the race entirely; per-tool granularity isn't worth # the bookkeeping when each install is already O(seconds) at best. _tool_venv_lock = threading.Lock() def tool_venv_dir(key): return TOOL_VENVS_DIR / key def tool_venv_python(key): """Path to the python executable inside a tool's venv.""" venv = tool_venv_dir(key) if os.name == "nt": return venv / "Scripts" / "python.exe" return venv / "bin" / "python" def tool_venv_bin(key, name): """Path to a binary (e.g. 'aider') inside a tool's venv. Returns None if missing.""" venv = tool_venv_dir(key) if os.name == "nt": candidates = [ venv / "Scripts" / f"{name}.exe", venv / "Scripts" / f"{name}.cmd", venv / "Scripts" / name, ] else: candidates = [venv / "bin" / name] for c in candidates: if c.exists(): return c return None def _ensure_uv(): """Ensure uv is importable as a Python module. Installs to user site if missing. Returns (ok: bool, error: str). The error string is empty on success and contains decoded stderr from the bootstrap pip install on failure so the caller can surface a real diagnosis instead of a generic message. """ try: subprocess.run( [sys.executable, "-c", "import uv"], check=True, capture_output=True, ) return True, "" except Exception: pass try: subprocess.run( [sys.executable, "-m", "pip", "install", "--user", "uv"], check=True, capture_output=True, timeout=180, ) return True, "" except subprocess.TimeoutExpired: return False, "uv bootstrap timed out (3min) — check network." except subprocess.CalledProcessError as ex: stderr = "" if ex.stderr: try: stderr = ex.stderr.decode("utf-8", errors="replace") if isinstance(ex.stderr, bytes) else str(ex.stderr) except Exception: stderr = "" return False, f"pip install --user uv failed (exit {ex.returncode}): {stderr.strip()[:300]}" except Exception as ex: return False, f"uv bootstrap error: {str(ex)[:300]}" def ensure_tool_venv(key, python_version=None): """Create a venv for a tool if missing. Returns (venv_path, created_now: bool). If python_version is specified (e.g. '3.12'), uses uv to fetch that interpreter and create the venv with it — required for tools like aider that don't yet support the host's Python version. Otherwise uses the host Python via the stdlib `venv` module. """ venv = tool_venv_dir(key) if venv.exists() and tool_venv_python(key).exists(): return venv, False TOOL_VENVS_DIR.mkdir(parents=True, exist_ok=True) if python_version: ok, uv_err = _ensure_uv() if not ok: raise RuntimeError( f"Tool {key} requires Python {python_version} via uv, " f"but uv could not be installed: {uv_err}" ) # uv handles both fetching the interpreter and creating the venv. subprocess.run( [sys.executable, "-m", "uv", "python", "install", python_version], check=True, capture_output=True, timeout=300, ) subprocess.run( [sys.executable, "-m", "uv", "venv", "--python", python_version, str(venv)], check=True, capture_output=True, timeout=120, ) else: subprocess.run( [sys.executable, "-m", "venv", str(venv)], check=True, capture_output=True, ) return venv, True def is_isolated_tool(tool): """A tool should be installed in its own venv if it sets isolated=True.""" return bool(tool.get("isolated")) def install_in_tool_venv(key, install_cmd, python_version=None): """Install a pip-based tool inside its own venv at ~/.codegpt/tool-venvs//. install_cmd is the original list starting with 'pip' or 'pip3'. If python_version is specified, the venv uses uv to provision that Python interpreter instead of the host's. Returns (ok: bool, error: str). Full pip output is written to ~/.codegpt/tool-venvs//install.log so users can read the real error when something fails (the returned error string is intentionally short for UI display). """ # Strip leading 'pip' / 'pip3' and the literal 'install' keyword to # extract the package args (which may include flags or VCS URLs). pkg_args = [a for a in install_cmd[1:] if a != "install"] log_path = tool_venv_dir(key) / "install.log" def _write_log(text): try: tool_venv_dir(key).mkdir(parents=True, exist_ok=True) log_path.write_text(text, encoding="utf-8", errors="replace") except Exception: pass # Pre-create the tool venv dir so the install.log path referenced by # error handlers is always writable, even if ensure_tool_venv() fails # before any other write touches the directory. try: tool_venv_dir(key).mkdir(parents=True, exist_ok=True) except Exception: pass # Serialize all venv operations to prevent races between concurrent # tool installs (e.g. /split aider mentat). Each install is O(seconds- # to-minutes) so the lock is effectively free at the granularity that # matters. if not _tool_venv_lock.acquire(timeout=900): return False, "Another tool install is in progress (15min lock timeout)." try: ensure_tool_venv(key, python_version=python_version) py = tool_venv_python(key) if python_version: # uv path: use `uv pip install --python ` for fast, # Py3.13-aware dep resolution. uv handles wheels for Python # versions plain pip can't. r = subprocess.run( [ sys.executable, "-m", "uv", "pip", "install", "--python", str(py), *pkg_args, ], capture_output=True, text=True, timeout=900, ) else: # Stdlib pip path: upgrade pip + setuptools + wheel first # (Python 3.12+ venvs ship without setuptools, breaking sdist # builds for many packages). subprocess.run( [str(py), "-m", "pip", "install", "--upgrade", "pip", "setuptools", "wheel"], capture_output=True, timeout=180, ) r = subprocess.run( [str(py), "-m", "pip", "install", *pkg_args], capture_output=True, text=True, timeout=900, ) # Always write full output to the log for diagnosis full_log = f"$ {' '.join(map(str, r.args))}\n\n=== STDOUT ===\n{r.stdout or ''}\n\n=== STDERR ===\n{r.stderr or ''}\n" _write_log(full_log) if r.returncode == 0: return True, "" err = (r.stderr or "").strip() or (r.stdout or "").strip() short = err.splitlines()[-1] if err else f"exit {r.returncode}" return False, f"{short[:300]}\n Full log: {log_path}" except subprocess.TimeoutExpired as ex: # Pre-created tool dir guarantees the log path is writable here. _write_log(f"Install timed out (15min): {ex}") return False, f"Install timed out (15min). Log: {log_path}" except subprocess.CalledProcessError as ex: # Catches venv-creation / uv-bootstrap failure (check=True paths). stderr = "" if ex.stderr: try: stderr = ex.stderr.decode("utf-8", errors="replace") if isinstance(ex.stderr, bytes) else str(ex.stderr) except Exception: stderr = "" msg = f"venv create failed (exit {ex.returncode}): {stderr.strip()}" _write_log(msg) return False, msg[:400] except Exception as ex: _write_log(f"Unexpected error: {ex}") return False, str(ex)[:400] finally: try: _tool_venv_lock.release() except RuntimeError: pass def repair_tool_venv(key): """Wipe and recreate a tool's venv. Used by /repair-tool for upgrade or breakage recovery. Returns True if the venv directory was removed.""" venv = tool_venv_dir(key) if venv.exists(): shutil.rmtree(venv, ignore_errors=True) return True return False def shell_join(parts): """Cross-platform shell-quote join for shell=True subprocess calls. Critical when tool_bin is an absolute path that may contain spaces (e.g. C:\\Users\\John Doe\\.codegpt\\tool-venvs\\aider\\Scripts\\aider.exe). Without quoting, the shell tokenizes on the space and runs the wrong binary. Uses subprocess.list2cmdline on Windows (cmd.exe rules) and shlex.join on POSIX. """ if os.name == "nt": return subprocess.list2cmdline([str(p) for p in parts]) return shlex.join([str(p) for p in parts]) # --- End per-tool venv isolation ------------------------------------------ SYSTEM_PROMPT = """You are an AI modeled after a highly technical, system-focused developer mindset. Communication: - Be direct, concise, and dense with information - No fluff, no filler, no emojis - No motivational or overly friendly tone - Give conclusions first, then minimal necessary explanation Thinking: - Break problems into systems and components - Optimize for efficiency, scalability, and control - Focus on practical, real-world solutions - Avoid over-explaining basic concepts Behavior: - Do not sugar-coat - Do not moralize - Do not give generic advice - If uncertain, say so briefly - If incorrect, correct immediately Focus areas: - AI, coding, automation, cybersecurity (defensive), system design Style: - Structured when useful (lists, steps, architecture) - Blunt but intelligent - Slightly dark, high-intensity tone is acceptable Goal: Deliver high-value, efficient, technically sharp responses with zero wasted words.""" AI_TOOLS = { # --- Works everywhere (pip — pure Python) --- "shellgpt": { "name": "ShellGPT", "desc": "AI assistant in your shell", "bin": "sgpt", "install": ["pip", "install", "shell-gpt"], "default_args": [], "needs_key": "OPENAI_API_KEY", "termux": True, }, "llm": { "name": "LLM", "desc": "Simon Willison's multi-model CLI", "bin": "llm", "install": ["pip", "install", "llm"], "default_args": ["chat"], "needs_key": "OPENAI_API_KEY (or plugins)", "termux": True, }, "litellm": { "name": "LiteLLM", "desc": "Unified API for 100+ models", "bin": "litellm", "install": ["pip", "install", "litellm"], "default_args": [], "needs_key": "Any provider key", "termux": True, }, "gorilla": { "name": "Gorilla CLI", "desc": "AI generates CLI commands from English", "bin": "gorilla", "install": ["pip", "install", "gorilla-cli"], "default_args": [], "needs_key": "None — free API", "termux": True, }, "chatgpt": { "name": "ChatGPT CLI", "desc": "Official ChatGPT in terminal", "bin": "chatgpt", "install": ["pip", "install", "chatgpt"], "default_args": [], "needs_key": "OPENAI_API_KEY", "termux": True, }, "aider": { "name": "Aider", "desc": "AI pair programmer — edits your code", "bin": "aider", "install": ["pip", "install", "aider-chat"], "default_args": [], "needs_key": "OPENAI_API_KEY or ANTHROPIC_API_KEY", "termux": True, "isolated": True, "python_version": "3.12", # aider explicitly pins <3.13 }, "interpreter": { "name": "Open Interpreter", "desc": "AI that runs code on your machine", "bin": "interpreter", "install": ["pip", "install", "open-interpreter"], "default_args": [], "needs_key": "OPENAI_API_KEY (or --local)", "termux": True, "isolated": True, "python_version": "3.12", # litellm + tiktoken Py3.13 issues }, "gpt-engineer": { "name": "GPT Engineer", "desc": "AI builds entire projects from prompts", "bin": "gpte", "install": ["pip", "install", "gpt-engineer"], "default_args": [], "needs_key": "OPENAI_API_KEY", "termux": True, "isolated": True, "python_version": "3.12", # langchain + tiktoken — same Py3.13 wall }, "mentat": { "name": "Mentat", "desc": "AI coding agent by AbanteAI", "bin": "mentat", "install": ["pip", "install", "mentat"], "default_args": [], "needs_key": "OPENAI_API_KEY or ANTHROPIC_API_KEY", "termux": True, "isolated": True, "python_version": "3.12", # tiktoken + openai SDK pin }, # --- Works everywhere (npm — pure JS) --- "opencommit": { "name": "OpenCommit", "desc": "AI writes your git commit messages", "bin": "opencommit", "install": ["npm", "i", "-g", "opencommit"], "default_args": [], "needs_key": "OPENAI_API_KEY", "termux": True, }, "ai-shell": { "name": "AI Shell", "desc": "Natural language to shell commands", "bin": "ai", "install": ["npm", "i", "-g", "ai-shell"], "default_args": [], "needs_key": "OPENAI_API_KEY", "termux": True, }, "aipick": { "name": "AIPick", "desc": "AI-powered git commit selector", "bin": "aipick", "install": ["npm", "i", "-g", "aipick"], "default_args": [], "needs_key": "OPENAI_API_KEY", "termux": True, }, "cline": { "name": "Cline", "desc": "Autonomous AI coding agent", "bin": "cline", "install": ["npm", "i", "-g", "cline"], "default_args": [], "needs_key": "ANTHROPIC_API_KEY or OPENAI_API_KEY", "termux": True, }, # --- Platform tools (pkg on Termux, winget on Windows) --- "ollama": { "name": "Ollama", "desc": "Run local LLMs", "bin": "ollama", "install": ["pip", "install", "ollama"], "install_termux": ["pkg", "install", "-y", "ollama"], "install_win": ["winget", "install", "Ollama.Ollama"], "default_args": ["run", "llama3.2"], "needs_key": "None — local", "termux": True, }, "jq": { "name": "jq", "desc": "JSON processor for the command line", "bin": "jq", "install": ["pip", "install", "jq"], "install_termux": ["pkg", "install", "-y", "jq"], "install_win": ["winget", "install", "jqlang.jq"], "default_args": [], "needs_key": "None", "termux": True, }, # --- Desktop/x86 only (native binaries, no ARM) --- "opencode": { "name": "OpenCode", "desc": "AI coding agent — terminal IDE", "bin": "opencode", "install": ["npm", "i", "-g", "opencode-ai"], "default_args": [], "needs_key": "ANTHROPIC_API_KEY or OPENAI_API_KEY", "termux": False, }, "codex": { "name": "Codex", "desc": "OpenAI's coding agent CLI", "bin": "codex", "install": ["npm", "i", "-g", "@openai/codex"], "default_args": [], "needs_key": "OPENAI_API_KEY", "termux": False, # ARM64 build fails on Termux }, "gemini": { "name": "Gemini CLI", "desc": "Google's AI coding CLI", "bin": "gemini", "install": ["npm", "i", "-g", "@google/gemini-cli"], "default_args": [], "needs_key": "Google login", "termux": True, # Pure JS, no native deps }, "copilot": { "name": "GitHub Copilot", "desc": "AI pair programmer in terminal", "bin": "gh", "install": ["gh", "extension", "install", "github/gh-copilot"], "install_termux": ["pkg", "install", "-y", "gh"], "default_args": ["copilot"], "needs_key": "GitHub login", "termux": True, # gh available via pkg }, "gpt4all": { "name": "GPT4All", "desc": "Run AI models 100% offline", "bin": "gpt4all", "install": ["pip", "install", "gpt4all"], "default_args": [], "needs_key": "None — offline", "termux": False, }, "cursor": { "name": "Cursor CLI", "desc": "Cursor AI editor from terminal", "bin": "cursor", "install": ["npm", "i", "-g", "cursor-cli"], "default_args": [], "needs_key": "Cursor account", "termux": True, # Pure JS }, # --- Deploy CLIs (work everywhere) --- "vercel": { "name": "Vercel", "desc": "Deploy frontend apps", "bin": "vercel", "install": ["npm", "i", "-g", "vercel"], "default_args": [], "needs_key": "Vercel account", "termux": True, }, "netlify": { "name": "Netlify", "desc": "Deploy web apps", "bin": "netlify", "install": ["npm", "i", "-g", "netlify-cli"], "default_args": [], "needs_key": "Netlify account", "termux": True, }, "supabase": { "name": "Supabase", "desc": "Backend-as-a-service CLI", "bin": "supabase", "install": ["npm", "i", "-g", "supabase"], "default_args": [], "needs_key": "Supabase account", "termux": True, }, "railway": { "name": "Railway", "desc": "Deploy apps to the cloud", "bin": "railway", "install": ["npm", "i", "-g", "@railway/cli"], "default_args": [], "needs_key": "Railway account", "termux": True, }, "wrangler": { "name": "Wrangler", "desc": "Cloudflare Workers CLI", "bin": "wrangler", "install": ["npm", "i", "-g", "wrangler"], "default_args": [], "needs_key": "Cloudflare account", "termux": True, }, } SUGGESTIONS = [ "Explain how TCP/IP works under the hood", "Write a Python script to monitor CPU usage", "What are the OWASP top 10 vulnerabilities?", "Design a REST API for a todo app", "How does Docker networking work?", "Explain buffer overflow attacks", ] COMMANDS = { "/new": "Start a new conversation", "/save": "Save current conversation", "/load": "Load a saved conversation", "/delete": "Delete a saved conversation", "/copy": "Copy last AI response to clipboard", "/regen": "Regenerate last AI response", "/edit": "Edit & resend last message", "/model": "Switch model (/model )", "/system": "Set system prompt", "/remind": "Set reminder (/remind 5m msg)", "/reminders": "List active reminders", "/voice": "Speak instead of type", "/file": "Read a file into context (/file path)", "/run": "Execute last Python code block", "/code": "Multi-line code input (end with <<<)", "/think": "Toggle deep thinking mode", "/temp": "Set temperature 0.0-2.0 (/temp 0.7)", "/tokens": "Show token usage stats", "/compact": "Summarize conversation to save context", "/search": "Search conversation (/search keyword)", "/export": "Export chat as markdown file", "/diff": "Compare last 2 AI responses", "/pin": "Pin a message for reference (/pin 3)", "/pins": "Show pinned messages", "/modelinfo": "Show current model details", "/params": "Set model params (/params top_p 0.9)", "/prompts": "Prompt template library", "/fork": "Fork conversation from message # (/fork 3)", "/compare": "Compare 2 models on same prompt", "/rate": "Rate last response (good/bad)", "/tag": "Tag current conversation (/tag python)", "/shortcuts": "Show keyboard shortcuts", "/agent": "Run an AI agent (/agent )", "/agents": "List available agents", "/lab": "AI Lab — experiments & tools", "/chain": "Chain prompts (/chain p1 | p2 | p3)", "/mem": "AI memory (/mem save/recall/list)", "/shell": "Run a shell command (/shell dir)", "/usage": "Full usage dashboard", "/openclaw": "Launch OpenClaw AI assistant", "/claude": "Launch Claude Code CLI", "/aider": "Launch Aider (AI pair programmer)", "/interpreter": "Launch Open Interpreter", "/shellgpt": "Launch ShellGPT", "/opencode": "Launch OpenCode (AI coding agent)", "/codex": "Launch Codex (OpenAI coding CLI)", "/gemini": "Launch Gemini CLI (Google AI)", "/copilot": "Launch GitHub Copilot CLI", "/cline": "Launch Cline (coding agent)", "/gpt-engineer": "Launch GPT Engineer", "/mentat": "Launch Mentat (coding agent)", "/ollama": "Launch Ollama (run local models)", "/jq": "Launch jq (JSON processor)", "/llm": "Launch LLM (multi-model CLI)", "/gpt4all": "Launch GPT4All (offline AI)", "/litellm": "Launch LiteLLM (100+ models)", "/opencommit": "Launch OpenCommit (AI git commits)", "/ai-shell": "Launch AI Shell (English to commands)", "/gorilla": "Launch Gorilla CLI (AI commands)", "/chatgpt": "Launch ChatGPT CLI", "/cursor": "Launch Cursor CLI", "/aipick": "Launch AIPick (AI git selector)", "/vercel": "Launch Vercel (deploy)", "/netlify": "Launch Netlify (deploy)", "/supabase": "Launch Supabase CLI", "/railway": "Launch Railway (deploy)", "/wrangler": "Launch Wrangler (Cloudflare)", "/tools": "List all AI tools", "/repair-tool": "Wipe + reinstall a broken isolated tool venv (/repair-tool aider)", "/bg": "Launch tool in new window (/bg claude)", "/split": "Split screen tools (/split claude codex)", "/splitv": "Vertical split (/splitv claude gemini)", "/grid": "4-pane grid of tools (/grid claude codex gemini cline)", "/running": "Show running AI tools", "/killall": "Close all background tools", "/broadcast": "Send message to all tools (/broadcast hello)", "/inbox": "Check messages from other tools", "/dm": "Message a specific tool (/dm claude fix this)", "/chat-link": "Link tools for live conversation", "/monitor": "Live dashboard — all tools & messages", "/feed": "Show all recent tool messages", "/hub": "Full hub view — tools, messages, stats", "/sidebar": "Toggle sidebar on/off", "/all": "Ask ALL agents at once (/all your question)", "/race": "Race all models — who answers first", "/vote": "All agents vote on a question", "/swarm": "Agents collaborate on a task step by step", "/team": "Start a team chat with 2 AIs (/team coder reviewer)", "/room": "AI chat room — multiple AIs talk (/room coder reviewer architect)", "/spectate": "Watch AIs chat without you (/spectate claude codex topic)", "/github": "GitHub tools (/github repos, issues, prs)", "/weather": "Get weather (/weather London)", "/open": "Open URL in browser (/open google.com)", "/spotify": "Spotify controls (/spotify play, pause, next)", "/volume": "Set system volume (/volume 50)", "/bright": "Set screen brightness (/bright 80)", "/sysinfo": "System info (CPU, RAM, disk, network)", "/train": "AI Training Lab (/train help)", "/pin-set": "Set a login PIN", "/pin-remove": "Remove login PIN", "/lock": "Lock session now", "/audit": "View security audit log", "/security": "Security status dashboard", "/permissions": "View/reset action permissions", "/desktop": "Launch CodeGPT desktop app", "/tui": "Launch CodeGPT TUI mode", "/web": "Open CodeGPT website", "/skill": "Create a custom command (/skill name prompt)", "/skills": "List custom skills", "/browse": "Browse a URL and summarize (/browse url)", "/cron": "Schedule a recurring task (/cron 5m /weather)", "/crons": "List scheduled tasks", "/auto": "AI creates a skill from your description", "/connect": "Connect to remote Ollama (/connect 192.168.1.237)", "/disconnect": "Switch back to local Ollama", "/server": "Show current Ollama server", "/qr": "Show QR code to connect from phone", "/scan": "Scan QR code to connect to a server", "/profile": "View your profile", "/setname": "Set display name", "/setbio": "Set bio", "/persona": "Switch persona (/persona hacker)", "/personas": "List all personas", "/history": "Show conversation", "/clear": "Clear screen", "/help": "Show commands", "/quit": "Exit", } TIME_PATTERN = re.compile(r"^(\d+)\s*(s|sec|m|min|h|hr|hour)s?\b", re.IGNORECASE) TIME_MULTIPLIERS = {"s": 1, "sec": 1, "m": 60, "min": 60, "h": 3600, "hr": 3600, "hour": 3600} active_reminders = [] reminder_lock = threading.Lock() console = Console() _hist_path = Path.home() / ".codegpt" / "input_history" _hist_path.parent.mkdir(parents=True, exist_ok=True) try: input_history = FileHistory(str(_hist_path)) except Exception: input_history = InMemoryHistory() # Command categories for autocomplete display CMD_CATEGORIES = {} _cat_map = { "Chat": ["/new", "/save", "/load", "/delete", "/copy", "/regen", "/edit", "/history", "/clear", "/quit"], "Model": ["/model", "/modelinfo", "/params", "/temp", "/think", "/tokens", "/compact", "/system"], "AI Agents": ["/agent", "/agents", "/all", "/vote", "/swarm", "/team", "/room", "/spectate", "/dm", "/chat-link"], "AI Lab": ["/lab", "/chain", "/race", "/prompts", "/compare"], "Tools": ["/tools", "/bg", "/split", "/splitv", "/grid", "/running", "/killall"], "Connect": ["/connect", "/disconnect", "/server", "/qr", "/scan"], "Files & Code": ["/file", "/run", "/code", "/shell", "/browse", "/open", "/export"], "Memory": ["/mem", "/train", "/pin", "/pins", "/search", "/fork", "/rate", "/tag"], "Profile": ["/profile", "/setname", "/setbio", "/persona", "/personas", "/usage"], "Skills": ["/skill", "/skills", "/auto", "/cron", "/crons"], "Comms": ["/broadcast", "/inbox", "/feed", "/monitor", "/hub"], "System": ["/github", "/weather", "/spotify", "/volume", "/bright", "/sysinfo", "/voice", "/remind", "/reminders", "/shortcuts"], "Security": ["/pin-set", "/pin-remove", "/lock", "/audit", "/security", "/permissions"], } for _cat, _cmds in _cat_map.items(): for _cmd in _cmds: CMD_CATEGORIES[_cmd] = _cat # Tools get their own category for _tool_name in AI_TOOLS: CMD_CATEGORIES[f"/{_tool_name}"] = "Tool" CMD_CATEGORIES["/claude"] = "Tool" CMD_CATEGORIES["/openclaw"] = "Tool" CMD_CATEGORIES["/sidebar"] = "UI" CMD_CATEGORIES["/diff"] = "Chat" CMD_CATEGORIES["/help"] = "Help" class SlashCompleter(Completer): """Show all commands with categories when typing /""" def get_completions(self, document, complete_event): text = document.text_before_cursor.lstrip() if text.startswith("/"): typed = text.lower() on_termux = os.path.exists("/data/data/com.termux") # Custom skills first skills = load_skills() for skill_name in skills: cmd = f"/{skill_name}" if cmd.startswith(typed): yield Completion( cmd, start_position=-len(text), display=f"{cmd}", display_meta=f"skill: {skills[skill_name].get('desc', '')[:30]}", ) # Main commands with categories for cmd, desc in COMMANDS.items(): if cmd.startswith(typed): tool_name = cmd[1:] if on_termux and tool_name in AI_TOOLS and not AI_TOOLS[tool_name].get("termux", True): continue cat = CMD_CATEGORIES.get(cmd, "") meta = f"[{cat}] {desc}" if cat else desc yield Completion( cmd, start_position=-len(text), display=f"{cmd}", display_meta=meta, ) # Aliases for alias, target in ALIASES.items(): if alias.startswith(typed) and alias not in COMMANDS: desc = COMMANDS.get(target, "") cat = CMD_CATEGORIES.get(target, "") yield Completion( alias, start_position=-len(text), display=f"{alias}", display_meta=f"-> {target}", ) cmd_completer = SlashCompleter() input_style = PtStyle.from_dict({ "prompt": "ansicyan bold", "bottom-toolbar": "bg:#1a1a2e #888888", "completion-menu": "bg:#1a1a2e #ffffff", "completion-menu.completion": "bg:#1a1a2e #ffffff", "completion-menu.completion.current": "bg:#00aaff #ffffff bold", "completion-menu.meta.completion": "bg:#1a1a2e #888888", "completion-menu.meta.completion.current": "bg:#00aaff #ffffff", }) session_stats = {"messages": 0, "tokens_in": 0, "tokens_out": 0, "start": time.time()} last_ai_response = "" # --- Permissions --- PERMISSION_ALWAYS_ALLOW = set() # Commands the user has approved permanently PERMISSION_FILE = Path.home() / ".codegpt" / "permissions.json" def load_permissions(): global PERMISSION_ALWAYS_ALLOW if PERMISSION_FILE.exists(): try: data = json.loads(PERMISSION_FILE.read_text()) PERMISSION_ALWAYS_ALLOW = set(data.get("always_allow", [])) except Exception: pass def save_permissions(): PERMISSION_FILE.parent.mkdir(parents=True, exist_ok=True) PERMISSION_FILE.write_text(json.dumps({ "always_allow": list(PERMISSION_ALWAYS_ALLOW), }, indent=2)) # Actions that need confirmation — (description, risk level) # Risk: CRITICAL, HIGH, MEDIUM, LOW RISKY_ACTIONS = { # CRITICAL — can damage system, leak data, or run arbitrary code "shell": ("Run a shell command", "CRITICAL"), "code_exec": ("Execute Python code", "CRITICAL"), "tool_install": ("Install a new tool", "CRITICAL"), "connect": ("Connect to a remote server", "CRITICAL"), "pin_set": ("Set a login PIN", "CRITICAL"), # HIGH — external access, data modification "tool_launch": ("Launch an external AI tool", "HIGH"), "open_url": ("Open a URL in browser", "HIGH"), "github": ("Access GitHub", "HIGH"), "delete_chat": ("Delete a saved conversation", "HIGH"), "mem_clear": ("Clear all AI memories", "HIGH"), "train_build": ("Build a custom AI model", "HIGH"), "qr": ("Generate QR code with your IP", "HIGH"), "broadcast": ("Send message to all tools", "HIGH"), "system_prompt": ("Modify system prompt", "HIGH"), # MEDIUM — uses resources, changes settings "file_read": ("Read a file into context", "MEDIUM"), "export": ("Export conversation to file", "MEDIUM"), "save_chat": ("Save conversation to disk", "MEDIUM"), "train_collect": ("Collect conversation as training", "MEDIUM"), "mem_save": ("Save to AI memory", "MEDIUM"), "agent_run": ("Run an AI agent", "MEDIUM"), "swarm": ("Run agent swarm pipeline", "MEDIUM"), "all_agents": ("Ask all agents at once", "MEDIUM"), "race": ("Race all models", "MEDIUM"), "team_chat": ("Start team chat with AIs", "MEDIUM"), "spotify": ("Control Spotify", "MEDIUM"), "volume": ("Change system volume", "MEDIUM"), "brightness": ("Change screen brightness", "MEDIUM"), # LOW — safe changes "model_change": ("Switch AI model", "LOW"), "persona_change": ("Change AI persona", "LOW"), "compact": ("Summarize and compact conversation","LOW"), "fork": ("Fork conversation", "LOW"), } RISK_COLORS = { "CRITICAL": "bold red", "HIGH": "red", "MEDIUM": "yellow", "LOW": "green", } RISK_ICONS = { "CRITICAL": "☠", "HIGH": "⚠", "MEDIUM": "◇", "LOW": "△", } def ask_permission(action, detail=""): """Ask user for permission before performing an action. Returns True if allowed, False if denied.""" # Already permanently approved if action in PERMISSION_ALWAYS_ALLOW: return True # Get action info action_info = RISKY_ACTIONS.get(action, (action, "MEDIUM")) if isinstance(action_info, str): action_desc, risk = action_info, "MEDIUM" else: action_desc, risk = action_info risk_color = RISK_COLORS.get(risk, "yellow") risk_icon = RISK_ICONS.get(risk, "?") # Detailed risk info per level risk_info = { "CRITICAL": { "warning": "Can execute code, modify files, or expose data.", "examples": "shell commands, code execution, installing software", "tip": "Only allow if you trust the command.", }, "HIGH": { "warning": "Accesses external services or modifies data.", "examples": "opening URLs, GitHub access, deleting data", "tip": "Check what it's doing before allowing.", }, "MEDIUM": { "warning": "Uses resources or changes settings.", "examples": "running agents, saving files, training models", "tip": "Generally safe for normal use.", }, "LOW": { "warning": "Safe operation with minimal impact.", "examples": "switching model, changing persona, forking chat", "tip": "Low risk — consider always-allowing.", }, } info = risk_info.get(risk, risk_info["MEDIUM"]) compact = is_compact() # Permission prompt with full context console.print() console.print(Rule(style=risk_color.replace("bold ", ""), characters="─")) console.print() console.print(Text.from_markup(f" [{risk_color}]{risk_icon} {risk}[/] [{risk_color}]{action_desc}[/]")) console.print() if detail: console.print(Text.from_markup(f" [bright_cyan]what:[/] {detail[:70]}")) if not compact: console.print(Text.from_markup(f" [dim]risk:[/] {info['warning']}")) console.print(Text.from_markup(f" [dim]e.g.:[/] {info['examples']}")) console.print(Text.from_markup(f" [dim]tip:[/] {info['tip']}")) else: console.print(Text.from_markup(f" [{risk_color}]{info['warning']}[/]")) console.print() try: answer = prompt( [("class:prompt", " (y)es (n)o (a)lways (?) info > ")], style=input_style, ).strip().lower() except (KeyboardInterrupt, EOFError): audit_log("PERMISSION_DENIED", f"{action}: interrupted") return False if answer in ("?", "info", "help"): # Show detailed info then re-ask console.print() console.print(Text.from_markup( f" [bold]Action:[/] {action_desc}\n" f" [bold]Risk:[/] [{risk_color}]{risk}[/]\n" f" [bold]Warning:[/] {info['warning']}\n" f" [bold]Examples:[/] {info['examples']}\n" f" [bold]Tip:[/] {info['tip']}\n\n" f" [dim]What each option does:[/]\n" f" [bright_cyan]y[/] Allow this one time\n" f" [bright_cyan]n[/] Block this action\n" f" [bright_cyan]a[/] Always allow (saved, never asked again)\n" )) try: answer = prompt( [("class:prompt", " Allow? (y/n/a) > ")], style=input_style, ).strip().lower() except (KeyboardInterrupt, EOFError): return False if answer in ("a", "always"): PERMISSION_ALWAYS_ALLOW.add(action) save_permissions() console.print(Text(f" ✓ Always allowed — {action_desc}", style="green")) audit_log("PERMISSION_ALWAYS", action) return True elif answer in ("y", "yes", ""): audit_log("PERMISSION_GRANTED", action) return True else: console.print(Text(f" ✗ Blocked — {action_desc}", style="red")) audit_log("PERMISSION_DENIED", action) return False # Load saved permissions on startup load_permissions() # --- Security --- SECURITY_DIR = Path.home() / ".codegpt" / "security" SECURITY_DIR.mkdir(parents=True, exist_ok=True) PIN_FILE = SECURITY_DIR / "pin.hash" LOCK_FILE = SECURITY_DIR / "lock.conf" AUDIT_FILE = SECURITY_DIR / "audit.log" # Shell command blocklist SHELL_BLOCKLIST = [ "rm -rf", "del /f", "del /s", "format", "mkfs", "dd if=", "shutdown", "reboot", ":(){", "fork bomb", "rmdir /s", "> /dev/sda", "wget|sh", "curl|sh", "powershell -enc", "reg delete", "net user", "net localgroup", "taskkill /f /im", ] # Max code execution per session CODE_EXEC_LIMIT = 20 code_exec_count = 0 AUTO_LOCK_MINUTES = 10 last_activity = [time.time()] # Rate limiting — prevent rapid-fire commands RATE_LIMIT_WINDOW = 2 # seconds RATE_LIMIT_MAX = 5 # max commands in window _cmd_timestamps = [] def check_rate_limit(): """Block rapid-fire command spam. Returns True if OK.""" now = time.time() # Remove old timestamps while _cmd_timestamps and now - _cmd_timestamps[0] > RATE_LIMIT_WINDOW: _cmd_timestamps.pop(0) _cmd_timestamps.append(now) if len(_cmd_timestamps) > RATE_LIMIT_MAX: return False return True def sanitize_input(text): """Strip control characters and null bytes from user input.""" # Remove null bytes, control chars (except newline/tab) cleaned = "" for c in text: if c == '\x00': continue if ord(c) < 32 and c not in ('\n', '\t', '\r'): continue cleaned += c return cleaned.strip() def hash_pin(pin, salt=None): """Hash a PIN with a random salt. Returns 'salt:hash'.""" if salt is None: salt = base64.b64encode(os.urandom(16)).decode("ascii") pin_hash = hashlib.sha256(f"{salt}:{pin}".encode()).hexdigest() return f"{salt}:{pin_hash}" def set_pin(pin): """Set a new PIN with a random salt. Uses atomic rename to prevent a half-written hash file if the process is killed mid-write.""" import tempfile tmp = Path(tempfile.mktemp(dir=PIN_FILE.parent, prefix=".pin_")) tmp.write_text(hash_pin(pin)) os.replace(str(tmp), str(PIN_FILE)) def verify_pin(pin): """Verify PIN against stored hash. Supports two formats: - Modern: "salt:hash" (random salt per user, secure) - Legacy: plain hex hash using the static 'codegpt_v1_salt' (weak, vulnerable to rainbow tables if the hash file is exfiltrated) On successful verify of a LEGACY hash, auto-upgrades to the modern random-salt format so the weak salt is permanently retired. The user never notices — their PIN stays the same, only the stored format changes. """ if not PIN_FILE.exists(): return True stored = PIN_FILE.read_text().strip() # Modern format: "salt:hash" if ":" in stored and len(stored.split(":", 1)) == 2: salt, expected_hash = stored.split(":", 1) pin_hash = hashlib.sha256(f"{salt}:{pin}".encode()).hexdigest() return pin_hash == expected_hash # Legacy format: static salt — verify, then auto-upgrade if correct. legacy_hash = hashlib.sha256(f"codegpt_v1_salt:{pin}".encode()).hexdigest() if stored == legacy_hash: # Auto-upgrade to modern format with random salt. try: set_pin(pin) except Exception: pass # Upgrade failed — still return True for this verify return True return False def has_pin(): """Check if a PIN is set.""" return PIN_FILE.exists() def remove_pin(): """Remove the PIN.""" if PIN_FILE.exists(): PIN_FILE.unlink() def check_auto_lock(): """Check if session should be locked due to inactivity.""" if not has_pin(): return False elapsed = time.time() - last_activity[0] return elapsed > AUTO_LOCK_MINUTES * 60 def prompt_pin_unlock(): """Prompt for PIN to unlock.""" console.print(Panel( Text("Session locked due to inactivity.", style="bold yellow"), title="[bold yellow]Locked[/]", border_style="yellow", padding=(0, 2), )) for attempt in range(3): try: pin = getpass(f" PIN ({3 - attempt} attempts): ") except (KeyboardInterrupt, EOFError): return False if verify_pin(pin): last_activity[0] = time.time() print_sys("Unlocked.") return True print_err("Wrong PIN.") print_err("Too many attempts. Exiting.") return False def pin_login(): """Initial PIN check on startup.""" if not has_pin(): return True console.print(Panel( Text("PIN required to access CodeGPT.", style="bold"), title="[bold bright_cyan]Security[/]", border_style="bright_cyan", padding=(0, 2), )) for attempt in range(3): try: pin = getpass(f" Enter PIN ({3 - attempt} attempts): ") except (KeyboardInterrupt, EOFError): return False if verify_pin(pin): return True print_err("Wrong PIN.") print_err("Access denied.") return False def audit_log(action, detail=""): """Write to audit log.""" timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") entry = f"[{timestamp}] {action}" if detail: entry += f" | {detail[:100]}" try: with open(AUDIT_FILE, "a", encoding="utf-8") as f: f.write(entry + "\n") except Exception: pass def is_shell_safe(cmd_text): """Check if a shell command is safe to run.""" cmd_lower = cmd_text.lower().strip() # Blocklist check for blocked in SHELL_BLOCKLIST: if blocked in cmd_lower: return False, blocked # Block shell injection patterns injection_patterns = [ r'[;&|`]', # Command chaining/injection r'\$\(', # Command substitution r'>\s*/dev/', # Device writes r'\\x[0-9a-f]', # Hex escapes r'\\u[0-9a-f]', # Unicode escapes r'\brm\b.*-[rR]', # rm with recursive flag (any form) ] for pattern in injection_patterns: if re.search(pattern, cmd_text): return False, f"blocked pattern: {pattern}" # Max command length if len(cmd_text) > 500: return False, "command too long (500 char limit)" return True, "" # --- Profiles --- PROFILES_DIR = Path.home() / ".codegpt" / "profiles" PROFILES_DIR.mkdir(parents=True, exist_ok=True) CLI_PROFILE = PROFILES_DIR / "cli_profile.json" PERSONAS = { "default": SYSTEM_PROMPT, "hacker": ( "You are a cybersecurity expert and ethical hacker. Technical jargon, " "CVEs, attack vectors and defense strategies. Defensive security only. " "Dark humor about data breaches. Concise." ), "teacher": ( "You are a patient programming teacher. Step by step, analogies, " "examples. Adapt to the student. Encourage questions." ), "roast": ( "You are a brutally sarcastic code reviewer. Roast bad code mercilessly " "but always give the correct solution after. Dark humor. You care deep down." ), "architect": ( "You are a senior system architect. Think in scalability, distributed systems, " "microservices. Draw ASCII diagrams. Always consider trade-offs." ), "minimal": "Shortest possible answer. One line if possible. Code only, no commentary.", } DEFAULT_PROFILE = { "name": "", "bio": "", "model": MODEL, "persona": "default", "total_messages": 0, "total_tokens": 0, "total_sessions": 0, "created": None, } def load_profile(): if CLI_PROFILE.exists(): try: data = json.loads(CLI_PROFILE.read_text()) return {**DEFAULT_PROFILE, **data} except Exception: pass return {**DEFAULT_PROFILE} def save_profile(profile): CLI_PROFILE.write_text(json.dumps(profile, indent=2)) def show_profile(): profile = load_profile() w = tw() name = profile["name"] or "Not set" bio = profile["bio"] or "Not set" model = profile["model"] persona = profile["persona"] total_msgs = profile["total_messages"] total_tok = profile["total_tokens"] total_sess = profile["total_sessions"] since = profile["created"][:10] if profile.get("created") else "today" table = Table(border_style="bright_cyan", show_header=False, padding=(0, 2), title="Your Profile", title_style="bold bright_cyan") table.add_column("Field", style="dim", width=14) table.add_column("Value", style="white") table.add_row("Name", name) table.add_row("Bio", bio) table.add_row("Model", f"[bright_cyan]{model}[/]") table.add_row("Persona", f"[green]{persona}[/]") table.add_row("Messages", str(total_msgs)) table.add_row("Tokens", str(total_tok)) table.add_row("Sessions", str(total_sess)) table.add_row("Since", since) console.print(table) console.print() console.print(Text(" Edit: /setname, /setbio, /persona", style="dim")) console.print() def setup_profile(): """First-time welcome & profile setup wizard.""" w = tw() compact = is_compact() # Big welcome popup if compact: console.print(Panel( Text.from_markup( "[bold bright_cyan]Welcome to CodeGPT![/]\n\n" " Your local AI assistant.\n" " 80+ commands. 8 agents.\n" " 29 tools. No cloud needed.\n\n" " Powered by [bold]Ollama[/].\n\n" " [dim]Press Enter...[/]" ), border_style="bright_cyan", padding=(0, 1), width=w, )) else: console.print(Panel( Text.from_markup( "[bold bright_cyan]Welcome to CodeGPT![/]\n\n" " Your local AI assistant hub.\n\n" " [bright_cyan]80+[/] slash commands\n" " [bright_cyan]8[/] AI agents (coder, debugger, reviewer...)\n" " [bright_cyan]29[/] AI tool integrations (Claude, Codex, Gemini...)\n" " [bright_cyan]6[/] personas (hacker, teacher, architect...)\n" " [bright_cyan]15[/] prompt templates\n\n" " No cloud. No API keys. Powered by [bold]Ollama[/].\n\n" " [dim]Press Enter to continue...[/]" ), title="[bold bright_cyan]CodeGPT v1.0[/]", border_style="bright_cyan", padding=(1, 2), width=w, )) # Wait for Enter try: prompt([("class:prompt", " Press Enter to continue... ")], style=input_style) except (KeyboardInterrupt, EOFError): pass clear_screen() print_header(MODEL) console.print(Panel( Text("Let's set up your profile — takes 10 seconds.", style="bold"), border_style="bright_cyan", padding=(0, 1 if compact else 2), width=w, )) console.print() try: name = prompt([("class:prompt", " Your name > ")], style=input_style).strip() bio = prompt([("class:prompt", " Short bio > ")], style=input_style).strip() except (KeyboardInterrupt, EOFError): name = "" bio = "" profile = load_profile() profile["name"] = name or "User" profile["bio"] = bio or "" profile["created"] = datetime.now().isoformat() profile["total_sessions"] = 1 save_profile(profile) # Post-setup quick start guide if compact: console.print(Panel( Text.from_markup( f"[bold green]Hey {profile['name']}![/]\n\n" " [dim]Quick start:[/]\n" " Just type to chat\n" " [bright_cyan]/[/] see all commands\n" " [bright_cyan]/help[/] full guide\n" " [bright_cyan]/connect IP[/] link PC\n\n" " [dim]Press Enter...[/]" ), title="[bold green]Ready[/]", border_style="green", padding=(0, 1), width=w, )) else: console.print(Panel( Text.from_markup( f"[bold green]Welcome, {profile['name']}![/]\n\n" " [bold]Quick start:[/]\n" " [bright_cyan]Just type[/] Chat with the AI\n" " [bright_cyan]/[/] See all commands\n" " [bright_cyan]/help[/] Full command list\n" " [bright_cyan]/persona hacker[/] Change personality\n" " [bright_cyan]/agent coder[/] Use a specialist agent\n" " [bright_cyan]/all question[/] Ask all 8 agents at once\n" " [bright_cyan]/tools[/] Browse 29 AI tools\n" " [bright_cyan]/connect IP[/] Connect to remote Ollama\n\n" " [dim]Tip: Press / to see autocomplete suggestions.[/]\n\n" " [dim]Press Enter to start chatting...[/]" ), title="[bold green]You're all set[/]", border_style="green", padding=(1, 2), width=w, )) # Wait for Enter before entering chat try: prompt([("class:prompt", " Press Enter to start... ")], style=input_style) except (KeyboardInterrupt, EOFError): pass console.print() # --- Sidebar --- sidebar_enabled = False SIDEBAR_WIDTH = 26 def build_sidebar(): """Build the sidebar panel content.""" profile = load_profile() name = profile.get("name", "User") persona = profile.get("persona", "default") mem_count = len(load_memories()) pin_count = len(pinned_messages) elapsed = int(time.time() - session_stats["start"]) msgs = session_stats["messages"] tok = session_stats["tokens_out"] unread = bus_unread("codegpt") # Running tools alive_tools = [n for n, i in running_tools.items() if i.get("proc") is None or i["proc"].poll() is None] lines = [] lines.append(f"[bold bright_cyan]{name}[/]") lines.append(f"[dim]{'━' * (SIDEBAR_WIDTH - 4)}[/]") lines.append("") # Session lines.append("[bold]Session[/]") lines.append(f" [dim]Messages[/] [bright_cyan]{msgs}[/]") lines.append(f" [dim]Tokens[/] [bright_cyan]{tok}[/]") lines.append(f" [dim]Uptime[/] [bright_cyan]{elapsed // 60}m {elapsed % 60}s[/]") lines.append(f" [dim]Persona[/] [green]{persona}[/]") lines.append("") # Think mode / temp lines.append("[bold]Config[/]") lines.append(f" [dim]Think[/] {'[green]ON[/]' if think_mode else '[dim]off[/]'}") lines.append(f" [dim]Temp[/] [bright_cyan]{temperature}[/]") lines.append("") # Memory & Pins lines.append("[bold]Data[/]") lines.append(f" [dim]Memories[/] [bright_cyan]{mem_count}[/]") lines.append(f" [dim]Pinned[/] [bright_cyan]{pin_count}[/]") if unread > 0: lines.append(f" [dim]Inbox[/] [bold red]{unread} new[/]") lines.append("") # Running tools if alive_tools: lines.append("[bold]Running[/]") for t in alive_tools[:5]: lines.append(f" [green]●[/] {t}") lines.append("") # Quick commands lines.append("[bold]Quick[/]") lines.append(" [dim]/h[/] help") lines.append(" [dim]/m[/] model") lines.append(" [dim]/t[/] think") lines.append(" [dim]/a[/] all agents") lines.append(" [dim]/u[/] usage") return "\n".join(lines) def print_with_sidebar(panel): """Print a panel with sidebar if enabled. Auto-disabled on small screens.""" if not sidebar_enabled or is_compact() or console.width < 80: console.print(panel) return from rich.columns import Columns sidebar = Panel( Text.from_markup(build_sidebar()), title="[dim]sidebar[/]", border_style="bright_black", width=SIDEBAR_WIDTH, padding=(0, 1), ) # Adjust main panel width main_width = tw() - SIDEBAR_WIDTH - 2 if hasattr(panel, 'width'): panel.width = main_width console.print(Columns([sidebar, panel], padding=1)) # --- UI Components --- def tw(): return min(console.width, 100) def is_compact(): """Check if terminal is small (Termux, narrow window).""" return console.width < 60 def clear_screen(): os.system("cls" if os.name == "nt" else "clear") LOGO_FULL = """ [bright_cyan] ██████╗ ██████╗ ██████╗ ███████╗[/][bold white] ██████╗ ██████╗ ████████╗[/] [bright_cyan] ██╔════╝██╔═══██╗██╔══██╗██╔════╝[/][bold white] ██╔════╝ ██╔══██╗╚══██╔══╝[/] [bright_cyan] ██║ ██║ ██║██║ ██║█████╗ [/][bold white] ██║ ███╗██████╔╝ ██║ [/] [bright_cyan] ██║ ██║ ██║██║ ██║██╔══╝ [/][bold white] ██║ ██║██╔═══╝ ██║ [/] [bright_cyan] ╚██████╗╚██████╔╝██████╔╝███████╗[/][bold white] ╚██████╔╝██║ ██║ [/] [bright_cyan] ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝[/][bold white] ╚═════╝ ╚═╝ ╚═╝ [/] [dim] Your Local AI Assistant — Powered by Ollama[/]""" LOGO_COMPACT = """ [bold bright_cyan]╔═══════════════════════╗[/] [bold bright_cyan]║[/] [bold white]C O D E[/][bold bright_cyan] G P T[/] [bold bright_cyan]║[/] [bold bright_cyan]╚═══════════════════════╝[/] [dim] Local AI · Ollama[/]""" LOGO = LOGO_FULL # --- Command Aliases --- ALIASES = { "/q": "/quit", "/x": "/quit", "/exit": "/quit", "/n": "/new", "/s": "/save", "/l": "/load", "/c": "/copy", "/r": "/regen", "/e": "/edit", "/h": "/help", "/m": "/model", "/t": "/think", "/f": "/file", "/v": "/voice", "/a": "/all", "/ag": "/agent", "/sw": "/swarm", "/p": "/prompts", "/pr": "/profile", "/u": "/usage", "/tk": "/tokens", "/gh": "/github", "/sp": "/spotify", "/w": "/weather", "/si": "/sysinfo", "/con": "/connect", "/srv": "/server", "/mon": "/monitor", } # --- Tips --- TIPS = [ "Type / to see all commands with autocomplete", "/think toggles deep reasoning mode", "/all asks ALL 8 agents your question at once", "/swarm runs a 6-agent pipeline on any task", "/split claude codex opens both side by side", "/connect IP connects to a remote Ollama server", "/qr generates a QR code to connect from your phone", "/train collect saves this chat as AI training data", "/mem save remembers things across sessions", "/rate good after a response improves future training", "/persona hacker changes the AI personality", "/lab bench benchmarks a prompt across all models", "/chain chains prompts: /chain explain X | simplify | give code", "/dm coder write a Flask app — instant agent response", "/fork 5 branches the conversation from message #5", "/compact summarizes old messages to save context", "/bg claude launches Claude Code in a new window", "You can pipe input: echo 'question' | ai", "/shortcuts shows all keyboard shortcuts", "/tools lists all 25 AI CLI integrations", ] # --- Persistent History --- HISTORY_FILE = Path.home() / ".codegpt" / "input_history" def print_header(model): clear_screen() compact = is_compact() # Shortcut refs to the vivid palette — used throughout this function. CY = CYBER["cyan"] LM = CYBER["lime"] MG = CYBER["magenta"] OR = CYBER["orange"] YL = CYBER["yellow"] PK = CYBER["pink"] PR = CYBER["purple"] GR = CYBER["green"] DM = CYBER["dim"] WH = CYBER["white"] if compact: console.print() console.print(Text.from_markup( f" {rainbow('CodeGPT')} [{DM}]v2.0 · {model}[/]" )) console.print(Text.from_markup(gradient_rule(60))) console.print() else: is_local = "localhost" in OLLAMA_URL or "127.0.0.1" in OLLAMA_URL server = "local" if is_local else OLLAMA_URL.split("//")[1].split("/")[0] if "//" in OLLAMA_URL else "?" profile = load_profile() name = profile.get("name", "") mem_count = len(load_memories()) console.print() # Banner — each border row picks up the rainbow at a different offset # so the box appears to sweep horizontally across each line. box_width = 50 # inner width between ║ walls bar = "═" * box_width def sweep(s, off): return "".join( f"[{CYBER[RAINBOW[(i + off) % len(RAINBOW)]]}]{ch}[/]" for i, ch in enumerate(s) ) console.print(Text.from_markup(f" [{CYBER['red']}]╔[/]{sweep(bar, 0)}[{CYBER['magenta']}]╗[/]")) console.print(Text.from_markup(f" [{CYBER['orange']}]║[/]{' ' * box_width}[{CYBER['pink']}]║[/]")) title = f"{rainbow(' C o d e G P T')} [{DM}]v2.0[/]" pad = box_width - 24 # visual pad, hand-tuned for the spaced title console.print(Text.from_markup(f" [{CYBER['yellow']}]║[/] {title}{' ' * max(0, pad - 4)}[{CYBER['purple']}]║[/]")) subtitle = "local ai · powered by ollama" sub_pad = box_width - len(subtitle) - 4 console.print(Text.from_markup(f" [{CYBER['lime']}]║[/] [{DM} italic]{subtitle}[/]{' ' * sub_pad}[{CYBER['indigo']}]║[/]")) console.print(Text.from_markup(f" [{CYBER['green']}]║[/]{' ' * box_width}[{CYBER['blue']}]║[/]")) console.print(Text.from_markup(f" [{CYBER['teal']}]╚[/]{sweep(bar, 6)}[{CYBER['cyan']}]╝[/]")) console.print() # Info block — each label gets its own accent color so the eye # can scan by hue instead of reading every word. total_tok = profile.get("total_tokens", 0) total_msgs = profile.get("total_messages", 0) sessions = profile.get("total_sessions", 0) pin_on = has_pin() perms = len(PERMISSION_ALWAYS_ALLOW) audit_count = 0 if AUDIT_FILE.exists(): try: audit_count = len(AUDIT_FILE.read_text().strip().splitlines()) except Exception: pass console.print(Text.from_markup( f" [{DM}]model[/] [bold {CY}]{model}[/]\n" f" [{DM}]server[/] [bold {LM}]{server}[/]\n" f" [{DM}]user[/] [bold {WH}]{name or '—'}[/]\n" f" [{DM}]memory[/] [bold {PR}]{mem_count}[/] [{DM}]items[/]" )) console.print() console.print(Text.from_markup( f" [{DM}]tokens[/] [bold {MG}]{total_tok:,}[/] [{DM}]lifetime[/]\n" f" [{DM}]messages[/] [bold {PK}]{total_msgs:,}[/] [{DM}]across[/] [bold {OR}]{sessions}[/] [{DM}]sessions[/]" )) console.print() pin_status = f"[bold {GR}]on[/]" if pin_on else f"[bold {YL}]off[/] [{DM}]— /pin-set to enable[/]" sandbox_status = f"[bold {GR}]active[/]" console.print(Text.from_markup( f" [{DM}]security[/]\n" f" [{DM}]pin lock[/] {pin_status}\n" f" [{DM}]sandbox[/] {sandbox_status}\n" f" [{DM}]permissions[/] [bold {CY}]{perms}[/] [{DM}]always-allowed[/]\n" f" [{DM}]audit log[/] [bold {MG}]{audit_count}[/] [{DM}]events[/]" )) console.print(Text.from_markup(gradient_rule())) console.print() def print_welcome(model, available_models): w = tw() import random compact = is_compact() # Rainbow-cycled greeting so the welcome line has the same vibe as the banner. hour = datetime.now().hour greeting = "Good morning" if hour < 12 else "Good afternoon" if hour < 18 else "Good evening" console.print(Text.from_markup( f" {rainbow(greeting)}[bold {CYBER['white']}]. How can I help?[/]" )) console.print() # Suggestions — each number cycles through the rainbow palette so they # read as a spectrum at a glance. items = SUGGESTIONS[:3] if compact else SUGGESTIONS[:5] for i, s in enumerate(items, 1): hue = CYBER[RAINBOW[(i * 2) % len(RAINBOW)]] console.print(Text.from_markup(f" [bold {hue}]{i}.[/] [{CYBER['dim']}]{s}[/]")) console.print() # Tip tip = random.choice(TIPS) console.print(Text.from_markup( f" [{CYBER['orange']}]tip:[/] [{CYBER['dim']} italic]{tip}[/]" )) console.print() def _build_suggestions(max_items=None): text = Text() items = SUGGESTIONS[:max_items] if max_items else SUGGESTIONS for i, s in enumerate(items, 1): if is_compact(): text.append(f" {i}.", style="bright_cyan bold") text.append(f" {s[:30]}\n", style="white") else: text.append(f" [{i}]", style="bright_cyan bold") text.append(f" {s}\n", style="white") return text def print_user_msg(text): # User messages get a magenta left-gutter accent so they pop visually # against the rainbow AI separator and the dim system lines. console.print() console.print(Text.from_markup( f" [bold {CYBER['magenta']}]▎[/] [bold {CYBER['white']}]{text}[/]" )) console.print() def print_ai_msg(text, stats=""): # AI responses get a full-width rainbow rule as the separator instead # of a solid green one — more colorful while still functioning as a # clear visual divider between turns. w = tw() compact = is_compact() console.print(Text.from_markup(gradient_rule(w))) console.print() console.print(Markdown(text), width=w - 4) if stats and not compact: console.print(Text.from_markup(f" [{CYBER['dim']}]{stats}[/]")) console.print() def print_sys(text): # System/status lines — cyan gutter to distinguish from plain dim output # and give the eye an anchor point. console.print(Text.from_markup( f" [{CYBER['cyan']}]·[/] [{CYBER['dim']}]{text}[/]" )) def print_err(text): # Errors — vivid hot-red with an icon. console.print(Text.from_markup( f" [bold {CYBER['red']}]✗[/] [bold {CYBER['red']}]{text}[/]" )) def print_success(text): # Success — neon mint green with an icon. console.print(Text.from_markup( f" [bold {CYBER['green']}]✓[/] [bold {CYBER['green']}]{text}[/]" )) def _print_err_panel(text): """Legacy panel error for important errors.""" console.print(Panel( Text(text, style="bold red"), title="[bold red]Error[/]", title_align="left", border_style="red", padding=(0, 1), width=tw(), )) def print_help(): # Group commands by category — clean minimal list categories = { "Chat": ["/new", "/save", "/load", "/delete", "/copy", "/regen", "/edit", "/history", "/clear", "/quit"], "Model": ["/model", "/modelinfo", "/params", "/temp", "/think", "/tokens", "/compact"], "AI": ["/agent", "/agents", "/all", "/vote", "/swarm", "/team", "/room", "/spectate", "/dm", "/chat-link"], "Lab": ["/lab", "/chain", "/race", "/prompts"], "Tools": ["/tools", "/bg", "/split", "/grid", "/running", "/killall"], "Connect": ["/connect", "/disconnect", "/server", "/qr", "/scan"], "Files": ["/file", "/run", "/code", "/shell", "/browse", "/open", "/export"], "Memory": ["/mem", "/train", "/pin", "/pins", "/search", "/fork", "/rate", "/tag"], "Profile": ["/profile", "/setname", "/setbio", "/persona", "/personas", "/usage"], "Skills": ["/skill", "/skills", "/auto", "/cron", "/crons"], "Comms": ["/broadcast", "/inbox", "/feed", "/monitor", "/hub"], "System": ["/github", "/weather", "/spotify", "/volume", "/bright", "/sysinfo"], "Security": ["/pin-set", "/pin-remove", "/lock", "/audit", "/security", "/permissions"], } on_termux = os.path.exists("/data/data/com.termux") for cat, cmds in categories.items(): console.print(Text(f"\n {cat}", style="bold bright_cyan")) for cmd in cmds: desc = COMMANDS.get(cmd, "") if not desc: continue # Hide unsupported tool commands on Termux tool_name = cmd[1:] if on_termux and tool_name in AI_TOOLS and not AI_TOOLS[tool_name].get("termux", True): continue console.print(Text.from_markup(f" [bright_cyan]{cmd:<16}[/] [dim]{desc}[/]")) console.print(Text("\n Type / to autocomplete. Aliases: /q /n /s /m /h /a /t /f", style="dim")) console.print() # --- Reminders --- def parse_time(text): match = TIME_PATTERN.match(text.strip()) if not match: return None, None, text value = int(match.group(1)) unit = match.group(2).lower() seconds = value * TIME_MULTIPLIERS[unit] message = text[match.end():].strip() return seconds, f"{value}{unit}", message def fire_reminder(rid, message, label): console.print() console.print(Panel( Text(f" {message}", style="bold yellow"), title=f"[bold yellow]REMINDER[/] [dim]({label} ago)[/]", title_align="left", border_style="yellow", padding=(0, 1), )) with reminder_lock: active_reminders[:] = [r for r in active_reminders if r["id"] != rid] def set_reminder(text): seconds, label, message = parse_time(text) if seconds is None: print_sys("Usage: /remind