Agent Gateway是所有客户端到 Agent 的统一网关:提供多频道接入、请求路由与调度能力
Access rate limit exceeded. Please log in to continue.
Agent Gateway
One gateway from every client to the agent — multi-channel access, routing, scheduling
English · Chinese · Local Validation · Repository
Agent Gateway is the gateway process of the split deployment (Gateway + AgentServer). It sits between user-facing channels and the AgentServer: it accepts connections from the Web UI, TUI, ACP clients and IM platforms, routes requests to the AgentServer over a single WebSocket (E2A protocol), and owns the cross-session services — scheduled tasks, heartbeat, health checks and multi-instance isolation.
The gateway builds and runs as its own Python package agent-gateway with two entry points: agent-gateway (gateway + channels) and agent-gateway-acp (ACP bridge).
Web control startup does not wait for the execution SDK or legacy Cron model migration.
Cron migration makes at most three attempts, with a three-second remote catalog timeout.
If migration remains unavailable, existing jobs retain their legacy model names and the
scheduler starts once, preserving compatibility with older AgentServers. Mutations and
run-now requests wait at most five seconds for startup and receive SERVICE_UNAVAILABLE
on timeout, startup failure or shutdown. Extension manifests may declare requires_sdk: false
when their module import and initialization need no SDK. Omitted declarations retain
the legacy SDK/logging initialization order. Authentication, crypto, storage and selected
southbound clients are initialized before Web traffic in either case. Deferred callback
registrations preserve order; triggering a registered event waits for SDK readiness.
Core Features
| Capability | Value |
|---|---|
| Multi-channel access | One process serves the Web UI, TUI, ACP clients and IM platforms (Xiaoyi, Feishu, DingTalk, WeCom, Personal WeChat, Telegram, Discord, Slack, WhatsApp) with per-channel lazy loading |
| Request routing | Every client request is normalized and forwarded to the AgentServer over one E2A WebSocket; responses and stream chunks are demultiplexed by request id |
| Session & project routing | Gateway keeps routing state (session, project, work mode, channel binding) so clients can reconnect or switch without losing the conversation |
| Scheduled tasks | Cron store, scheduler and command acknowledgement live in the gateway; jobs are executed by the AgentServer; system-owned proactive.tick jobs cannot be created or edited manually |
| Media & file forwarding | Files from IM platforms are persisted through the AgentServer — the gateway never writes into the user's project directory |
| Security | WebSocket origin checks, user-id whitelist, explicit stripping of client-forged auth keys, and credentials forwarded only from authenticated channels |
| Protocol bridges | ACP, A2A, SSH relay and web proxy channels share the same routing layer |
| Health & heartbeat | Periodic health checks and heartbeat keep the gateway/AgentServer pair observable and let the supervisor restart a stuck half |
| Multi-instance isolation | AGENT_GATEWAY_HOME / AGENT_GATEWAY_DATA_DIR isolate workspaces, and a workspace lock prevents two gateways from serving the same instance |
Attachments and file references
Structured attachments and @path mentions share the same expansion rules. PDF, Office, image, archive, and other non-text files retain only their filename, absolute path, type, and reason for not being expanded. Their raw bytes are never decoded into the model input. Agents should use document or media reading tools as needed; Gateway does not parse PDFs.
PDF detection also scans for a versioned header (%PDF-1.7, for example) starting within the first 1024 bytes, including when the extension has been changed. Text or source files containing a literal versioned PDF header in this region may conservatively retain only a file reference; a mention of %PDF- without a version is not sufficient on its own.
UTF-8 text and source files may be inlined, up to 128 KiB of body text per file and 256 KiB of body text across a message, measured in UTF-8 bytes. Truncation notices also consume the remaining message budget. XML wrappers, path attributes and deferred file references are excluded, so the final rendered message can exceed 256 KiB. Each actual path is expanded only once. Truncated files and files deferred by the message budget retain a path and a notice for further tool reads. Invalid UTF-8 and binary control characters are not converted into replacement-character noise.
The binary-text check rejects Unicode control characters (Cc, including C0, DEL and C1), except tab, newline and carriage return. Text containing form feed (U+000C) or vertical tab (U+000B) therefore also retains only a file reference and requires a file reading tool. Unicode format characters (Cf, including bidirectional controls, zero-width characters and BOM) are preserved as text to support emoji sequences and multilingual content. This check identifies non-text files; it does not sanitize document content.
MessageHandler.resolve_at_file_references retains max_file_size and adds the keyword-only max_total_inline_bytes parameter. max_file_size=None disables only the per-file limit, not the message budget. These byte limits do not guarantee a model token limit.
Related Documents
- Documentation — tutorial, how-to, reference, and explanation
- Examples — runnable mock AgentServer example
- Local Validation — end-to-end validation walkthrough
- AG-UI integration guide (Chinese) — Gateway setup, sessions, and application tools
- Release Notes
Requirements
| Dependency | Requirement |
|---|---|
| Operating system | Linux / macOS / Windows |
| Python | 3.11 ~ 3.13 |
| uv | Installed |
| Network | Access to gitcode.com (dependencies include git sources) |
Install
From Source
git clone https://gitcode.com/openJiuwen/agent-gateway.git
cd agent-gateway
uv sync
uv run agent-gateway --help
All third-party dependencies are declared in pyproject.toml; the package does not depend on workswarm and can be installed standalone.
If uv sync is slow or fails on the git sources, configure an index mirror first:
export UV_DEFAULT_INDEX=https://pypi.org/simple
uv sync
From Wheel
bash scripts/build.sh --wheel
pip install dist/agent_gateway-*.whl
Quick Start
Start the downstream AgentServer in one terminal (or use the mock from examples/mock-agent-server):
uv run jiuwenswarm-agentserver --port 18092
Then start the gateway in another terminal:
# Keep the workspace of this instance separate
export AGENT_GATEWAY_HOME="$PWD/.local-home"
# AgentServer (southbound) and WebChannel (northbound)
export AGENT_SERVER_HOST=127.0.0.1
export AGENT_SERVER_PORT=18092
export WEB_HOST=127.0.0.1
export WEB_PORT=19000
uv run agent-gateway --port 19000
Ready markers in the log:
[ExtensionManager] 加载 <name>— an extension has been loadedUvicorn running on http://127.0.0.1:19000— WebChannel is up[Cron] loaded N job(s) from .../background_cleanup: started ...— cron and background cleanup are running
A [App] Another Gateway is already serving this workspace error means another gateway holds the workspace lock; stop it or use a different AGENT_GATEWAY_HOME.
For a fully self-contained walkthrough (mock downstream + chat.send round trip), see Quick Start.
Architecture
Web UI / TUI / ACP / IM channels
│ WebSocket (E2A frames)
▼
Agent Gateway
├─ MessageHandler + ChannelManager
├─ WebChannel (uvicorn) / TUI route
├─ Cron scheduler · heartbeat · health check
└─ routing / session binding
│ AgentServer WebSocket (E2A)
▼
jiuwenswarm-agentserver
The gateway is stateless with respect to agent execution: everything that touches the workspace, the model credentials or the tool sandbox is executed by the AgentServer. See Architecture for details.
Command-Line Options
| Option | Description |
|---|---|
-u, --agent-server-url <URL> |
AgentServer WebSocket URL; overrides AGENT_SERVER_URL / AGENT_SERVER_HOST + PORT |
-H, --host <HOST> |
WebChannel bind host (default WEB_HOST or 127.0.0.1) |
-p, --port <PORT> |
WebChannel bind port (default WEB_PORT or 19000) |
--web-path <PATH> |
WebChannel WebSocket path (default WEB_PATH or /ws) |
--name <name> |
Start a named instance from instances.yaml |
--dotenv <path> |
Load environment variables from a .env file at startup |
Environment Variables
| Variable | Default | Description |
|---|---|---|
AGENT_GATEWAY_HOME |
~ |
Workspace root; the instance directory is .jiuwenswarm. |
AGENT_GATEWAY_DATA_DIR |
unset | Data directory for multi-instance isolation. |
AGENT_SERVER_URL |
derived | AgentServer WebSocket URL (highest priority) |
AGENT_SERVER_HOST / AGENT_SERVER_PORT |
127.0.0.1 / 18092 |
Used to build ws://host:port when the URL is unset |
WEB_HOST / WEB_PORT / WEB_PATH |
127.0.0.1 / 19000 / /ws |
WebChannel (uvicorn) listen address |
GATEWAY_HOST / GATEWAY_PORT |
127.0.0.1 / 19001 |
TUI route listen address |
AGENT_CONNECT_RETRY / AGENT_CONNECT_RETRY_INTERVAL |
20 / 3 |
Southbound connection retries / interval in seconds |
See the CLI and environment reference for the environment variables. When deployed together with the JiuwenSwarm AgentServer, make sure both sides use the same data directory and secrets.
config.yaml
The config file lives at $AGENT_GATEWAY_HOME/.jiuwenswarm/config/config.yaml. On a first standalone start, Gateway installs its bundled template when this file is missing; existing user configuration is preserved. To start with every IM channel disabled:
channels: {}
health_check:
every: 60
target: web
Channels (feishu, dingtalk, telegram, discord, slack, wecom, wechat, xiaoyi, whatsapp) are loaded lazily: only the entries present under channels are initialized, together with their dependencies.
Channels
Enable a channel in the Web UI, or in config.yaml with enabled: true and that platform's credentials.
| Region | Channels |
|---|---|
| China | Xiaoyi, Feishu (Lark), DingTalk, WeCom (WeChat Work), Personal WeChat |
| International | Telegram, Discord, Slack, WhatsApp |
Capabilities differ per platform: Xiaoyi and WhatsApp are private chat only; Feishu, WeCom, DingTalk, Telegram, Discord and Slack also work in groups, usually by @mentioning the bot. Feishu and WeCom additionally support the Digital Avatar feature. See Configure Channels.
Local Validation
A self-contained walkthrough that mocks the AgentServer and drives the gateway through its /tui route is in docs/en/how-to/local-validation.md. It covers install, workspace isolation, ports, startup markers, an upstream chat.send round trip and troubleshooting.
Build
bash scripts/build.sh # clean, then build wheel + sdist
bash scripts/build.sh --wheel # wheel only
bash scripts/build.sh --sdist # sdist only
bash scripts/build.sh --no-clean # keep build/ artifacts
Artifacts are written to dist/:
dist/agent_gateway-<version>-py3-none-any.whldist/agent_gateway-<version>.tar.gz
Test
./run_tests.sh # all tests
./run_tests.sh -u # unit tests only
./run_tests.sh -c # tests + HTML coverage report
./run_tests.sh -p # parallel (requires pytest-xdist)
pytest.ini enables coverage by default for agent_gateway:
- terminal report (
term-missing) htmlcov/index.htmlcoverage.xml
Standalone contract ST (spawns a real gateway process against the bundled StubAgentServer; no workswarm required):
python -m pytest st_test/testcases_gateway --no-cov
workswarm compatibility ST (requires workswarm, develop by default; starts a real AgentServer and gateway process per run):
python -m pytest st_test/testcases_integration --no-cov
Contributing
We welcome developers to contribute to Agent Gateway:
- Report bugs, feature requests, or usage issues: Issues
- Submit code, documentation, or examples: Pull Requests
Before contributing, read the Contributing Guide for the debugging workflow, code style, and commit conventions.
Community
| Channel | Purpose | Link |
|---|---|---|
| Website | Product info, updates, and ecosystem | Visit Website |
| SIG | Technical roadmap, engineering practices, ecosystem building | Join SIG |
| Swarm Skills Hub | Browse, publish, and reuse agent skills | Visit Swarm Skills Hub |
License
This project is licensed under Apache License 2.0.
This product serves solely as a workflow orchestration tool and does not embed any AI model capabilities. When users integrate AI models for specific business scenarios, they shall bear full responsibility for compliance obligations under the EU AI Act and other relevant regulatory frameworks.