Skip to content

feat: Enhanced channels + bot gateway + wiki + system prompt integration#565

Closed
FluxLuFFy wants to merge 18 commits intoGitlawb:mainfrom
FluxLuFFy:enhanced-combined
Closed

feat: Enhanced channels + bot gateway + wiki + system prompt integration#565
FluxLuFFy wants to merge 18 commits intoGitlawb:mainfrom
FluxLuFFy:enhanced-combined

Conversation

@FluxLuFFy
Copy link
Copy Markdown
Contributor

Summary

Combines and improves upon PR #524 (MCP channel unlocking) and PR #551 (bot gateway) into a single, production-ready branch. Also adds a Wiki system, BotManager agent tool, and integrates all new features into the AI system prompt.

What's included

🔧 Bug fixes (from PR #524 + new)

  • Circular permission relay fix — prevents permission relay back to the tool-owning server
  • REPL queue wakeup — channel messages now properly wake the headless queue
  • Trust boundary narrowing — auto-allow only applies to official non-dev plugin entries, only for the reply tool
  • Dev gate restoration — server-kind entries still require --dangerously-load-development-channels
  • Bun.sleepsetTimeout — portable across runtimes
  • Duplicate handler flag_messageHandlerWired prevents double-subscribing
  • Health EADDRINUSE — graceful fallback when health port is in use
  • BotTool error handling — clear message when gateway not running
  • Discord chunkMessage — handles empty string edge case
  • Channel save() try/catch — write errors no longer crash

✨ New features

MCP Channel System (improved from PR #524)

  • Hardcoded channel allowlist — replaces GrowthBook dependency
  • Auto-allow rules — channel reply tool auto-allowed without per-tool prompts
  • Permission relay over channels — users approve/deny via yes/no <id> in Telegram/Discord
  • Queue wakeup — headless mode auto-runs on channel message arrival
  • 17 focused tests

Bot Gateway (from PR #551 + improvements)

  • 24/7 Telegram bot via grammY (polling + webhook)
  • 24/7 Discord bot via discord.js v14
  • Per-user rate limiting, metrics tracking
  • Health endpoints /health + /healthz
  • Channel Manager with JSON persistence
  • Bot-to-MCP Bridge
  • Docker, PM2, systemd deployment

BotManager Agent Tool — programmatic bot management from the agent

Wiki System/wiki init|status|ingest for project knowledge base in .openclaude/wiki/

System Prompt Integration — agent now knows about wiki, bots, channels from first interaction

Reviewers

cc @kali113 @kevincodex1 @Vasanthdev2004 @gnanam1990

Dhiraj Lochib and others added 18 commits April 8, 2026 23:04
…Gitlawb#378)

Ungate the full channel notification system so OpenClaude users can
receive and reply to messages from Telegram, Discord, iMessage, and
other MCP channel plugins -- all inside the terminal.

Previously, channels were fully implemented but blocked by four cloud-
dependent gates: GrowthBook feature flags, OAuth-only auth, org policy
(Teams/Enterprise channelsEnabled), and a GrowthBook-sourced plugin
allowlist. None of these work for OpenClaude users.

Changes by area:

Feature gates (build-time):
- Replace 18 feature('KAIROS')/feature('KAIROS_CHANNELS') guards with
  true so Bun DCE keeps channel code in the build
- Replace feature('KAIROS_PERMISSIONS') with true for permission relay

Runtime gates (channelNotification.ts):
- Remove OAuth requirement (getClaudeAIOAuthTokens)
- Remove Teams/Enterprise org policy check (channelsEnabled)
- Simplify allowlist to hardcoded approved plugins (telegram, discord,
  imessage, fakechat) instead of GrowthBook tengu_harbor_ledger
- Allow server-kind --channels entries (previously always rejected)

Auto-registration (channelNotification.ts):
- Allowlisted plugins auto-register when they connect -- no --channels
  flag needed for approved channel plugins
- gateChannelServer() checks pluginSource against the hardcoded
  allowlist and calls setAllowedChannels() to add a session entry

Auto-permission (useManageMCPConnections.ts, print.ts):
- When a channel server registers, auto-add a session-level allow rule
  for all tools from that server (e.g. mcp__plugin_telegram_telegram)
- Eliminates per-tool permission prompts for channel reply tools
- Applied in both interactive (REPL) and headless (SDK/print) modes,
  including reconnect paths

Headless queue wakeup (print.ts):
- subscribeToCommandQueue now calls run() when the model is idle and
  channel messages (priority 'next') are in the queue
- Previously only handled 'now' priority interrupts

Channel allowlist (channelAllowlist.ts):
- isChannelsEnabled() returns true (no GrowthBook dependency)
- isChannelPermissionRelayEnabled() returns true
- getChannelAllowlist() returns hardcoded list of approved plugins

Other fixes:
- Fix OAuth gate bug in interactiveHelpers.tsx
- Update ChannelsNotice.tsx for auto-registration flow

Documentation:
- Add Channels section to README.md with quick start guide

Closes Gitlawb#378
…mments

- Narrow channel tool auto-allow to only reply/send tools for official
  non-dev plugin entries (useManageMCPConnections.ts, print.ts)
- Restore --dangerously-load-development-channels requirement for
  server-kind channel entries (channelNotification.ts)
- Update --channels help text to document plugin:/server: format (main.tsx)
- Remove unused checkGate_CACHED_OR_BLOCKING import (interactiveHelpers.tsx)
- Fix stale comments in interactiveHelpers.tsx and LogoV2.tsx
Tests (42 passing, 73 assertions):

channelNotification.test.ts — gateChannelServer() trust boundary:
  - approved plugin: registration, auto-registration, idempotency
  - non-allowlisted plugin: skip, no auto-register, dev bypass
  - marketplace verification: mismatch rejection, @-less rejection
  - server-kind: reject without dev flag, allow with dev flag
  - capability/runtime checks: missing capability, disabled feature
  - findChannelEntry: plugin-kind vs server-kind matching

channelAutoAllow.test.ts — permission auto-allow:
  - only reply/send tools for official non-dev plugins
  - dev entries get no auto-allow rules
  - server-kind entries get no auto-allow rules
  - no broader server-level rule (only specific tools)
  - merge idempotency (repeated reconnects don't widen permissions)
  - multiple servers get distinct non-overlapping rules

channelQueueWakeup.test.ts — headless queue wakeup:
  - enqueue triggers subscriber callback
  - idle → run wakeup pattern (print.ts headless loop)
  - already-running guard prevents double-run
  - unsubscribe prevents stale callbacks

Refactoring:
  - Extract computeChannelAutoAllowRules() and mergeAutoAllowRules()
    into channelAutoAllow.ts (pure, testable helper)
  - useManageMCPConnections.ts and print.ts now use the shared helper
  - Fix stale GrowthBook comment in main.tsx channel parsing
1. Remove auto-registration: gateChannelServer() no longer calls
   setAllowedChannels(). All plugins now require explicit --channels
   opt-in. Reviewers: gnanam1990, Vasanthdev2004.

2. Narrow auto-allow to reply only: computeChannelAutoAllowRules()
   returns only the reply tool rule. The broader send tool (proactive
   outbound) goes through the normal permission prompt.

3. Re-gate permission relay: isChannelPermissionRelayEnabled() now
   delegates to isChannelsEnabled() instead of returning hardcoded true.
   interactiveHandler.ts and useCanUseTool.tsx use the gate function
   instead of 'true /* channels enabled */'.

4. Fix headless channel_enable for server-kind entries: print.ts
   handleChannelEnable now checks getAllowedChannels() for an existing
   server-kind entry instead of rejecting all non-plugin servers.

5. Fix Gemini extra_content bug: normalizeMessagesForAPI() now preserves
   extra_content on tool_use blocks (carries thought_signature needed
   for subsequent Gemini API turns).

Tests updated: 41 pass, 0 fail across 3 test suites.
1. Call recheckCommandQueue() after queryGuard.end() in REPL.tsx so
   channel messages that arrived during a running query get processed.
   Ink's React reconciler can coalesce the guard→idle and snapshot
   state changes, causing useQueueProcessor's useEffect to miss the
   wakeup. recheckCommandQueue() bumps the snapshot reference.

2. Surface a visible toast when a channel-capable server connects but
   is not in the --channels list (session-kind gate skip). Previously
   this was debug-only, making it invisible why messages were dropped.
When a tool from server X needs permission approval, don't relay the
prompt back to server X itself. This prevents a loop where approving
via Telegram triggers the skill, which hits another permission check,
which gets relayed back to Telegram, ad infinitum.

Filter by comparing ctx.tool.mcpInfo.serverName against the channel
client name — the owning server is excluded from relay recipients.
- Base adapter with auto-reconnect (exponential backoff + jitter)
- Telegram adapter (grammY, polling + webhook modes)
- Discord adapter (discord.js v14, mention/DM handling, message chunking)
- Bot gateway manager with 24/7 lifecycle + health endpoints
- Channel manager with runtime add/remove, JSON persistence, Zod validation
- Message bus for cross-platform routing
- CLI commands: /bots [start|stop|status|restart], /channels [list|add|remove|enable|disable]
- Docker + docker-compose + PM2 + systemd deployment configs
- Adapted from hustcc/nano-claw (MIT License)

New packages: grammy, discord.js
- Agent loop architecture diagram
- How messages flow from Discord/Telegram to OpenClaude coordinator
- Step-by-step setup for Telegram BotFather + Discord Developer Portal
- All 5 deployment methods (CLI, standalone, Docker, PM2, systemd)
- Per-channel agent customization (system prompts, allowed tools)
- Health endpoint response examples
- Troubleshooting guide
- How to add new platforms (Slack, WhatsApp, etc.)
Tests cover:
- BaseAdapter: init, connect, uptime, messages, errors, auth, send, failures (10)
- MessageBus: platform routing, global handlers, unsubscribe, error handling, events (9)
- ChannelManager: CRUD, persistence, filtering, events, enable/disable (14)
- BotGateway: config, dynamic adapters, routing, send, shutdown (7)
- HealthReport: status, uptime formatting, degraded detection (5)

Also fixes:
- onMessage handler now wires to bus immediately (not just in start24_7)
The AI agent can now directly interact with the bot gateway:
- Check gateway status and adapter health
- List/add/remove/enable/disable channels
- Send messages through Telegram or Discord
- View uptime, reconnect counts, errors

Files:
- src/tools/BotTool/BotTool.ts — Tool implementation (buildTool, Zod schemas)
- src/tools/BotTool/prompt.ts — Agent-facing description + usage docs
- src/tools/BotTool/UI.tsx — Tool use rendering (messages, summaries)
- src/tools.ts — Registered BotTool in tools array
Added 13 new tests for BotTool:
- Tool name export, description content
- Render messages for all actions (status, channels, send)
- Summary generation for each action type
- Success/error result rendering
- Input schema validation
- Error handling for unknown actions, missing params

Total: 58 tests, 0 failures
…awb#551 + improvements)

Combined the best of both PRs with significant improvements:

Channel Unlocking (from PR Gitlawb#524):
- Removed GrowthBook, OAuth, org policy gates
- Hardcoded allowlist for official plugins
- Auto-permission relay for channel reply tools
- Headless queue wakeup for channel messages

Bot Gateway (from PR Gitlawb#551 + enhancements):
- Rate limiting per adapter (new)
- Metrics tracking: messages, errors, rate limited (new)
- BotMcpBridge for MCP ↔ bot routing (new)
- Health endpoint with full metrics (enhanced)
- Fixed Bun.sleep → setTimeout for portability
- Fixed duplicate onMessage handler registration
- Fixed health server EADDRINUSE graceful fallback
- Fixed BotTool error handling for missing gateway
- Fixed Discord chunkMessage empty string edge case
- Fixed channel-manager save() error handling
- Split monolithic test file into 7+ granular test files
- Enhanced Docker with proper labels and healthcheck
- Comprehensive README.md
- Added getOpenClaudeEnhancedFeaturesSection() to system prompt
- Documents Wiki System (/wiki init/status/ingest) for project knowledge base
- Documents Bot Gateway (/bots start/stop/status/restart) for 24/7 Telegram+Discord
- Documents Channel Management (/channels list/add/remove/enable/disable)
- Documents BotManager agent tool for programmatic bot control
- Documents MCP Channel System (auto-allow, permission relay, channel tags)
- Section placed between output efficiency and dynamic boundary (static/cacheable)
@FluxLuFFy
Copy link
Copy Markdown
Contributor Author

Requesting review — would appreciate feedback on channel trust boundaries, bot adapter error handling, and system prompt section placement.

cc @kali113 @kevincodex1 @Vasanthdev2004 @gnanam1990

@FluxLuFFy FluxLuFFy closed this Apr 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants