How sgaofen/cli-in-wechat works
1. This repository is a TypeScript/Node.js bridge service, not a standalone AI app. It runs on the user’s computer and connects WeChat ClawBot messages to locally installed AI coding CLIs. The computer is the execution boundary; WeChat is only the remote control surface.
2. The system has two major external dependencies: the official WeChat iLink Bot API and a set of locally spawned command-line tools (Claude Code, Codex CLI, Gemini CLI, Kimi Code, OpenCode). The bridge translates between WeChat message events and each tool’s own CLI invocation style.
3. The entrypoint is src/index.ts, which wires together configuration, the iLink client, the message router, and the adapter registry. This is the orchestration layer that starts the long-polling loop and dispatches incoming messages into the bridge pipeline.
4. src/ilink/ is the WeChat-facing transport layer. auth.ts handles QR-code login and token acquisition, client.ts handles long polling, sending messages, typing indicators, and token renewal, and types.ts defines the API contract. This layer isolates all network interaction with ilinkai.weixin.qq.com.
5. src/bridge/router.ts is the central message dispatcher. It interprets @tool prefixes, / commands, >> result-chaining, chained tool syntax like @claude>codex, session-resume flows, and the Claude-specific AskUserQuestion round-trip back to WeChat. This is where message intent is converted into executable actions.
6. src/adapters/ is the tool abstraction boundary. base.ts defines shared adapter behavior and spawn helpers, while claude.ts, codex.ts, gemini.ts, kimi.ts, and opencode.ts each encode one CLI’s invocation model, permissions flags, stdin/stdout handling, and output parsing. registry.ts detects which tools are installed and available for routing.
7. The adapter layer is intentionally heterogeneous because each CLI behaves differently. Some tools are driven through stdin, some through flags like --print or -p, and Claude can also use an Agent SDK-style interaction for richer turns. The bridge hides these differences so the router can treat them as interchangeable tool backends.
8. src/bridge/session.ts provides conversation persistence and continuity. It stores session metadata locally with atomic writes, enabling /resume, /session set <id>, /fork, /new, and continuity across WeChat and terminal-originated sessions. This is the state boundary that preserves context between messages.
9. src/bridge/formatter.ts is the output-shaping layer. It converts adapter responses into WeChat-friendly message content, including formatting for summaries, streamed or multi-part outputs, and command feedback. This prevents raw CLI output from leaking directly into the chat experience.
10. src/utils/ contains cross-cutting infrastructure. http.ts wraps fetch with timeout, retries, jitter, and optional proxy support; media.ts handles attachment download, AES decryption, and safe filenames; crypto.ts provides signing/encryption helpers; logger.ts standardizes diagnostics. These utilities support robustness but are not business logic themselves.
11. src/config.ts centralizes local configuration such as default tool, working directory, CLI timeout, allowed users, and per-tool arguments. The README makes clear that allowedUsers is a key security boundary: if left empty, any private-chat user can trigger fully privileged local CLI execution.
12. The main data flow is: WeChat message arrives via iLink long polling → router classifies it → session/context is loaded or updated → matching adapter spawns or drives the chosen CLI → output is formatted → response is sent back through iLink. For AskUserQuestion, the flow temporarily reverses: Claude asks a question, the bridge relays it to WeChat, then the reply is fed back into the same session.
13. Reliability is a visible architectural concern. The bridge tolerates transient network failures with retries, handles token expiry by forcing re-login, and avoids shell-injection risks in tool adapters by preferring stdin or structured arguments where possible. That makes the service resilient because both the chat transport and the local CLI processes can fail independently.
14. The repository also includes tests under test/ that cover routing, session behavior, media handling, HTTP resilience, and adapter-specific behavior. .github/workflows/ci.yml suggests automated validation in CI, which is important because the architecture depends on several external tools and network-bound integrations that can regress independently.
Main entry points: router.ts Router · index.ts Main · base.ts Base Adapter · client.ts Client
Components 20
Entry & CLI
Process startup and local command entrypoints
WeChat Transport
Official iLink API integration
Bridge Core
Message routing, session state, and response shaping
- Router · Classifies commands, tool routing, chained flows, and AskUserQuestion round-trips
src/bridge/router.ts - Session Store · Persistent session metadata, resume, fork, and continuity handling
src/bridge/session.ts - Formatter · Converts adapter output into WeChat-friendly message content
src/bridge/formatter.ts
Tool Adapters
Per-CLI execution backends and availability detection
- Registry · Detects installed adapters and exposes available backends
src/adapters/registry.ts - Base Adapter · Shared adapter behavior and process spawn helpers
src/adapters/base.ts - Claude · Claude Code invocation, permissions, and richer turn handling
src/adapters/claude.ts - Codex · Codex CLI execution model and output parsing
src/adapters/codex.ts - Gemini · Gemini CLI invocation and output handling
src/adapters/gemini.ts - Kimi · Kimi Code CLI invocation and output handling
src/adapters/kimi.ts - OpenCode · OpenCode CLI invocation and model selection
src/adapters/opencode.ts
Utilities
Cross-cutting helpers for networking, media, crypto, and logging
- HTTP · Fetch wrapper with timeout, retries, jitter, and proxy support
src/utils/http.ts - Media · Attachment download, AES decryption, and safe filename handling
src/utils/media.ts - Crypto · Signing and encryption helpers
src/utils/crypto.ts - Logger · Standardized logging and diagnostics
src/utils/logger.ts
Connections 27
- Main → Config: loads · Reads runtime configuration before startup
- Main → Auth: auths · Initializes iLink login/token acquisition
- Main → Client: starts · Creates the long-polling transport client
- Main → Router: wires · Connects incoming messages to the dispatcher
- Main → Registry: wires · Registers available tool backends
- Client → HTTP: uses · Network requests and retries rely on HTTP helper
- Client → API Types: uses · Implements the iLink API contract
- Router → Session Store: loads/saves · Resumes and persists conversation state
- Router → Registry: selects · Chooses an available tool backend
- Router → Formatter: formats · Shapes replies for WeChat delivery
- Router → Media: handles · Processes attachments and downloaded media
- Router → Claude: dispatches · Routes Claude-specific turns and AskUserQuestion flows
- Router → Codex: dispatches · Routes Codex sessions
- Router → Gemini: dispatches · Routes Gemini sessions
- Router → Kimi: dispatches · Routes Kimi sessions
- Router → OpenCode: dispatches · Routes OpenCode sessions
- Registry → Base Adapter: extends · Adapter implementations share common spawn helpers
- Claude → Base Adapter: builds on · Specialized adapter behavior on top of shared base
- Codex → Base Adapter: builds on · Specialized adapter behavior on top of shared base
- Gemini → Base Adapter: builds on · Specialized adapter behavior on top of shared base
- Kimi → Base Adapter: builds on · Specialized adapter behavior on top of shared base
- OpenCode → Base Adapter: builds on · Specialized adapter behavior on top of shared base
- Send CLI → Client: uses · CLI entry reuses the iLink transport path
- Send CLI → Router: uses · Shares routing and session semantics where applicable
- Client → Logger: logs · Emits operational diagnostics
- Router → Logger: logs · Records command and routing diagnostics
- HTTP → Crypto: supports · Security-sensitive transport and media helpers rely on crypto utilities