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-ui-miniprogram

v0.0.22

Published

AG-UI SDK for WeChat Mini Program

Readme

@cloudbase/agent-ui-miniprogram

微信小程序的 AG-UI 客户端 SDK。

为什么用这个库?

AG-UI 是一个用于构建 AI 对话应用的协议。它定义了客户端和服务端如何通信——流式文本、工具调用、消息历史等。

如果从零开始构建 AG-UI 客户端,你需要:

  1. 解析服务端的 Server-Sent Events 流
  2. 处理 15+ 种事件类型(TEXT_MESSAGE_START、TOOL_CALL_ARGS、RUN_ERROR...)
  3. 维护消息状态、合并流式片段、跟踪工具调用状态
  4. 执行客户端工具并回传结果
  5. 保持 UI 与所有状态变化同步

@cloudbase/agent-ui-miniprogram 帮你处理了这些逻辑。 你只需要:

调用 this.agui.sendMessage 发送消息:

// chat.js
this.agui.sendMessage('你好')

将注入的消息列表数据 uiMessages 渲染成 UI:

<!-- chat.wxml -->
<view wx:for="{{agui.uiMessages}}" wx:key="id">
  {{item.role}}: {{item.parts[0].text}}
</view>

安装

npm install @cloudbase/agent-ui-miniprogram@beta

快速开始

import { createAGUIBehavior, CloudbaseTransport } from '@cloudbase/agent-ui-miniprogram'

Component({
  behaviors: [
    createAGUIBehavior({
      transport: new CloudbaseTransport({ botId: 'your-bot-id' }),
    })
  ],

  methods: {
    onSend(e) {
      this.agui.sendMessage(e.detail.value)
    }
  }
})
<view class="chat">
  <view wx:for="{{agui.uiMessages}}" wx:key="id" class="message {{item.role}}">
    <block wx:for="{{item.parts}}" wx:for-item="part" wx:key="id">
      <text wx:if="{{part.type === 'text'}}">{{part.text}}</text>
      <view wx:if="{{part.type === 'tool'}}" class="tool">
        🔧 {{part.name}}: {{part.status}}
      </view>
    </block>
  </view>
  <view wx:if="{{agui.error}}" class="error">{{agui.error.message}}</view>
</view>

<input placeholder="输入消息..." bindconfirm="onSend" disabled="{{agui.isRunning}}" />

核心概念

本 SDK 使用小程序的 Behavior 机制——一种可以在多个组件间复用代码的 mixin 模式。

当你在组件中添加由 createAGUIBehavior() 创建出的 Behavior 后,它会:

  1. 将 AG-UI 相关状态注入到 this.data.agui
  2. 提供 this.agui.xxx 方法调用 AG-UI 相关能力

状态

Behavior 会在 this.data.agui 中提供以下数据:

| 属性 | 用途 | |------|------| | uiMessages | 渲染聊天界面 | | isRunning | 显示加载状态、禁用输入框 | | error | 显示错误信息 |

对于其他数据,请查看 API Reference 了解。

Transport

flowchart LR
    A[小程序<br/>@cloudbase/agent-ui-miniprogram] <-->|transport| B[AG-UI 服务端<br/>你的后端]
    B <--> C[LLM<br/>Claude 等]

@cloudbase/agent-ui-miniprogram 采用了通信层(Transport)无关的设计。它只负责处理 AG-UI 事件流、管理状态、提供交互方法,而不关心如何与后端通信。

Transport 层专门负责与后端通信,你可以在创建 Behavior 的时候传入任意符合定义的 Transport 实例。

createAGUIBehavior({
  transport: new AnyTransport()
})

@cloudbase/agent-ui-miniprogram 提供了 CloudbaseTransport,对接 Cloudbase 云开发 Agent。

createAGUIBehavior({
  transport: new CloudbaseTransport({ botId: '...' })
})

自定义 Transport 需要满足的接口:

interface Transport {
  run(input: RunAgentInput): AsyncIterable<BaseEvent>
}

客户端工具

客户端工具能够让 Agent 能够与小程序环境交互。

使用场景:

  • 访问设备功能(位置、相机、存储)
  • 读取客户端数据(用户偏好、购物车)
  • 触发 UI 操作(导航、弹窗、提示)

示例:

createAGUIBehavior({
  transport,
  tools: [{
    name: 'get_location',
    description: '获取用户当前位置',
    parameters: { type: 'object', properties: {} },
    handler: async ({ args }) => {
      const res = await wx.getLocation()
      return JSON.stringify(res)
    }
  }]
})

当 Agent 决定调用工具时,SDK 会执行你的 handler 并自动将结果发回给 Agent。


CloudbaseTransport 配置

用于微信云开发 Cloudbase 的 Transport 实现,基于 wx.cloud.extend.AI.bot

前置条件

  1. 开通微信云开发 - 在小程序中启用云开发
  2. 创建 Agent - 创建一个 AI Bot 并获取其 agentId

配置步骤

1. 在 app.js 中初始化云开发

// app.js
App({
  onLaunch() {
    wx.cloud.init({
      env: 'your-env-id'
    })
  }
})

2. 使用 CloudbaseTransport

import { createAGUIBehavior, CloudbaseTransport } from '@cloudbase/agent-ui-miniprogram'

const transport = new CloudbaseTransport({
  botId: 'your-agent-id'  // 从云开发控制台获取
})

Component({
  behaviors: [createAGUIBehavior({ transport })]
})

CloudbaseTransport 构造函数

new CloudbaseTransport(options: { botId: string })

| 选项 | 类型 | 必需 | 说明 | |------|------|------|------| | botId | string | 是 | 云开发控制台中的 Agent ID |

工作原理

CloudbaseTransport 内部调用 wx.cloud.extend.AI.bot.sendMessage()

const res = await wx.cloud.extend.AI.bot.sendMessage({
  botId: 'your-bot-id',
  data: {
    threadId: '...',
    messages: [...],
    tools: [...],
    context: [...]
  }
})

for await (const event of res.eventStream) {
  // AG-UI 事件在这里流式返回
}

API 参考

createAGUIBehavior(options?)

创建一个带有 AG-UI 状态管理的 Behavior mixin。

import { createAGUIBehavior } from '@cloudbase/agent-ui-miniprogram'

Component({
  behaviors: [createAGUIBehavior(options)]
})

配置项

| 选项 | 类型 | 说明 | |------|------|------| | transport | Transport | Transport 实现(sendMessage 必需) | | threadId | string | 会话线程 ID(不传则自动生成) | | messages | Message[] | 初始消息 | | tools | ClientTool[] | 带有 handler 的客户端工具 | | contexts | Context[] | Agent 运行时的上下文 | | onRawEvent | (event: BaseEvent) => void | 每个原始 AG-UI 事件的回调 |

实例方法

组件 attached 后通过 this.agui.xxx 访问。

| 方法 | 签名 | 说明 | |------|------|------| | init | (config: AGUIConfig) => void | 初始化或重新初始化 transport/threadId | | sendMessage | (input: string \| Message[]) => Promise<void> | 发送消息并运行 agent | | appendMessage | (message: Message) => void | 添加消息但不触发 agent | | setMessages | (messages: Message[]) => void | 替换整个消息历史 | | reset | () => void | 重置为配置项中的初始状态 | | setThreadId | (threadId: string) => void | 更改线程 ID | | addTool | (tool: ClientTool) => void | 注册新工具 | | removeTool | (name: string) => void | 按名称移除工具 | | updateTool | (name: string, updates: Partial<ClientTool>) => void | 更新工具属性 | | clearTools | () => void | 移除所有工具 |

状态属性

通过 this.data.agui.xxx 访问(WXML 中使用 {{agui.xxx}})。

| 属性 | 类型 | 说明 | |------|------|------| | messages | Message[] | 原始消息历史(用于 AI) | | uiMessages | UIMessage[] | UI 优化的消息(用于渲染) | | isRunning | boolean | Agent 是否正在处理中 | | error | AGUIClientError \| null | 当前错误(如果有) | | activeToolCalls | ToolCallState[] | 进行中的工具调用 | | threadId | string | 当前会话线程 ID | | tools | Tool[] | 已注册的工具定义(不含 handler) | | contexts | Context[] | 已注册的上下文 | | runId | string \| null | 当前运行 ID(未运行时为 null) |

this.agui 完整类型

可以通过 this.agui 访问到所有的数据和方法。

interface AGUINamespace {
  // 方法
  init(config: AGUIConfig): void
  sendMessage(input: string | Message[]): Promise<void>
  appendMessage(message: Message): void
  setMessages(messages: Message[]): void
  reset(): void
  setThreadId(threadId: string): void
  addTool(tool: ClientTool): void
  removeTool(name: string): void
  updateTool(name: string, updates: Partial<ClientTool>): void
  clearTools(): void

  // 状态(只读,与 this.data.agui 同步)
  readonly messages: Message[]
  readonly uiMessages: UIMessage[]
  readonly isRunning: boolean
  readonly error: AGUIClientError | null
  readonly activeToolCalls: ToolCallState[]
  readonly threadId: string
  readonly tools: Tool[]
  readonly contexts: Context[]
  readonly runId: string | null

  // 配置(只读,传入 createAGUIBehavior 的原始选项)
  readonly config: CreateAGUIBehaviorOptions
}

类型定义

AG-UI 协议类型

以下类型来自 AG-UI 协议,本 SDK 对标版本:v0.0.42

详细定义请参考 AG-UI 官方文档:

UIMessage

interface UIMessage {
  id: string
  role: 'user' | 'assistant' | 'system' | 'developer'
  parts: UIMessagePart[]
}

type UIMessagePart = TextPart | ToolPart

interface TextPart {
  id: string
  type: 'text'
  text: string
  state?: 'streaming' | 'done'
}

interface ToolPart {
  id: string
  type: 'tool'
  toolCallId: string
  name: string
  argsString: string
  args: Record<string, unknown>
  status: 'pending' | 'ready' | 'executing' | 'completed' | 'failed'
  result?: unknown
  error?: AGUIClientError
}

ClientTool

扩展自 AG-UI 的 Tool 类型,增加了 handler 函数用于执行客户端工具。

interface ClientTool extends Tool {
  handler: (params: ToolHandlerParams) => string | Promise<string>
}

interface ToolHandlerParams {
  name: string
  description: string
  toolCallId: string
  args: Record<string, unknown>
}

AGUIClientError

interface AGUIClientError {
  code: AGUIClientErrorCode
  message: string
  recoverable: boolean
  details?: unknown
  originalError?: Error
}

type AGUIClientErrorCode =
  | 'INIT_ERROR'
  | 'TRANSPORT_ERROR'
  | 'RUNTIME_ERROR'
  | 'INVALID_EVENT'
  | 'TOOL_EXECUTION_ERROR'
  | 'TOOL_NOT_FOUND'
  | 'PARSE_ERROR'
  | 'TIMEOUT'
  | 'INVALID_CONFIG'
  | 'UNKNOWN'

ToolCallState

interface ToolCallState {
  toolCallId: string
  name: string
  argsString: string                    // 原始参数字符串(流式传输中)
  args: Record<string, unknown>         // 解析后的参数
  status: ToolCallStatus
  result?: unknown
  error?: AGUIClientError
}

type ToolCallStatus = 'pending' | 'ready' | 'executing' | 'completed' | 'failed'

AGUIConfig

interface AGUIConfig {
  transport: Transport
  threadId?: string
}

CreateAGUIBehaviorOptions

interface CreateAGUIBehaviorOptions {
  transport?: Transport
  threadId?: string
  messages?: Message[]
  tools?: ClientTool[]
  contexts?: Context[]
  onRawEvent?: (event: BaseEvent) => void
}

Transport

interface Transport {
  run(input: RunAgentInput): AsyncIterable<BaseEvent>
}

RunAgentInputBaseEvent 类型定义见 AG-UI 协议类型