npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@cloudbase/agent-adapter-wx

v0.0.24

Published

WeChat adapter for AG-Kit - Forward LLM messages to WeChat platforms

Readme

@cloudbase/agent-adapter-wx

WeChat adapter for AG-Kit - Forward LLM messages to WeChat platforms

Features

Multi-Platform Support: WeChat Mini Program, Official Account (Service/Subscription), Enterprise WeChat Customer Service ✅ Express Handler: Ready-to-use createWxMessageHandler for Express servers ✅ Agent Adapter: WeChatAgent wraps any AG-UI agent with WeChat integration ✅ CloudBase History: WeChatHistoryManager with CloudBase database storage ✅ Automatic Token Management: Built-in caching and refresh mechanism ✅ Type-Safe: Full TypeScript support ✅ Async/Sync Reply: Supports both sync HTTP response and async message sending

Installation

npm install @cloudbase/agent-adapter-wx
# or
pnpm add @cloudbase/agent-adapter-wx

Quick Start

Express Server Handler

import express from "express";
import { createWxMessageHandler, WeChatAgent } from "@cloudbase/agent-adapter-wx";

const app = express();
app.use(express.json());

// Create handler with agent factory
const wxHandler = createWxMessageHandler(
  async ({ request, options }) => {
    const agent = new WeChatAgent({
      agent: yourBaseAgent,
      wechatConfig: {
        platform: WeChatPlatform.SERVICE,
        appId: process.env.WECHAT_APP_ID!,
        appSecret: process.env.WECHAT_APP_SECRET!,
      },
    });
    return { agent };
  },
  { logger: console }
);

app.post("/wx/message", wxHandler);

Direct Message Sending

import { WeChatSender, WeChatPlatform } from "@cloudbase/agent-adapter-wx";

const sender = new WeChatSender({
  platform: WeChatPlatform.MINI_APP,
  appId: "your-app-id",
  appSecret: "your-app-secret",
});

await sender.send({
  toUser: "user-openid",
  message: {
    content: "Hello from LLM!",
    type: "text",
  },
});

Core Components

createWxMessageHandler

Express route handler for WeChat message webhook. Handles the complete message flow:

  1. Parse incoming WeChat message
  2. Validate message type (text/voice)
  3. Handle retry logic for unverified accounts (11-second rule)
  4. Process "继续" command for async replies
  5. Run agent and return response
import { createWxMessageHandler } from "@cloudbase/agent-adapter-wx";

const handler = createWxMessageHandler(createAgent, {
  logger: console, // optional logger
});

app.post("/wx/callback", handler);

Bot ID Resolution Priority:

  1. SCF_FUNCTIONNAME environment variable
  2. Parsed from request URL via utils.parseBotId()
  3. Parsed from HOSTNAME environment variable
  4. Fallback: "agent-id"

WeChatAgent

Wraps any AG-UI AbstractAgent with WeChat-specific functionality:

import { WeChatAgent, WeChatPlatform, WeChatSendMode } from "@cloudbase/agent-adapter-wx";

const wechatAgent = new WeChatAgent({
  agent: yourBaseAgent,
  wechatConfig: {
    platform: WeChatPlatform.SERVICE,
    appId: "your-app-id",
    appSecret: "your-app-secret",
    sendMode: WeChatSendMode.AITOOLS, // or WeChatSendMode.LOCAL
  },
  recommendQuestions: ["Question 1", "Question 2"],
});

WeChatHistoryManager

CloudBase database storage for chat history (singleton pattern):

import { WeChatHistoryManager } from "@cloudbase/agent-adapter-wx";

// Initialize (requires TCB_ENV or CLOUDBASE_ENV)
const historyManager = WeChatHistoryManager.getInstance({
  envId: "your-cloudbase-env", // or set TCB_ENV env var
  collectionName: "wx_chat_history", // default
  botId: "your-bot-id",
});

// Save to history
await historyManager.saveToHistory({
  messageId: "msg-123",
  role: "user",
  content: "Hello",
  threadId: "conversation-id",
  createdAt: Date.now(),
  metadata: {
    sender: "user-openid",
    triggerSrc: "WXService",
  },
});

// Get previous reply
const previous = await historyManager.getPreviousReply(
  "conversation-id",
  "msg-123"
);

Usage Examples

Enterprise WeChat Customer Service

const sender = new WeChatSender({
  platform: WeChatPlatform.CUSTOM_SERVICE,
  appId: "your-corp-id",
  appSecret: "your-corp-secret",
  openKfId: "your-kf-id",
});

await sender.send({
  toUser: "user-openid",
  message: {
    content: "Your AI assistant response",
    type: "text",
  },
  msgId: "original-message-id",
});

Batch Sending

const results = await sender.sendBatch([
  { toUser: "user1", message: { content: "Message 1", type: "text" } },
  { toUser: "user2", message: { content: "Message 2", type: "text" } },
]);

API Reference

Types

WeChatPlatform

enum WeChatPlatform {
  CUSTOM_SERVICE = "WXCustomerService", // 企业微信客服
  MINI_APP = "WXMiniApp",               // 微信小程序
  SERVICE = "WXService",                // 微信服务号
  SUBSCRIPTION = "WXSubscription",      // 微信订阅号
}

WeChatSendMode

enum WeChatSendMode {
  LOCAL = "local",     // Use WeChatSender (local development)
  AITOOLS = "aitools", // Use aitools SDK (cloud function)
}

HistoryEntry

interface HistoryEntry {
  id?: string;
  messageId: string;
  role: "user" | "assistant" | "system";
  content?: string;
  threadId: string;
  createdAt: number;
  botId?: string;
  runId?: string;
  needAsyncReply?: boolean;
  status?: string;
  type?: string;
  metadata?: {
    sender?: string;
    triggerSrc?: string;
    originMsg?: string;
    replyTo?: string;
    reply?: string;
    image?: string;
    recommendQuestions?: string[];
  };
}

WeChatSender Methods

  • send(options, originMsg?): Promise<WeChatAPIResponse>
  • sendBatch(messages): Promise<WeChatAPIResponse[]>
  • sendAsync(options, originMsg?): Promise<void>
  • clearCache(): void

WeChatHistoryManager Methods

  • getInstance(config?): WeChatHistoryManager - Get singleton instance
  • getPreviousReply(threadId, messageId?): Promise<HistoryEntry | null>
  • saveToHistory(record): Promise<void>
  • updateContent(threadId, messageId, content): Promise<void>

Environment Variables

| Variable | Description | |----------|-------------| | TCB_ENV or CLOUDBASE_ENV | CloudBase environment ID (required for history) | | SCF_FUNCTIONNAME | Cloud function name (used as bot ID) | | HOSTNAME | Container hostname (fallback for bot ID) |

Platform-Specific Notes

| Platform | Trigger Source | Async Reply | |----------|---------------|-------------| | Mini Program | WXMiniApp | Always async | | Service Account | WXService | Based on verification | | Subscription | WXSubscription | Based on verification | | Enterprise CS | WXCustomerService | Always async |

License

ISC