{"id":50194614,"url":"https://github.com/ipnet-mesh/meshbot","last_synced_at":"2026-05-25T16:33:55.609Z","repository":{"id":325723665,"uuid":"1101518235","full_name":"ipnet-mesh/meshbot","owner":"ipnet-mesh","description":"Agentic AI Bot for MeshCore Mesh Networks","archived":false,"fork":false,"pushed_at":"2025-11-23T02:19:55.000Z","size":329,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-11-23T02:25:37.453Z","etag":null,"topics":["agentic","ai","bot","claude-code","meshcore"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ipnet-mesh.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null}},"created_at":"2025-11-21T19:40:54.000Z","updated_at":"2025-11-23T02:04:31.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/ipnet-mesh/meshbot","commit_stats":null,"previous_names":["ipnet-mesh/meshbot"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/ipnet-mesh/meshbot","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ipnet-mesh%2Fmeshbot","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ipnet-mesh%2Fmeshbot/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ipnet-mesh%2Fmeshbot/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ipnet-mesh%2Fmeshbot/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ipnet-mesh","download_url":"https://codeload.github.com/ipnet-mesh/meshbot/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ipnet-mesh%2Fmeshbot/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33484096,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-25T14:31:05.219Z","status":"ssl_error","status_checked_at":"2026-05-25T14:31:02.878Z","response_time":57,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agentic","ai","bot","claude-code","meshcore"],"created_at":"2026-05-25T16:33:54.774Z","updated_at":"2026-05-25T16:33:55.563Z","avatar_url":"https://github.com/ipnet-mesh.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# MeshBot - AI Agent for MeshCore Network\n\nMeshBot is an intelligent AI agent that communicates through the MeshCore network using Pydantic AI as its framework. It maintains conversation history with users through simple text file logs and handles both direct messages and channel communications with automatic message length management for MeshCore's constraints.\n\n## 🐳 Quick Start with Docker (Recommended)\n\nThe easiest way to run MeshBot is using our Docker image:\n\n```bash\n# Pull the latest image\ndocker pull ghcr.io/ipnet-mesh/meshbot:latest\n\n# Run with mock connection (for testing)\ndocker run -it --rm \\\n  -e LLM_API_KEY=your_api_key_here \\\n  -e LLM_MODEL=openai:gpt-4o-mini \\\n  -e MESHCORE_CONNECTION_TYPE=mock \\\n  ghcr.io/ipnet-mesh/meshbot:latest\n\n# Run with serial connection (real hardware)\ndocker run -it --rm \\\n  --device=/dev/ttyUSB0 \\\n  -v $(pwd)/logs:/app/logs \\\n  -e LLM_API_KEY=your_api_key_here \\\n  -e LLM_MODEL=openai:gpt-4o-mini \\\n  -e MESHCORE_CONNECTION_TYPE=serial \\\n  -e MESHCORE_PORT=/dev/ttyUSB0 \\\n  ghcr.io/ipnet-mesh/meshbot:latest\n\n# Run with custom configuration via .env file\ndocker run -it --rm \\\n  --env-file .env \\\n  -v $(pwd)/logs:/app/logs \\\n  ghcr.io/ipnet-mesh/meshbot:latest\n```\n\n### Docker Environment Variables\n\nAll configuration is done via environment variables (see full list in [Configuration](#configuration)):\n\n```bash\n# Required\nLLM_API_KEY=your_api_key_here\nLLM_MODEL=openai:gpt-4o-mini\n\n# MeshCore Connection\nMESHCORE_CONNECTION_TYPE=mock  # or serial, tcp, ble\nMESHCORE_PORT=/dev/ttyUSB0     # for serial\n# MESHCORE_HOST=192.168.1.100  # for TCP\n\n# Optional\nLISTEN_CHANNEL=0\nMAX_MESSAGE_LENGTH=120\nLOG_LEVEL=INFO\n```\n\n### Docker Volumes\n\nMount volumes to persist logs and use custom prompts:\n\n```bash\ndocker run -it --rm \\\n  -v $(pwd)/logs:/app/logs \\\n  -v $(pwd)/my_prompt.txt:/app/custom_prompt.txt \\\n  -e CUSTOM_PROMPT_FILE=/app/custom_prompt.txt \\\n  --env-file .env \\\n  ghcr.io/ipnet-mesh/meshbot:latest\n```\n\n## Features\n\n- **🤖 AI-Powered**: Built with Pydantic AI for structured, type-safe agent development\n- **📡 MeshCore Integration**: Communicates via MeshCore network (serial, TCP, BLE, or mock)\n- **🧠 Simple Memory System**: Text file-based chat logs (1000 lines per conversation)\n- **💬 Smart Messaging**: Automatic message splitting with length limits (configurable, default 120 chars)\n- **🔧 Rich Tool System**: Utility tools (calculator, time, bot status) and fun tools (dice, coin, 8-ball, random numbers)\n- **🌐 Network Awareness**: Real-time tracking of mesh network events (adverts, contacts, paths, status)\n- **👥 Contact Tracking**: Automatic node name discovery and mapping from mesh advertisements\n- **📊 Situational Context**: Network events and node names included in LLM context for awareness\n- **💰 Cost Control**: API request limits (max 5 per message) to prevent excessive LLM usage\n- **⚙️ Configurable**: Flexible configuration via files and environment variables\n- **🎯 Message Routing**: Intelligent DM and channel message handling with @NodeName mentions\n- **🔌 OpenAI-Compatible**: Works with any OpenAI-compatible endpoint (OpenAI, Groq, Ollama, etc.)\n\n## Alternative: Install from Source\n\nFor development or if you prefer not to use Docker:\n\n### Installation\n\n```bash\n# Clone the repository\ngit clone https://github.com/ipnet-mesh/meshbot.git\ncd meshbot\n\n# Create virtual environment\npython -m venv .venv\nsource .venv/bin/activate  # On Windows: .venv\\Scripts\\activate\n\n# Install in development mode\npip install -e \".[dev]\"\n```\n\n### Basic Usage\n\n```bash\n# Run with mock connection (for testing)\nmeshbot test --meshcore-connection-type mock\n\n# Run with serial connection\nmeshbot --meshcore-connection-type serial --meshcore-port /dev/ttyUSB0\n\n# Run with custom prompt file\nmeshbot --custom-prompt my_prompt.txt --meshcore-connection-type mock\n```\n\n### Environment Variables\n\nCreate a `.env` file:\n\n```bash\n# LLM Configuration (OpenAI-compatible)\nLLM_MODEL=openai:gpt-4o-mini\nLLM_API_KEY=your_api_key_here\n# LLM_BASE_URL=http://localhost:11434/v1  # For Ollama or other endpoints\n\n# Bot Behavior\nLISTEN_CHANNEL=0                # Channel to monitor\nMAX_MESSAGE_LENGTH=120          # MeshCore message length limit\n# MESHCORE_NODE_NAME=MeshBot    # Bot will respond to @MeshBot mentions\n\n# MeshCore Configuration\nMESHCORE_CONNECTION_TYPE=mock\n# MESHCORE_PORT=/dev/ttyUSB0\n# MESHCORE_HOST=192.168.1.100\n# MESHCORE_BAUDRATE=115200\n\n# Logging\nLOG_LEVEL=INFO\n```\n\n### Using a Custom Prompt File\n\nCreate a custom prompt file (e.g., `my_prompt.txt`):\n\n```\nYou are a helpful assistant for the mesh network.\nYou specialize in network troubleshooting and device management.\nAlways be concise and technical in your responses.\n```\n\nRun with the custom prompt:\n\n```bash\n# Via command line\nmeshbot --custom-prompt my_prompt.txt --meshcore-connection-type mock\n\n# Via environment variable\nexport CUSTOM_PROMPT_FILE=my_prompt.txt\nmeshbot\n```\n\n## Architecture\n\n### Core Components\n\n1. **MeshCore Interface** (`meshcore_interface.py`)\n   - Abstract interface for MeshCore communication\n   - Mock implementation for testing\n   - Real implementation using meshcore library\n   - Auto clock sync and local advertisement on startup\n   - Network event tracking (advertisements, contacts, paths, status)\n   - Automatic node name discovery and mapping\n\n2. **Memory Manager** (`memory.py`)\n   - Simple text file-based chat logs\n   - Separate logs for DMs and channels\n   - Network event logs with timestamps\n   - Node name mapping storage\n   - Automatic trimming to configured limits\n   - Format: `timestamp|role|content`\n\n3. **AI Agent** (`agent.py`)\n   - Pydantic AI agent with rich tool set\n   - Utility tools (calculate, time, bot status)\n   - Fun tools (dice, coin, random numbers, magic 8-ball)\n   - Network/mesh tools (contact management, conversation history, node queries)\n   - Structured responses with message splitting\n   - API request limits (max 5 per message)\n   - Network context injection for situational awareness\n   - Dependency injection\n\n4. **Configuration** (`config.py`)\n   - Environment-based configuration\n   - Command-line argument overrides\n   - Validation\n\n### Message Handling\n\n#### Direct Messages (DMs)\n- Bot **always** responds to direct messages\n- Each user gets a separate conversation log in `logs/dm_{user_id}.txt`\n\n#### Channel Messages\n- Bot only responds when mentioned by node name (e.g., `@MeshBot`)\n- Only monitors the configured listen channel (default: channel 0)\n- Shared conversation log in `logs/channel.txt`\n- Node name is set via `MESHCORE_NODE_NAME` environment variable\n\nExample:\n```\nUser: @MeshBot what's the weather?  → Bot responds\nUser: hello everyone                → Bot ignores (not mentioned)\n```\n\n#### Message Length Limits\n\nMeshCore has character limits (default 120). MeshBot automatically:\n- Splits long responses into multiple messages\n- Breaks on word boundaries (never mid-word)\n- Adds `(1/3)`, `(2/3)`, `(3/3)` indicators\n- Adds 0.5s delay between chunks\n\nExample:\n```\nLong response: \"This is a very long message that exceeds the maximum allowed length...\"\n\nSent as:\n\"This is a very long message that exceeds the (1/2)\"\n\"maximum allowed length... (2/2)\"\n```\n\n## Usage Examples\n\n### Testing Mode\n\n```bash\n# Interactive testing with mock MeshCore\nmeshbot test --meshcore-connection-type mock\n\n# The test command provides an interactive prompt:\n# Enter messages to send (or 'quit' to exit)\n# \u003e Hello!\n```\n\n### Programmatic Usage\n\n```python\nimport asyncio\nfrom meshbot import MeshBotAgent\nfrom pathlib import Path\n\nasync def main():\n    # Create agent with custom prompt\n    with open(\"my_prompt.txt\") as f:\n        custom_prompt = f.read()\n\n    agent = MeshBotAgent(\n        model=\"openai:gpt-4o-mini\",\n        meshcore_connection_type=\"mock\",\n        node_name=\"Assistant\",  # Bot will respond to @Assistant mentions\n        listen_channel=\"0\",\n        max_message_length=120,\n        custom_prompt=custom_prompt\n    )\n\n    # Initialize and start\n    await agent.initialize()\n    await agent.start()\n\n    # Send a message\n    success = await agent.send_message(\"node1\", \"Hello!\")\n\n    # Keep running\n    await asyncio.sleep(60)\n\n    # Stop\n    await agent.stop()\n\nasyncio.run(main())\n```\n\n## Configuration\n\n### LLM Providers\n\nMeshBot works with any OpenAI-compatible API:\n\n#### OpenAI\n```bash\nLLM_MODEL=openai:gpt-4o-mini\nLLM_API_KEY=sk-...\n```\n\n#### Groq\n```bash\nLLM_MODEL=openai:llama-3.1-70b-versatile\nLLM_API_KEY=gsk_...\nLLM_BASE_URL=https://api.groq.com/openai/v1\n```\n\n#### Ollama (local)\n```bash\nLLM_MODEL=openai:llama2\nLLM_BASE_URL=http://localhost:11434/v1\n# No API key needed for local Ollama\n```\n\n### Message Behavior\n\n```bash\n# Node name - bot responds to @NodeName mentions in channels\nMESHCORE_NODE_NAME=MeshBot\n\n# Channel settings\nLISTEN_CHANNEL=0              # Which channel to monitor\n\n# Message length\nMAX_MESSAGE_LENGTH=120        # Character limit per message chunk\n\n# LoRa duty cycle compliance (prevents message loss)\nMESHCORE_MESSAGE_DELAY=5.0    # Delay between message chunks (seconds)\nMESHCORE_MESSAGE_RETRY=1      # Number of retry attempts for failed sends\n```\n\n**Note**: The `MESHCORE_MESSAGE_DELAY` setting is critical for reliable message delivery over LoRa. LoRa radios have duty cycle restrictions (e.g., 1% in Europe requires ~50 seconds of wait time after a 500ms transmission). The default 5.0 second delay provides a safe balance between speed and reliability. Reduce to 2-3 seconds for less restrictive regions (US), or increase to 7-10 seconds for very strict requirements.\n\n## Chat Logs\n\nConversation history and network data are stored in simple text files:\n\n```\nlogs/\n├── channel.txt              # Channel conversation (all users)\n├── dm_2369759a4926.txt     # Direct message with specific user\n├── network_events.txt       # Network events (adverts, contacts, paths, status)\n└── node_names.txt          # Node name mappings (pubkey -\u003e friendly name)\n```\n\n### Conversation Log Format\n```\n1734567890.123|user|Hello, how are you?\n1734567891.456|assistant|I'm doing well, thanks!\n```\n\n### Network Events Log Format\n```\n1734567890.123|ADVERT from 2369759a49261ac6 (NodeName)\n1734567891.456|NEW_CONTACT 4a5b6c7d8e9f0123 (OtherNode)\n1734567892.789|STATUS from 2369759a49261ac6 (NodeName)\n```\n\n### Node Names Mapping Format\n```\n2369759a49261ac6|NodeName|1734567890.123\n4a5b6c7d8e9f0123|OtherNode|1734567891.456\n```\n\nLogs automatically:\n- Trim to configured limits when exceeded (1000 for conversations, 100 for network events)\n- Persist across restarts\n- Include timestamps for all entries\n- Network events and node names are included in LLM context for situational awareness\n- Can be viewed/edited as plain text files\n\n## AI Tools\n\nThe agent has access to three categories of built-in tools:\n\n### Utility Tools\n- **Calculate**: Perform mathematical calculations (e.g., \"calculate 25 * 4 + 10\")\n- **Get Current Time**: Get the current date and time\n- **Get Bot Status**: Check bot uptime and connection status\n\n### Fun Tools\n- **Roll Dice**: Roll dice with custom sides (e.g., \"roll 2d6\", \"roll 1d20\")\n- **Flip Coin**: Flip a coin (heads or tails)\n- **Random Number**: Generate random numbers in a range\n- **Magic 8-Ball**: Ask the magic 8-ball for wisdom\n\n### Network/Mesh Tools\n- **Get Contacts**: List available MeshCore contacts with their names\n- **Get Channel Messages**: Retrieve recent messages from a channel\n- **Get User Messages**: Access recent private messages with a user\n- **Get Node Info**: Get detailed information about a specific mesh node\n- **List Nodes**: List all known nodes with optional filters\n- **List Adverts**: Search advertisement history with filters\n\n### Network Awareness\nThe agent automatically receives context about:\n- **Recent Network Events**: Last 5 network events (adverts, new contacts, status responses)\n- **Node Names**: Friendly names for all discovered nodes\n- **Network Activity**: Timing and frequency of mesh network activity\n\nWhen users ask questions, the agent can automatically use these tools and has awareness of the mesh network state.\n\n## Development\n\n### Project Structure\n\n```\nmeshbot/\n├── src/meshbot/\n│   ├── __init__.py\n│   ├── agent.py              # Main AI agent with message splitting\n│   ├── meshcore_interface.py  # MeshCore communication\n│   ├── memory.py             # Text file-based chat logs\n│   ├── config.py            # Configuration management\n│   └── main.py             # CLI entry point\n├── logs/                     # Chat log files (auto-created)\n├── tests/                   # Test suite\n├── examples/               # Usage examples\n├── CLAUDE.md / AGENTS.md   # Development guidelines\n└── pyproject.toml          # Project configuration\n```\n\n### Running Tests\n\n```bash\n# Install development dependencies\npip install -e \".[dev]\"\n\n# Run tests\npytest\n\n# Run with coverage\npytest --cov=meshbot --cov-report=html\n```\n\n### Code Quality\n\nSee `AGENTS.md` for full development workflow including:\n- Pre-commit hooks (black, isort, mypy, flake8, bandit)\n- Virtual environment setup\n- Testing guidelines\n\n## Production Deployment\n\n### Docker Deployment (Recommended)\n\nThe recommended way to deploy MeshBot in production is using Docker:\n\n#### Using Docker Compose\n\nCreate a `docker-compose.yml`:\n\n```yaml\nversion: '3.8'\n\nservices:\n  meshbot:\n    image: ghcr.io/ipnet-mesh/meshbot:latest\n    container_name: meshbot\n    restart: unless-stopped\n    devices:\n      - /dev/ttyUSB0:/dev/ttyUSB0  # For serial connection\n    volumes:\n      - ./logs:/app/logs\n      - ./custom_prompt.txt:/app/custom_prompt.txt:ro  # Optional\n    environment:\n      - LLM_MODEL=openai:gpt-4o-mini\n      - LLM_API_KEY=${LLM_API_KEY}\n      - MESHCORE_NODE_NAME=MeshBot\n      - MESHCORE_CONNECTION_TYPE=serial\n      - MESHCORE_PORT=/dev/ttyUSB0\n      - MAX_MESSAGE_LENGTH=120\n      - LOG_LEVEL=INFO\n    # Optionally use env_file instead:\n    # env_file:\n    #   - .env\n```\n\nRun with:\n```bash\n# Create .env file with your secrets\necho \"LLM_API_KEY=your_key_here\" \u003e .env\n\n# Start the service\ndocker-compose up -d\n\n# View logs\ndocker-compose logs -f\n\n# Stop the service\ndocker-compose down\n```\n\n### Alternative: Direct Installation\n\nFor production use with real MeshCore hardware without Docker:\n\n```bash\n# Serial connection\nmeshbot --meshcore-connection-type serial --meshcore-port /dev/ttyUSB0\n\n# TCP connection\nmeshbot --meshcore-connection-type tcp --meshcore-host 192.168.1.100\n\n# BLE connection\nmeshbot --meshcore-connection-type ble --meshcore-address XX:XX:XX:XX:XX:XX\n```\n\n### Environment Setup\n\n```bash\n# Production environment variables\nexport LLM_MODEL=openai:gpt-4o-mini\nexport LLM_API_KEY=your_production_key\nexport MESHCORE_NODE_NAME=MeshBot\nexport MESHCORE_CONNECTION_TYPE=serial\nexport MESHCORE_PORT=/dev/ttyUSB0\nexport MAX_MESSAGE_LENGTH=120\nexport LOG_LEVEL=INFO\n```\n\n## Troubleshooting\n\n### Common Issues\n\n1. **Import Errors**: Ensure virtual environment is activated and dependencies installed\n2. **MeshCore Connection**: Check port permissions (`sudo usermod -a -G dialout $USER`)\n3. **API Keys**: Set `LLM_API_KEY` environment variable\n4. **Long Messages**: Adjust `MAX_MESSAGE_LENGTH` if messages are too short/long\n5. **Channel Not Responding**: Ensure messages mention the bot's node name (e.g., `@MeshBot`)\n\n### Debug Mode\n\n```bash\n# Enable verbose logging\nmeshbot -vv --meshcore-connection-type mock\n\n# Test with specific prompt\nmeshbot test --custom-prompt debug_prompt.txt -vv --meshcore-connection-type mock\n```\n\n### Viewing Logs\n\n```bash\n# View channel conversation\ncat logs/channel.txt\n\n# View DM with specific user\ncat logs/dm_2369759a4926.txt\n\n# View network events\ncat logs/network_events.txt\n\n# View node name mappings\ncat logs/node_names.txt\n\n# Watch logs in real-time\ntail -f logs/channel.txt\ntail -f logs/network_events.txt\n\n# Monitor all activity\nwatch -n 1 'ls -lh logs/'\n```\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch\n3. Make your changes\n4. Add tests for new functionality\n5. Run pre-commit hooks: `pre-commit run --all-files`\n6. Submit a pull request\n\nSee `AGENTS.md` for detailed development guidelines.\n\n## License\n\nThis project is licensed under the GNU General Public License v3.0 - see the LICENSE file for details.\n\n## Acknowledgments\n\n- [Pydantic AI](https://ai.pydantic.dev/) - Agent framework\n- [MeshCore](https://github.com/meshcore) - Network communication library\n- [Click](https://click.palletsprojects.com/) - CLI framework\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fipnet-mesh%2Fmeshbot","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fipnet-mesh%2Fmeshbot","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fipnet-mesh%2Fmeshbot/lists"}