pi-gateway

License: MIT Bun GitHub Stars

The multi-channel AI gateway for pi coding agent. Connect your AI assistant to Telegram, Discord, Feishu, and WebChat with a single configuration.


Why pi-gateway?

Direct use of OpenClaw requires managing RPC processes, message routing, and channel integrations yourself. pi-gateway handles all the infrastructure so you can focus on building intelligent agents.

+------------------+     +------------------+     +------------------+
|                  |     |                  |     |                  |
|  Without         |     |  With            |     |  Your Benefit    |
|  pi-gateway      |     |  pi-gateway      |     |                  |
|                  |     |                  |     |                  |
+------------------+     +------------------+     +------------------+
| Manage RPC       |     |                  |     | Focus on agent   |
| processes        |     |  Automatic       |     | logic, not       |
|                  |     |  RPC Pool        |     | infrastructure   |
+------------------+     +------------------+     +------------------+
| Build message    |     |                  |     | Zero boilerplate |
| routing          |     |  Session Router  |     | for multi-user   |
|                  |     |                  |     | scenarios        |
+------------------+     +------------------+     +------------------+
| Handle channel   |     |                  |     | One config for   |
| differences      |     |  Unified API     |     | all platforms    |
|                  |     |                  |     |                  |
+------------------+     +------------------+     +------------------+
| Implement        |     |                  |     | Seamless pi      |
| from scratch     |     |  Plugin System   |     | skills support   |
|                  |     |                  |     |                  |
+------------------+     +------------------+     +------------------+

Key Differentiator: Seamless pi Skills

pi-gateway is designed for pi users. All pi skills work out of the box:

+-----------------+       +-----------------+       +-----------------+
|                 |       |                 |       |                 |
|  pi skills      |       |  pi-gateway     |       |  Result         |
|                 |       |                 |       |                 |
+-----------------+       +-----------------+       +-----------------+
| send_message    |  -->  | Auto-route to   |  -->  | Message sent    |
| send_media      |       | active channel  |       | to Telegram/    |
| session_status  |       |                 |       | Discord/WebChat |
+-----------------+       +-----------------+       +-----------------+
| cron            |  -->  | Isolated        |  -->  | Scheduled       |
|                 |       | execution       |       | tasks work      |
+-----------------+       +-----------------+       +-----------------+
| message         |  -->  | Channel-aware   |  -->  | Reactions,      |
|                 |       | adapters        |       | edits, pins     |
+-----------------+       +-----------------+       +-----------------+
| All pi skills   |  -->  | Transparent     |  -->  | Works anywhere  |
|                 |       | integration     |       | pi runs         |
+-----------------+       +-----------------+       +-----------------+

Architecture

+-------------------------------------------------------------------------+
|                           pi-gateway                                    |
|                                                                         |
|  Telegram ----+                                                         |
|               |     +------------+     +-------------+     +-------+    |
|  Discord ------+--> |  Plugin    | --> |  Session    | --> |  RPC  |    |
|               |     |  System    |     |  Router     |     |  Pool |    |
|  Feishu ------+     +------------+     +-------------+     +-------+    |
|               |           |                  |                |        |
|  WebChat -----+      Hooks/Tools       Message Queue    pi --mode rpc  |
|                           |                  |                |        |
|                     +-----+-----+            |           +----+----+   |
|                     |           |            |           |         |   |
|                  Auth       Transform    Backpressure   JSON     stdin  |
|                                          Handling       Lines    stdout |
|                                                                         |
+-------------------------------------------------------------------------+
                                    |
                                    v
                            +--------------+
                            |              |
                            |  pi agent    |
                            |  + skills    |
                            |              |
                            +--------------+
Component Purpose
Plugin System 14 hooks, 8 registration APIs. Extend without modifying core.
Session Router Route to isolated agent instances: agent:{id}:{channel}:{chat}
Message Queue Serialize per-session messages, prevent interleaving
RPC Pool Manage subprocess pool with crash recovery and auto-scaling

Features

Multi-Channel: Telegram, Discord, Feishu (Lark), WebChat

RPC Pool: Isolated subprocess per session with configurable min/max/idle

Session Isolation: Deterministic routing for per-user/group contexts

Message Queue: Priority queue with backpressure handling

Model Failover: Automatic fallback chain with exponential backoff

Cron Engine: Scheduled tasks with isolated execution context

Security: DM policies (pairing/allowlist/open/disabled), SSRF guard

Plugin Architecture: Hot-reloadable plugins with full lifecycle management


Quick Start

# Clone and install
git clone https://github.com/Dwsy/pi-gateway.git
cd pi-gateway
bun install

# Configure
cp pi-gateway.jsonc.example pi-gateway.jsonc
export TELEGRAM_BOT_TOKEN="your-bot-token"

# Start
bun run start

# Open http://localhost:52134

Configuration

Minimal setup:

{
  "gateway": { "port": 52134 },
  "agent": { "model": "claude-sonnet-4" },
  "channels": {
    "telegram": {
      "enabled": true,
      "botToken": "${TELEGRAM_BOT_TOKEN}"
    }
  }
}

Key settings:

Section Purpose Required
gateway.port HTTP/WS listen port No (default: 52134)
agent.model LLM model for agent Yes
agent.pool RPC pool size (min/max) No
channels.*.botToken Platform bot token If channel enabled

Plugin System

export default function myPlugin(api: GatewayPluginApi) {
  // Hook into agent lifecycle
  api.registerHook(["agent_end"], async (ctx) => {
    console.log(`Session ${ctx.sessionKey} completed`);
  });

  // Add HTTP endpoint
  api.registerHttpRoute("GET", "/health", async (req, res) => {
    res.json({ status: "ok" });
  });

  // Register slash command
  api.registerCommand("ping", async (ctx) => {
    await ctx.reply("Pong!");
  });
}

Available hooks:

Hook When
before_agent_start Before agent starts
agent_end After agent finishes
message_received Message from channel
message_sending Before sending (mutable)
message_sent After sending
before_tool_call Before tool execution
after_tool_call After tool execution
session_start / session_end Session lifecycle
gateway_start / gateway_stop Gateway lifecycle

CLI Commands

pi-gw gateway [--port N] [--verbose]   # Start gateway
pi-gw doctor                            # Health check
pi-gw send --to <target> --message <m>  # Send message
pi-gw config show                       # Show config
pi-gw onboard                           # Interactive setup

Send command targets:

telegram:<chatId>                           # DM
telegram:<accountId>:<chatId>               # Specific account
telegram:<accountId>:<chatId>:topic:<tid>   # Topic in group
discord:<channelId>                         # Discord channel

Security

Policy Behavior
pairing Unknown sender gets 8-char code, admin approves
allowlist Only configured user IDs can interact
open Anyone can interact
disabled Block all DMs
# Approve pairing request
pi-gw pairing approve telegram ABCD1234

Project Status

Feature Status
Telegram Stable
Discord Stable
Feishu (Lark) Beta
WebChat Stable
Cron Engine Stable
Plugin System Stable
Hot-Reload Planned

Requirements


Common Issues

Cannot connect to Telegram

# Verify bot token
curl https://api.telegram.org/bot<TOKEN>/getMe

# Check environment variable
echo $TELEGRAM_BOT_TOKEN

RPC pool exhausted

{ "agent": { "pool": { "min": 2, "max": 8 } } }

Model rate limited

{
  "agent": {
    "modelFailover": {
      "primary": "claude-sonnet-4",
      "fallbacks": ["gpt-4o", "gemini-pro"]
    }
  }
}

Documentation


Contributing

See CONTRIBUTING.md for development setup.


License

MIT - See LICENSE for details.


Acknowledgments