### Install and Run CoderBot Globally Source: https://github.com/tommertom/coderbot/blob/main/README.md Alternative installation method. Installs the package globally and then runs the command. ```bash npm install -g @tommertom/coderbot coderbot ``` -------------------------------- ### Install and Run CoderBot Source: https://context7.com/tommertom/coderbot/llms.txt Run CoderBot instantly using npx without global installation. Configure the .env file with your bot token and user ID after the first run. ```bash npx @tommertom/coderbot@latest ``` ```bash npm install -g @tommertom/coderbot coderbot ``` -------------------------------- ### Suggested Linting Setup (Not Implemented) Source: https://github.com/tommertom/coderbot/blob/main/AGENTS.md These commands represent a suggested linting and code quality setup using ESLint, Prettier, and TypeScript's noEmit flag. They are not yet implemented in the project. ```bash # Suggested linting setup (not yet implemented) npx eslint src/**/*.ts npx prettier --check src/**/*.ts npx tsc --noEmit ``` -------------------------------- ### Check OpenCode Version Source: https://github.com/tommertom/coderbot/blob/main/README.md Confirm the installation of the OpenCode CLI tool by checking its version. Installation methods may vary. ```bash opencode --version ``` -------------------------------- ### Start an AI Assistant Session Source: https://github.com/tommertom/coderbot/blob/main/README.md Initiate a session with an AI coding assistant like Copilot, OpenCode, or Gemini. ```bash /copilot # or /opencode, /gemini, /xterm ``` -------------------------------- ### Start GitHub Copilot CLI Session with Directory Source: https://github.com/tommertom/coderbot/blob/main/README.md Initiate a GitHub Copilot CLI session and automatically change the directory to a specified path. ```bash /copilot /home/user/myproject ``` -------------------------------- ### Check Google Gemini Version Source: https://github.com/tommertom/coderbot/blob/main/README.md Verify the installation of the Google Gemini CLI tool by checking its version. Refer to installation instructions for details. ```bash gemini --version ``` -------------------------------- ### Troubleshooting: Build or Start Errors Source: https://github.com/tommertom/coderbot/blob/main/README.md If the bot fails to start, ensure you are using the latest version with 'npx @tommertom/coderbot@latest', check Node.js compatibility (v18+), verify .env file syntax, and check logs for specific error messages. Clearing npm cache may help. ```bash npx @tommertom/coderbot@latest npm cache clean --force ``` -------------------------------- ### Voice Coding Prompt Mode Workflow Example Source: https://github.com/tommertom/coderbot/blob/main/README.md Demonstrates a typical interaction flow in Prompt Mode, where voice commands are directly sent to the terminal. ```text You: /copilot Bot: [Starts Copilot session] You: /audiomode Bot: 🚀 Prompt Mode: Transcribed text will be directly sent to terminal You: [Voice: "Create a TypeScript function to validate email addresses"] Bot: ✅ Transcribed text sent to terminal as prompt Bot: [Copilot responds with generated code] ``` -------------------------------- ### ControlBOT Setup Source: https://github.com/tommertom/coderbot/blob/main/README.md Instructions for setting up the ControlBOT, an optional administrative bot that runs in the parent process to manage worker bots. Requires BotFather token and admin user IDs in .env. ```env CONTROL_BOT_TOKEN=your_control_bot_token CONTROL_BOT_ADMIN_IDS=your_telegram_user_id ``` -------------------------------- ### Start AI Assistant Sessions via Telegram Source: https://context7.com/tommertom/coderbot/llms.txt Initiate terminal sessions with AI coding assistants using Telegram commands. You can start specific AI sessions like Copilot, OpenCode, or Gemini, or a raw bash terminal. ```bash # Start GitHub Copilot CLI session /copilot # Start with optional directory path /copilot /home/user/myproject # Start OpenCode AI session /opencode # Start Google Gemini CLI session /gemini # Start raw bash terminal (no AI assistant) /xterm # Close current session /close ``` -------------------------------- ### Configure .env for Docker Installation Source: https://github.com/tommertom/coderbot/blob/main/README.md Set essential environment variables like Telegram bot tokens and allowed user IDs for Docker deployment. ```env # Required: Your Telegram bot token(s) TELEGRAM_BOT_TOKENS=your_telegram_bot_token_here # Required: Comma-separated list of allowed user IDs ALLOWED_USER_IDS=your_telegram_user_id # Optional: Other configuration options (see Configuration section) XTERM_SESSION_TIMEOUT=1800000 MEDIA_TMP_LOCATION=/tmp/coderBOT_media ``` -------------------------------- ### Voice Coding Copy Mode Workflow Example Source: https://github.com/tommertom/coderbot/blob/main/README.md Illustrates the Copy Mode workflow, where transcribed voice messages are presented for review before use. ```text You: [Voice: "How do I fix this merge conflict?"] Bot: 🎙️ Transcription: `How do I fix this merge conflict?` You: [Reviews transcription, then copies and edits if needed] ``` -------------------------------- ### Troubleshooting: Session Management Source: https://github.com/tommertom/coderbot/blob/main/README.md If commands are not working or you encounter 'No active session' errors, ensure a session is started first using commands like /copilot or /opencode. Check for session timeouts and restart the session if necessary. ```bash /copilot /opencode /gemini /xterm /close ``` -------------------------------- ### Running CoderBOT Application Source: https://github.com/tommertom/coderbot/blob/main/AGENTS.md Commands to start the CoderBOT application. Development mode rebuilds on changes. Production uses the built artifacts. Direct CLI execution is also possible. ```bash # Start in development mode (rebuilds on changes) npm run dev ``` ```bash # Start production build npm start ``` ```bash # Direct CLI execution node ./dist/cli.js ``` -------------------------------- ### Run CoderBot with Docker Compose Source: https://github.com/tommertom/coderbot/blob/main/README.md Start the CoderBot service in detached mode using Docker Compose. ```bash docker compose up -d ``` -------------------------------- ### Check GitHub Copilot Version Source: https://github.com/tommertom/coderbot/blob/main/README.md Verify if GitHub Copilot CLI is installed by checking its version. Ensure the tool is accessible in your system's PATH. ```bash gh copilot --version ``` ```bash copilot --version ``` -------------------------------- ### Start Manual Terminal Session Source: https://github.com/tommertom/coderbot/blob/main/README.md Initiate a manual terminal session using the `/xterm` command. This allows for direct interaction and observation of potential error messages from AI tools. ```bash /xterm ``` -------------------------------- ### Environment Variable for Media Directory Cleanup Source: https://github.com/tommertom/coderbot/blob/main/README.md Set CLEAN_UP_MEDIADIR to true in .env to delete each bot's media directory on startup. This is useful for development and testing to ensure a fresh start. ```env CLEAN_UP_MEDIADIR=true # Delete media directory on startup (useful for development) CLEAN_UP_MEDIADIR=false # Preserve existing media directory (default, recommended for production) ``` -------------------------------- ### PM2 Production Deployment Commands Source: https://github.com/tommertom/coderbot/blob/main/AGENTS.md Manage CoderBOT's production deployment using PM2. These commands cover starting, stopping, restarting, viewing logs, monitoring, and deleting the PM2 process. ```bash # Build and start with PM2 npm run pm2:start ``` ```bash # PM2 management commands npm run pm2:stop npm run pm2:restart npm run pm2:delete npm run pm2:logs npm run pm2:monit npm run pm2:status ``` -------------------------------- ### TypeScript Interface and Type Definitions Source: https://github.com/tommertom/coderbot/blob/main/AGENTS.md Shows examples of defining interfaces for object shapes, using generic service patterns, and defining union types for state management in TypeScript. ```typescript // Interface definitions export interface XtermConfig { maxOutputLines: number; sessionTimeout: number; terminalRows: number; terminalCols: number; shellPath: string; } // Generic service pattern export class BaseService { constructor(protected config: T) {} } // Union types for state management export type BotStatus = 'starting' | 'running' | 'stopped' | 'error'; ``` -------------------------------- ### JSDoc Comments for TypeScript APIs Source: https://github.com/tommertom/coderbot/blob/main/AGENTS.md Provides an example of using JSDoc comments to document TypeScript classes and methods, including descriptions, parameter types, and return values, adhering to documentation best practices. ```typescript /** * Configuration Service * * Centralizes all environment variable access and provides type-safe * configuration management for bot instances. */ export class ConfigService { /** * Gets the maximum number of output lines to keep in buffer * @returns The configured maximum output lines */ public getXtermMaxOutputLines(): number { return this.xtermMaxOutputLines; } } ``` -------------------------------- ### ControlBOT Process Management Commands Source: https://github.com/tommertom/coderbot/blob/main/README.md Commands to manage worker bot processes, including checking status, starting, stopping, restarting, and managing all bots. ```text /status - Show status of all worker bots ``` ```text /start - Start a specific bot ``` ```text /stop - Stop a specific bot ``` ```text /restart - Restart a specific bot ``` ```text /stopall - Stop all running bots ``` ```text /startall - Start all stopped bots ``` ```text /restartall - Restart all bots ``` -------------------------------- ### Manage Bot Processes with ProcessManager Source: https://context7.com/tommertom/coderbot/llms.txt Utilize ProcessManager to start, stop, restart, and monitor individual or all bot worker processes. It requires a ConfigService instance for its operations. ```typescript import { ProcessManager } from './services/process-manager.service.js'; import { ConfigService } from './services/config.service.js'; const configService = new ConfigService(); const processManager = new ProcessManager(configService); // Start a bot worker await processManager.startBot('bot-1', 'telegram_token_here'); // Stop a specific bot await processManager.stopBot('bot-1'); // Restart a bot await processManager.restartBot('bot-1'); // Manage all bots await processManager.startAllBots(); await processManager.stopAllBots(); await processManager.restartAllBots(); // Check bot status const isRunning = processManager.isBotRunning('bot-1'); // boolean const status = processManager.getBotStatus('bot-1'); // BotProcessInfo | undefined const allStatuses = processManager.getAllBotStatuses(); // BotProcessInfo[] // BotProcessInfo structure: // { // botId: string, // status: 'running' | 'stopped' | 'starting' | 'stopping' | 'error', // pid: number | undefined, // uptime: number, // fullName?: string, // username?: string, // lastError?: string // } // Get bot logs const logs = processManager.getBotLogs('bot-1', 100); // string[] // Health check const isHealthy = await processManager.performHealthCheck('bot-1'); // boolean ``` -------------------------------- ### Testing Commands for CoderBOT Source: https://github.com/tommertom/coderbot/blob/main/AGENTS.md While automated tests are not configured, these commands relate to testing. `npm test` currently shows an error. Manual test execution involves running individual test files after starting the bot in development mode. ```bash # No automated test runner configured npm test # Currently just prints "Error: no test specified" ``` ```bash # Manual test execution (run individual test files) node tests/test_cwd.ts node tests/buffer-change-detection.test.ts ``` ```bash # To run a single manual test scenario: # 1. Start the bot: npm run dev # 2. Follow the test scenarios documented in the test files # 3. Use Telegram to interact with the bot as described ``` -------------------------------- ### Send ASCII Control Characters with Coderbot Source: https://github.com/tommertom/coderbot/blob/main/README.md The /ctrl command supports all 33 ASCII control characters, including letters and special characters. Common examples include interrupting processes, sending EOF, suspending processes, clearing the screen, and navigating text. ```text /ctrl a through /ctrl z (Ctrl+A through Ctrl+Z) ``` ```text /ctrl @ /ctrl [ /ctrl \ /ctrl ] /ctrl ^ /ctrl _ /ctrl ? ``` ```text /ctrl c - Interrupt process (SIGINT) ``` ```text /ctrl d - Send EOF / logout ``` ```text /ctrl z - Suspend process (SIGTSTP) ``` ```text /ctrl l - Clear screen ``` ```text /ctrl r - Reverse search in bash history ``` ```text /ctrl a - Move to beginning of line ``` ```text /ctrl e - Move to end of line ``` ```text /ctrl k - Delete to end of line ``` ```text /ctrl u - Delete entire line ``` ```text /ctrl w - Delete word backward ``` -------------------------------- ### Run CoderBot Instantly with npx Source: https://github.com/tommertom/coderbot/blob/main/README.md Recommended way to run CoderBot. Creates a .env file for configuration on first run. ```bash npx @tommertom/coderbot@latest ``` -------------------------------- ### Startup Prompt Configuration Source: https://context7.com/tommertom/coderbot/llms.txt Commands for setting and managing the startup prompt for coders. ```APIDOC ## Set startup prompt for any coder (sent automatically on launch) /startup resume /startup "Please continue from where we left off" /startup delete # Remove startup prompt /startup # View current startup prompt ``` -------------------------------- ### View Configured Macros Source: https://github.com/tommertom/coderbot/blob/main/README.md Use the /macros command to display all configured message placeholders (m0-m9) and their corresponding values. Unconfigured placeholders will show as 'undefined'. ```text You: /macros Bot: ⚙️ Message Placeholders [m0] → `copy the generated file(s) to /tmp/coderBOT_media/bot-2` [m1] → `git status` [m2] → `docker-compose up -d` [m3] → `npm test` [m4] → `git pull origin main` [m5] → undefined [m6] → undefined [m7] → undefined [m8] → undefined [m9] → undefined ``` -------------------------------- ### Configure and Use Message Placeholders Source: https://context7.com/tommertom/coderbot/llms.txt Define custom commands in the .env file and use them as placeholders in messages. Placeholders are replaced before execution. ```bash # Configure in .env file: # M0=npm run build # M1=git status # M2=docker-compose up -d # Use in messages (placeholders are replaced before execution) [m0] # Executes: npm run build First check: [m1] # Executes: First check: git status [m0] && [m2] # Executes: npm run build && docker-compose up -d ``` -------------------------------- ### Configure Message Placeholders (Macros) Source: https://github.com/tommertom/coderbot/blob/main/README.md Define shortcuts (M0-M9) in your .env file for frequently used commands. These placeholders are replaced before other processing and can be used multiple times in a single message. ```env M0=copy the generated file(s) to /tmp/coderBOT_media/bot-2 M1=git status M2=docker-compose up -d M3=npm test M4=git pull origin main ``` -------------------------------- ### Docker Deployment Source: https://context7.com/tommertom/coderbot/llms.txt Instructions for running CoderBot in a containerized environment using Docker. ```APIDOC ## Docker Deployment Run CoderBot in a containerized environment. ### Setup 1. Create a `.env` file in the project root with your configuration: ```bash TELEGRAM_BOT_TOKENS=your_token_here ALLOWED_USER_IDS=your_user_id XTERM_SESSION_TIMEOUT=1800000 MEDIA_TMP_LOCATION=/tmp/coderBOT_media ``` ### Running CoderBot - **Start**: `docker compose up -d` - **View Logs**: `docker compose logs -f` - **Stop**: `docker compose down` ``` -------------------------------- ### Usage of Message Placeholders Source: https://github.com/tommertom/coderbot/blob/main/README.md Demonstrates how to use configured message placeholders (e.g., [m0]) in your messages. Placeholders are replaced with their configured values before execution. ```text You: [m0] Bot: ✅ Sent (executes: copy the generated file(s) to /tmp/coderBOT_media/bot-2) ``` ```text You: First let me check: [m1] Bot: ✅ Sent (executes: First let me check: git status) ``` ```text You: [m0] && [m3] Bot: ✅ Sent (executes: copy the generated file(s) to /tmp/coderBOT_media/bot-2 && npm test) ``` -------------------------------- ### TypeScript Imports and Dependencies Source: https://github.com/tommertom/coderbot/blob/main/AGENTS.md Demonstrates correct import syntax for external dependencies (no file extensions) and internal modules (using .js extensions as required by ESM). Includes type-only imports. ```typescript // External dependencies - no file extensions import dotenv from 'dotenv'; import * as fs from 'fs'; // Internal modules - use .js extensions (ESM requirement) import { ConfigService } from './services/config.service.js'; import { XtermService } from '../features/xterm/xterm.service.js'; // Type-only imports import type { PtySession } from './xterm.types.js'; ``` -------------------------------- ### Initialize and Use ConfigService Source: https://context7.com/tommertom/coderbot/llms.txt Instantiate the ConfigService to access type-safe environment variables for various bot functionalities. Call validate() to ensure all required configurations are present. ```typescript import { ConfigService } from './services/config.service.js'; const config = new ConfigService(); // Validate configuration (throws if invalid) config.validate(); // Telegram Configuration const tokens = config.getTelegramBotTokens(); // string[] const allowedUsers = config.getAllowedUserIds(); // number[] const autoKill = config.isAutoKillEnabled(); // boolean // Terminal Configuration const maxLines = config.getXtermMaxOutputLines(); // number (default: 1000) const timeout = config.getXtermSessionTimeout(); // number (default: 1800000) const rows = config.getXtermTerminalRows(); // number (default: 50) const cols = config.getXtermTerminalCols(); // number (default: 100) const shell = config.getXtermShellPath(); // string (default: /bin/bash) // Media Configuration const mediaPath = config.getMediaTmpLocation(); // string const cleanMedia = config.shouldCleanUpMediaDir(); // boolean // Audio Transcription const hasTts = config.hasTtsApiKey(); // boolean const provider = config.detectTtsProvider(); // 'openai' | 'gemini' | null const ttsKey = config.getTtsApiKey(); // string | undefined // Control Bot const hasControl = config.hasControlBot(); // boolean const controlToken = config.getControlBotToken(); // string | undefined const adminIds = config.getControlBotAdminIds(); // number[] // Message Placeholders const m0 = config.getMPlaceholder(0); // string | undefined const allPlaceholders = config.getAllMPlaceholders(); // Map // AI Arguments const copilotArgs = config.getCopilotArguments(); // string const geminiArgs = config.getGeminiArguments(); // string // Debug info console.log(config.getDebugInfo()); ``` -------------------------------- ### Recommended Deployment Architecture Diagram Source: https://github.com/tommertom/coderbot/blob/main/README.md Visual representation of a secure deployment architecture for Coderbot, emphasizing isolation and restricted access. ```text ┌─────────────────────────────────────────┐ │ Isolated Environment (Docker/VM) │ │ ┌─────────────────────────────────────┐ │ │ │ Limited User (non-root) │ │ │ │ ┌─────────────────────────────────┐ │ │ │ │ │ Coder Bot │ │ │ │ │ │ - No sudo access │ │ │ │ │ │ - Restricted file system │ │ │ │ │ │ - AUTO_KILL=true │ │ │ │ │ │ - Firewall rules │ │ │ │ │ └─────────────────────────────────┘ │ │ │ └─────────────────────────────────────┘ │ └─────────────────────────────────────────┘ ↕ (Telegram API only) 🌐 Internet ``` -------------------------------- ### Docker Deployment Configuration and Execution Source: https://context7.com/tommertom/coderbot/llms.txt Deploy CoderBot using Docker. Create a .env file for configuration and use docker compose commands to manage the containerized application. ```bash # Create .env file with configuration cat > .env << EOF TELEGRAM_BOT_TOKENS=your_token_here ALLOWED_USER_IDS=your_user_id XTERM_SESSION_TIMEOUT=1800000 MEDIA_TMP_LOCATION=/tmp/coderBOT_media EOF # Run with Docker Compose docker compose up -d # View logs docker compose logs -f # Stop docker compose down ``` -------------------------------- ### Troubleshooting: Media File Sending Source: https://github.com/tommertom/coderbot/blob/main/README.md If media files are not being sent, verify that the MEDIA_TMP_LOCATION directory exists and is writable, and that the bot has read access to the files. Ensure files are completely written before testing. ```bash MEDIA_TMP_LOCATION ``` -------------------------------- ### ControlBOT Bot Configuration Commands Source: https://github.com/tommertom/coderbot/blob/main/README.md Commands for managing bot configurations, including listing bots, adding new bots with a token, removing bots, and reloading .env configurations. ```text /listbots - List all configured bots ``` ```text /addbot - Add and start a new bot ``` ```text /removebot - Remove a bot ``` ```text /reload - Reload .env configuration ``` -------------------------------- ### Coderbot Project File Structure Source: https://github.com/tommertom/coderbot/blob/main/AGENTS.md Illustrates the standard directory layout for the Coderbot project, organizing code into logical modules like app, features, services, and constants. ```tree src/ ├── app.ts # Main application entry ├── cli.ts # CLI interface ├── bot-worker.ts # Bot worker process ├── constants/ # Application constants ├── features/ # Feature modules (coder, xterm, audio, etc.) ├── services/ # Business logic services ├── middleware/ # Telegram middleware ├── types/ # TypeScript type definitions ├── utils/ # Utility functions └── tests/ # Manual test scenarios ``` -------------------------------- ### Build Commands for CoderBOT Source: https://github.com/tommertom/coderbot/blob/main/AGENTS.md Use these npm scripts for building the CoderBOT project. Development builds are faster with sourcemaps, while production builds are optimized and minified. TypeScript type checking and watch mode are also available. ```bash # Development build (fast, with sourcemaps) npm run build ``` ```bash # Production build (minified, optimized) npm run build:prod ``` ```bash # TypeScript type checking only npm run build:tsc ``` ```bash # Watch mode for development npm run watch ``` -------------------------------- ### Dot Command Prefix for Quick Commands Source: https://github.com/tommertom/coderbot/blob/main/README.md Prefix commands with a dot (.) to automatically send them with an Enter key press. This is a shortcut for the /send command. ```text .ls -la → sends: ls -la + Enter ``` ```text .git status → sends: git status + Enter ``` ```text .npm start → sends: npm start + Enter ``` -------------------------------- ### Configure API Keys for Voice Coding Source: https://github.com/tommertom/coderbot/blob/main/README.md Set your OpenAI Whisper or Google Gemini API key in the .env file to enable voice transcription. ```env # Option 1: OpenAI Whisper (recommended for accuracy) OPENAI_API_KEY=your_openai_api_key_here # Option 2: Google Gemini (alternative) GOOGLE_GEMINI_API_KEY=your_gemini_api_key_here ``` -------------------------------- ### Async/Await Patterns in TypeScript Source: https://github.com/tommertom/coderbot/blob/main/AGENTS.md Illustrates the preferred async/await pattern for asynchronous operations in TypeScript, including using `Promise.all` for concurrency and proper error handling within async functions. ```typescript // Good: async/await with proper error handling export async function initializeBot(): Promise { try { await this.configService.validate(); await Promise.all([ this.startXtermService(), this.startMediaWatcher() ]); } catch (error) { throw new Error(`Bot initialization failed: ${ErrorUtils.formatError(error)}`); } } ``` -------------------------------- ### Media File Handling Source: https://context7.com/tommertom/coderbot/llms.txt Upload and receive various media files through the bot. Supported types include photos, videos, audio, and voice messages. Files in the [media] directory are auto-sent. ```APIDOC ## Media File Handling Upload and receive media files through the bot. ```bash # Supported upload types (automatically saved to received directory): # - Photos: JPG, PNG, WebP, etc. # - Videos: MP4, MOV, AVI, etc. # - Audio: MP3, WAV, AAC, etc. # - Voice messages # Files copied to [media] directory are auto-sent to users cp generated_chart.png [media] # Find recent markdown files in current directory /md ``` ``` -------------------------------- ### Check GitHub CLI Authentication Status Source: https://github.com/tommertom/coderbot/blob/main/README.md Verify that your GitHub CLI is authenticated. This is a prerequisite for using GitHub Copilot. ```bash gh auth status ``` -------------------------------- ### Bot Media Directory Structure Source: https://github.com/tommertom/coderbot/blob/main/README.md Each bot worker has an isolated media directory containing 'sent' and 'received' subfolders. This structure ensures media files are organized per bot. ```treeview {MEDIA_TMP_LOCATION}/ ├── bot-0/ │ ├── sent/ │ └── received/ ├── bot-1/ │ ├── sent/ │ └── received/ └── bot-N/ ├── sent/ └── received/ ``` -------------------------------- ### Configure Telegram Bot Tokens Source: https://github.com/tommertom/coderbot/blob/main/README.md Set the TELEGRAM_BOT_TOKENS environment variable to configure one or multiple Telegram bot tokens. Tokens should be comma-separated for multiple bots. ```env # Telegram Bot Configuration (Required) # Single bot: provide one token # Multiple bots: provide comma-separated tokens (each bot runs independently with isolated sessions) # Example single: TELEGRAM_BOT_TOKENS=1234567890:ABCdefGHIjklMNOpqrsTUVwxyz # Example multi: TELEGRAM_BOT_TOKENS=1234567890:ABCdefGHI,0987654321:XYZabcDEF TELEGRAM_BOT_TOKENS=your_telegram_bot_token_here ``` -------------------------------- ### Troubleshooting: Restarting the Bot Source: https://github.com/tommertom/coderbot/blob/main/README.md If the bot is not responding, verify it is running using 'pm2 status' and restart it with 'pm2 restart coderbot'. Ensure your User ID is in ALLOWED_USER_IDS and TELEGRAM_BOT_TOKEN is correct. ```bash pm2 status pm2 restart coderbot ``` -------------------------------- ### User ID Whitelist Configuration Source: https://github.com/tommertom/coderbot/blob/main/README.md Configure the ALLOWED_USER_IDS environment variable to create a whitelist of Telegram user IDs that are permitted to use the bot. ```env # Single user ALLOWED_USER_IDS=123456789 ``` -------------------------------- ### View CoderBot Docker Logs Source: https://github.com/tommertom/coderbot/blob/main/README.md Monitor the CoderBot service logs in real-time to verify its status and troubleshoot issues. ```bash docker compose logs -f ``` -------------------------------- ### ConfigService API Source: https://context7.com/tommertom/coderbot/llms.txt Centralized configuration management with type-safe environment variable access. ```APIDOC ## ConfigService API Centralized configuration management with type-safe environment variable access. ### Methods - `validate()`: Validates the configuration. Throws an error if the configuration is invalid. - `getTelegramBotTokens()`: Returns an array of Telegram bot tokens. - `getAllowedUserIds()`: Returns an array of allowed user IDs. - `isAutoKillEnabled()`: Returns a boolean indicating if auto-kill is enabled. - `getXtermMaxOutputLines()`: Returns the maximum output lines for the terminal (default: 1000). - `getXtermSessionTimeout()`: Returns the session timeout for the terminal (default: 1800000). - `getXtermTerminalRows()`: Returns the number of rows for the terminal (default: 50). - `getXtermTerminalCols()`: Returns the number of columns for the terminal (default: 100). - `getXtermShellPath()`: Returns the path to the terminal shell (default: /bin/bash). - `getMediaTmpLocation()`: Returns the temporary media storage location. - `shouldCleanUpMediaDir()`: Returns a boolean indicating if the media directory should be cleaned up. - `hasTtsApiKey()`: Returns a boolean indicating if a TTS API key is present. - `detectTtsProvider()`: Detects the TTS provider ('openai', 'gemini', or null). - `getTtsApiKey()`: Returns the TTS API key. - `hasControlBot()`: Returns a boolean indicating if the control bot is enabled. - `getControlBotToken()`: Returns the control bot token. - `getControlBotAdminIds()`: Returns an array of control bot admin IDs. - `getMPlaceholder(index)`: Returns the placeholder string at the specified index. - `getAllMPlaceholders()`: Returns a map of all message placeholders. - `getCopilotArguments()`: Returns the arguments for Copilot. - `getGeminiArguments()`: Returns the arguments for Gemini. - `getDebugInfo()`: Returns debug information about the configuration. ``` -------------------------------- ### Error Handling with ErrorUtils Source: https://github.com/tommertom/coderbot/blob/main/AGENTS.md Demonstrates how to use the `ErrorUtils` pattern for consistent error message creation and formatting within a try-catch block in TypeScript. ```typescript import { ErrorUtils } from '../utils/error.utils.js'; try { // Risky operation await riskyAsyncOperation(); } catch (error) { // Use ErrorUtils for consistent formatting const errorMessage = ErrorUtils.createErrorMessage( 'initialize bot session', error ); console.error(errorMessage); throw new Error(`Bot initialization failed: ${ErrorUtils.formatError(error)}`); } ``` -------------------------------- ### Environment Configuration for CoderBot Source: https://context7.com/tommertom/coderbot/llms.txt Configure CoderBot using environment variables in a .env file. Essential variables include Telegram bot tokens and allowed user IDs. Optional settings control terminal behavior, media handling, and AI assistant arguments. ```bash # Required: Telegram Bot Configuration # Single bot token or comma-separated for multiple instances TELEGRAM_BOT_TOKENS=1234567890:ABCdefGHIjklMNOpqrsTUVwxyz # Required: Comma-separated list of allowed Telegram User IDs ALLOWED_USER_IDS=123456789,987654321 # Security: Auto-kill on unauthorized access (default: false) AUTO_KILL=true # Terminal Configuration XTERM_MAX_OUTPUT_LINES=1000 XTERM_SESSION_TIMEOUT=1800000 # 30 minutes in ms XTERM_TERMINAL_ROWS=50 XTERM_TERMINAL_COLS=100 XTERM_FONT_SIZE=18 XTERM_SHELL_PATH=/bin/bash # Media Configuration MEDIA_TMP_LOCATION=/tmp/coderBOT_media CLEAN_UP_MEDIADIR=false # Auto-refresh Configuration SCREEN_REFRESH_INTERVAL=5000 # 5 seconds SCREEN_REFRESH_MAX_COUNT=5 # Optional: Control Bot for multi-instance management CONTROL_BOT_TOKEN=your_control_bot_token CONTROL_BOT_ADMIN_IDS=123456789 # Optional: Audio Transcription (OpenAI or Gemini) TTS_API_KEY=sk-proj-your-openai-key AUDIO_TRANSCRIPTION_DEFAULT_MODE=copy # or 'prompt' # Optional: AI Assistant Arguments COPILOT_ARGUMENTS=--allow-all-tools --deny-tool 'shell(rm)' GEMINI_ARGUMENTS= OPENCODE_ARGUMENTS= # Optional: Message Placeholders (M0-M9) M0=npm run build M1=git status ``` -------------------------------- ### Add Custom AI Assistant Commands Source: https://context7.com/tommertom/coderbot/llms.txt Define custom commands to launch terminal sessions with your preferred AI assistant or CLI tool. Use the /addcoder command followed by your desired command name. ```bash # Add a custom coder (lowercase a-z only) /addcoder mycoder # Now you can use /mycoder to start a session # The bot executes 'mycoder' command in the terminal /mycoder ``` -------------------------------- ### Configure Allowed User IDs Source: https://github.com/tommertom/coderbot/blob/main/README.md Define a comma-separated list of user IDs that are permitted to access the bot. This is a fundamental setting for controlling access. ```env ALLOWED_USER_IDS=123456789,987654321,555666777 ``` -------------------------------- ### Configure Allowed User IDs Source: https://github.com/tommertom/coderbot/blob/main/README.md Set the ALLOWED_USER_IDS environment variable to a comma-separated list of Telegram User IDs permitted to use the bot. ```env # Access Control (Required) # Comma-separated list of Telegram User IDs allowed to use the bot # Example: ALLOWED_USER_IDS=123456789,987654321 ALLOWED_USER_IDS=your_telegram_user_id ``` -------------------------------- ### Render Terminal Output to PNG with XtermRendererService Source: https://context7.com/tommertom/coderbot/llms.txt Render terminal output to PNG images using Puppeteer. Requires initialization and cleanup of browser resources. ```typescript import { XtermRendererService } from './features/xterm/xterm-renderer.service.js'; import { ConfigService } from './services/config.service.js'; const configService = new ConfigService(); const renderer = new XtermRendererService(configService); // Initialize browser (called automatically on first render) await renderer.initialize(); // Render terminal output to PNG image const outputBuffer = ['$ ls -la\n', 'total 32\n', 'drwxr-xr-x 5 user user 4096 ...\n']; const rows = 50; const cols = 100; const imageBuffer = await renderer.renderToImage(outputBuffer, rows, cols); // Use imageBuffer (Buffer) to send as photo via Telegram // await ctx.replyWithPhoto(new InputFile(imageBuffer)); // Cleanup browser resources await renderer.cleanup(); ``` -------------------------------- ### TypeScript Naming Conventions Source: https://github.com/tommertom/coderbot/blob/main/AGENTS.md Illustrates the recommended naming conventions for TypeScript code: PascalCase for classes/interfaces, camelCase for methods/properties, UPPER_SNAKE_CASE for constants, and kebab-case for filenames. ```typescript // Classes and Interfaces - PascalCase export class ConfigService {} export interface XtermConfig {} // Methods and Properties - camelCase private telegramBotTokens: string[]; public getXtermMaxOutputLines(): number {} // Constants - UPPER_SNAKE_CASE export const DEFAULT_SESSION_TIMEOUT = 1800000; // Files - kebab-case with descriptive names // config.service.ts, xterm-renderer.service.ts ``` -------------------------------- ### Troubleshooting: Refreshing Screenshot Source: https://github.com/tommertom/coderbot/blob/main/README.md If the /screen command shows old or blank output, wait a moment for the terminal to respond, click the refresh button, or check if the terminal process is running. Puppeteer may require more system resources. ```bash /screen ``` -------------------------------- ### Configure Session Timeout Source: https://github.com/tommertom/coderbot/blob/main/README.md Set the session timeout in milliseconds. The default is 1800000 milliseconds (30 minutes). ```env # Session timeout in milliseconds (default: 1800000 = 30 minutes) ``` -------------------------------- ### Manage Terminal Screenshots Source: https://context7.com/tommertom/coderbot/llms.txt Capture and view terminal output as images or text. Toggle between text mode for low bandwidth and image mode for visual output. Screenshots auto-refresh after commands. ```bash # Capture current terminal screenshot /screen # Toggle airplane mode (text vs images) /airplane # Show current status /airplane on # Enable text mode (low bandwidth) /airplane off # Enable image mode (default) # Click the refresh button on screenshots to update # Auto-refresh happens automatically after commands ``` -------------------------------- ### View and Manage Terminal Output Source: https://github.com/tommertom/coderbot/blob/main/README.md Commands to capture screenshots, manage auto-refresh status, view markdown files, and display configured message placeholders. ```text /screen - Capture and view terminal screenshot ``` ```text /refresh - Show auto-refresh status and configuration ``` ```text /refresh on - Enable automatic screen refreshes after commands ``` ```text /refresh off - Disable automatic screen refreshes ``` ```text /md - Show 5 most recently updated markdown files with clickable menu ``` ```text /macros - Show all configured message placeholders (m0-m9) and their values ``` -------------------------------- ### Configure Auto-Kill Security Source: https://github.com/tommertom/coderbot/blob/main/README.md Set AUTO_KILL to 'true' to enable the feature that shuts down the bot upon an unauthorized access attempt. All allowed users are notified before shutdown. ```env # Security (Optional) # Auto-kill bot on unauthorized access attempt (default: false) # When enabled, bot shuts down if an unknown user tries to access it # All allowed users are notified before shutdown AUTO_KILL=true ``` -------------------------------- ### Execute Emergency Bot Shutdown Command Source: https://github.com/tommertom/coderbot/blob/main/README.md Use the /killbot command to immediately terminate the bot process. This is useful for emergency situations, maintenance, or forcing all sessions to close. ```bash /killbot ``` -------------------------------- ### ControlBOT Administrative Command Source: https://github.com/tommertom/coderbot/blob/main/README.md Use the /shutdown command to shut down the entire system managed by ControlBOT. ```text /shutdown - Shutdown entire system ``` -------------------------------- ### Manage Terminal Sessions with XtermService Source: https://context7.com/tommertom/coderbot/llms.txt Programmatically manage PTY terminal sessions, including creation, writing commands, reading output, and closing sessions. ```typescript import { XtermService } from './features/xterm/xterm.service.js'; import { ConfigService } from './services/config.service.js'; const configService = new ConfigService(); const xtermService = new XtermService(configService); // Create a new terminal session xtermService.createSession( userId, // Unique user identifier chatId, // Telegram chat ID (userId, chatId, data) => { // onDataCallback: Called when terminal produces output console.log(`Output for ${userId}: ${data}`); }, (userId, chatId) => { // onBufferingEndedCallback: Called when output stabilizes console.log(`Buffer stable for ${userId}`); } ); // Check if session exists if (xtermService.hasSession(userId)) { // Write command with Enter xtermService.writeToSession(userId, 'ls -la'); // Write raw characters without Enter xtermService.writeRawToSession(userId, '\x03'); // Ctrl+C // Get terminal output const output = await xtermService.getSessionOutput(userId, 500); const buffer = xtermService.getSessionOutputBuffer(userId); // Get terminal dimensions const { rows, cols } = xtermService.getSessionDimensions(userId); // Get current working directory const cwd = await xtermService.getSessionCwd(userId); // Close session xtermService.closeSession(userId); } // Get active session count const count = xtermService.getActiveSessions(); // Cleanup all sessions xtermService.cleanup(); ``` -------------------------------- ### Message Placeholders (Macros) Source: https://context7.com/tommertom/coderbot/llms.txt Utilize configurable placeholders (macros) in messages for frequently used commands. These placeholders are replaced before execution. ```APIDOC ## Message Placeholders Use configurable placeholders in messages for frequently used commands. ```bash # Configure in .env file: # M0=npm run build # M1=git status # M2=docker-compose up -d # Use in messages (placeholders are replaced before execution) [m0] # Executes: npm run build First check: [m1] # Executes: First check: git status [m0] && [m2] # Executes: npm run build && docker-compose up -d # View all configured macros /macros # Use [media] placeholder for media directory path cp output.png [media] ``` ``` -------------------------------- ### XtermService API Source: https://context7.com/tommertom/coderbot/llms.txt Core service for managing PTY terminal sessions programmatically. Allows creating, writing to, reading from, and closing terminal sessions. ```APIDOC ## XtermService API Core service for managing PTY terminal sessions programmatically. ```typescript import { XtermService } from './features/xterm/xterm.service.js'; import { ConfigService } from './services/config.service.js'; const configService = new ConfigService(); const xtermService = new XtermService(configService); // Create a new terminal session xtermService.createSession( userId, // Unique user identifier chatId, // Telegram chat ID (userId, chatId, data) => { // onDataCallback: Called when terminal produces output console.log(`Output for ${userId}: ${data}`); }, (userId, chatId) => { // onBufferingEndedCallback: Called when output stabilizes console.log(`Buffer stable for ${userId}`); } ); // Check if session exists if (xtermService.hasSession(userId)) { // Write command with Enter xtermService.writeToSession(userId, 'ls -la'); // Write raw characters without Enter xtermService.writeRawToSession(userId, '\x03'); // Ctrl+C // Get terminal output const output = await xtermService.getSessionOutput(userId, 500); const buffer = xtermService.getSessionOutputBuffer(userId); // Get terminal dimensions const { rows, cols } = xtermService.getSessionDimensions(userId); // Get current working directory const cwd = await xtermService.getSessionCwd(userId); // Close session xtermService.closeSession(userId); } // Get active session count const count = xtermService.getActiveSessions(); // Cleanup all sessions xtermService.cleanup(); ``` ``` -------------------------------- ### ProcessManager API Source: https://context7.com/tommertom/coderbot/llms.txt Service for managing multiple bot worker processes with health monitoring. ```APIDOC ## ProcessManager API Service for managing multiple bot worker processes with health monitoring. ### Methods - `startBot(botId, token)`: Starts a bot worker with the given ID and token. - `stopBot(botId)`: Stops a specific bot worker. - `restartBot(botId)`: Restarts a specific bot worker. - `startAllBots()`: Starts all stopped bot workers. - `stopAllBots()`: Stops all running bot workers. - `restartAllBots()`: Restarts all bot workers. - `isBotRunning(botId)`: Checks if a bot worker is running. - `getBotStatus(botId)`: Gets the status of a specific bot worker. - `getAllBotStatuses()`: Gets the statuses of all bot workers. - `getBotLogs(botId, lines)`: Retrieves the logs for a specific bot worker. - `performHealthCheck(botId)`: Performs a health check for a specific bot worker. ### BotProcessInfo Structure - `botId` (string): The unique identifier for the bot. - `status` (string): The current status of the bot ('running', 'stopped', 'starting', 'stopping', 'error'). - `pid` (number | undefined): The process ID of the bot. - `uptime` (number): The uptime of the bot in seconds. - `fullName` (string | undefined): The full name of the bot. - `username` (string | undefined): The username of the bot. - `lastError` (string | undefined): The last error message encountered by the bot. ``` -------------------------------- ### Implement Service with Dependency Injection in TypeScript Source: https://github.com/tommertom/coderbot/blob/main/AGENTS.md Utilize the Service Layer pattern with constructor injection for managing dependencies. This promotes modularity and testability. ```typescript // Service with dependency injection export class XtermService { constructor( private configService: ConfigService, private eventEmitter: EventEmitter ) {} } ``` -------------------------------- ### Configure Terminal Output Lines Source: https://github.com/tommertom/coderbot/blob/main/README.md Set XTERM_MAX_OUTPUT_LINES to configure the maximum number of output lines to retain in the terminal buffer. Defaults to 1000. ```env # Terminal Configuration (Optional) # Maximum output lines to keep in buffer (default: 1000) XTERM_MAX_OUTPUT_LINES=1000 ``` -------------------------------- ### Send Ctrl+Character Combinations with Coderbot Source: https://github.com/tommertom/coderbot/blob/main/README.md Send any Ctrl+character combination using the /ctrl command. Specific shortcuts for Ctrl+C and Ctrl+X are also available. ```text /ctrl - Send any Ctrl+character combination (e.g., /ctrl c for Ctrl+C) ``` ```text /ctrlc - Send Ctrl+C (interrupt) - shortcut ``` ```text /ctrlx - Send Ctrl+X - shortcut ``` -------------------------------- ### Create Service Container using Factory Pattern in TypeScript Source: https://github.com/tommertom/coderbot/blob/main/AGENTS.md Employ the Factory Pattern for complex object creation, such as instantiating a service container with its dependencies. This abstracts the creation process. ```typescript // Factory pattern for service creation export class ServiceContainerFactory { static create(): ServiceContainer { const config = new ConfigService(); return { configService: config, xtermService: new XtermService(config), // ... other services }; } } ``` -------------------------------- ### XtermRendererService API Source: https://context7.com/tommertom/coderbot/llms.txt Service for rendering terminal output to PNG images using Puppeteer. Allows initializing the browser, rendering output to an image buffer, and cleaning up resources. ```APIDOC ## XtermRendererService API Service for rendering terminal output to PNG images using Puppeteer. ```typescript import { XtermRendererService } from './features/xterm/xterm-renderer.service.js'; import { ConfigService } from './services/config.service.js'; const configService = new ConfigService(); const renderer = new XtermRendererService(configService); // Initialize browser (called automatically on first render) await renderer.initialize(); // Render terminal output to PNG image const outputBuffer = ['$ ls -la\n', 'total 32\n', 'drwxr-xr-x 5 user user 4096 ...\n']; const rows = 50; const cols = 100; const imageBuffer = await renderer.renderToImage(outputBuffer, rows, cols); // Use imageBuffer (Buffer) to send as photo via Telegram // await ctx.replyWithPhoto(new InputFile(imageBuffer)); // Cleanup browser resources await renderer.cleanup(); ``` ``` -------------------------------- ### Custom Coder Management Source: https://context7.com/tommertom/coderbot/llms.txt Commands for managing custom coders within the bot. ```APIDOC ## Remove a custom coder /removecoder mycoder ``` -------------------------------- ### AI Assistant Menu Navigation Source: https://github.com/tommertom/coderbot/blob/main/README.md Use number keys to make selections within the AI assistant's menus. ```text /1 /2 /3 /4 /5 - Send number keys (for AI assistant menu selections) ``` -------------------------------- ### Enable Auto-Kill Security Feature Source: https://github.com/tommertom/coderbot/blob/main/README.md Set AUTO_KILL to true to enable immediate bot shutdown upon unauthorized access attempts. This is recommended for production environments to prevent security breaches. ```env AUTO_KILL=true # Enable auto-kill (recommended for production) ``` -------------------------------- ### Troubleshooting: Control Characters Source: https://github.com/tommertom/coderbot/blob/main/README.md If control characters like Ctrl+C are not working, ensure an active session and try dedicated shortcuts like /ctrlc. If the terminal is unresponsive, try /ctrlc followed by /screen, or close and restart the session. ```bash /ctrlc /screen ``` -------------------------------- ### Send Commands to Terminal Session Source: https://context7.com/tommertom/coderbot/llms.txt Interact with the active terminal session by sending commands and text. Use direct messages for commands with Enter, dot prefix for quick commands, or specific commands for text input. ```bash # Send text message directly (with Enter) # Just type any message not starting with / npm install express # Quick command with dot prefix (dot removed, Enter added) .git status .ls -la .docker-compose up -d # Send text without Enter /keys partial_text # Send specific command /send echo "Hello World" ``` -------------------------------- ### Define Bot Messages Constants in TypeScript Source: https://github.com/tommertom/coderbot/blob/main/AGENTS.md Centralize bot-related messages in a constants file for maintainability. Use descriptive constant names and group related messages. ```typescript // src/constants/messages.ts export const BOT_MESSAGES = { SESSION_STARTED: '✅ Session started successfully', SESSION_CLOSED: '🔒 Session closed', UNAUTHORIZED: '❌ Access denied. Your user ID is not authorized.', COMMAND_NOT_FOUND: '❓ Unknown command. Type /help for available commands.' } as const; ```