@economic/agents-react

中文文档
2.1.0发布于 2026/11/09MITTypeScriptES Module近 30 天下载 2668

React hooks for connecting to agents built with @economic/agents. They wrap the Cloudflare agents and @cloudflare/ai-chat hooks and add typed connection state, message feedback, and the per-user multi-chat model used by `Assis

原始使用文档
文档目录11 节
  1. Install
  2. Which hook do I use?
  3. useAgent
  4. useChat
  5. Returns
  6. useAssistant
  7. Returns
  8. Options
  9. Types
  10. Authentication
  11. Tool approvals

@economic/agents-react

React hooks for connecting to agents built with @economic/agents. They wrap the Cloudflare agents and @cloudflare/ai-chat hooks and add typed connection state, message feedback, and the per-user multi-chat model used by Assistant.

Install

npm install @economic/agents-react

React 19 is a peer dependency.

Which hook do I use?

The package exports three hooks, layered on top of each other:

  • useAgent — the thin connection primitive both build on. Reach for it only when you need raw access to the connection.
  • useChat — connects directly to a single chat agent by name. Use it when you address one conversation yourself (e.g. one chat per route) rather than going through an Assistant.
  • useAssistant — the high-level hook for the v2 model: one assistant per user, many chats. It manages the chat list (create / open / delete), connects to the right chat facet, and exposes the active chat. Use this when your server uses an Assistant.

useAgent

The connection primitive useChat and useAssistant are built on. Connects to an agent by name and exposes its connection and call for invoking @callable methods.

import { useAgent } from "@economic/agents-react";

const agent = useAgent({
  host: "localhost:8787",
  agentName: "SupportAgent",
  name: "support",
  actorId: userId, // when set, the DO name becomes `${actorId}:${name}`
  authToken,
});

await agent.call("checkOrder", ["1234"]);
console.log(agent.state?.status);

useChat

Connects to a single chat agent by name — no Assistant needed. Returns the connection, the message interface, and message-feedback helpers.

import { useChat } from "@economic/agents-react";

const { status, chat, submitMessageFeedback, getMessageFeedback } = useChat({
  host: "localhost:8787",
  agentName: "MyChatAgent",
  name: `${userId}:${chatId}`,
  authToken,
  toolContext: { locale: "en-DK" },
});

// send a message
chat.sendMessage({ role: "user", parts: [{ type: "text", text: "Hello" }] });

// rate a message (1 = up, -1 = down) and read all feedback
await submitMessageFeedback(messageId, 1, "Helpful!");
const feedback = await getMessageFeedback();

Returns

FieldTypeDescription
statusAgentConnectionStatusConnection status.
refusalReasonstring | undefinedWhy the server refused the connection, if it said.
canChatbooleanfalse when the user can read the chat but not chat in it.
agentconnection objectThe underlying useAgent connection.
chatuseAgentChat resultmessages, sendMessage, setMessages, status, stop, …
submitMessageFeedback(id, rating, comment?) => Promise<void>Submit thumbs up/down feedback for a message.
getMessageFeedback() => Promise<Record<string, MessageFeedback>>All feedback for the chat, keyed by message id.

useAssistant

For the per-user, many-chats model: connects to the user's Assistant DO, keeps the chat list in sync, and manages which chat is active.

import { useAssistant } from "@economic/agents-react";

function Chat({ userId, authToken }: { userId: string; authToken: string }) {
  const { status, chats, currentChatName, assistant, chat } = useAssistant({
    host: "localhost:8787",
    agentName: "MyAssistant", // matches the Assistant DO binding/class name
    name: userId, // the Assistant is keyed by user
    authToken,
    toolContext: { locale: "en-DK" }, // forwarded to server tools as the request body
    welcomeMessage: "Hi! How can I help?",
  });

  return (
    <div>
      <button onClick={() => assistant.createChat()}>New chat</button>

      <ul>
        {chats.map((c) => (
          <li key={c.name}>
            <button onClick={() => assistant.openChat(c.name)}>{c.title ?? "Untitled"}</button>
            <button onClick={() => assistant.deleteChat(c.name)}>Delete</button>
          </li>
        ))}
      </ul>

      {chat.chat.messages.map((m) => (
        <Message key={m.id} message={m} />
      ))}

      <Composer
        onSend={(text) =>
          chat.chat.sendMessage({
            role: "user",
            parts: [{ type: "text", text }],
          })
        }
      />
    </div>
  );
}

Returns

FieldTypeDescription
statusAgentConnectionStatusConnection status of the assistant, or of the active chat once one is open.
chatsChatSummary[]Started chats plus the active empty draft, most recently updated first.
currentChatNamestring | undefinedId of the active chat, if any.
assistantAssistantActionsgetChats, createChat, openChat, deleteChat, renameChat.
chatuseChat resultThe active chat — chat.chat is the message interface (see below).

assistant actions:

ActionSignatureDescription
createChat()() => Promise<string>Creates a chat, makes it active, returns its id.
openChat(chatId)(chatId: string) => voidSwitches the active chat.
getChats()() => Promise<ChatSummary[]>Refreshes and returns the chat list.
deleteChat(chatId)(chatId: string) => Promise<void>Deletes a chat and clears the active selection.
renameChat(chatId)(chatId: string, title: string) => Promise<void>Renames a registered chat.

Titles and summaries are generated server-side a few seconds after the first message, so refetch with getChats() shortly after sending the opening message if you want the new title to appear.

The active empty chat is represented locally until its first turn registers it on the server.

After the active draft's first turn finishes, useAssistant refreshes the chat list automatically so the temporary entry is replaced by its persisted title and summary.


Options

All hooks share these connection options (useAssistant omits actorId):

OptionTypeDescription
hoststringWorker host, e.g. localhost:8787 or my-agent.workers.dev.
agentNamestringThe agent's DO binding/class name.
namestringDO name. For useAssistant this is the user id; for useChat, the chat key.
actorIdstring?If set, the DO name becomes ${actorId}:${name} (useAgent / useChat).
authTokenstring?Bearer token; sent as an Authorization header and WebSocket subprotocol.
enabledboolean?Gate the connection (defaults to enabled when a name is present).
sub{ agent; name }[]?Sub-agent routing (used internally by useAssistant).
toolContextRecord<string, unknown>?Forwarded to server tools as the request body (useChat / useAssistant).
welcomeMessagestring?Seeds an initial assistant message when the chat is empty.
onOpen / onClose / onErrorevent handlersWebSocket lifecycle callbacks.

Types

type AgentConnectionStatus =
  | "connecting"
  | "reconnecting"
  | "connected"
  | "disconnected"
  | "unauthorized"
  | "error";
type AgentConnectionType = "agent" | "chat" | "assistant";

type AgentConnectionState = {
  status: AgentConnectionStatus;
  type: AgentConnectionType;
  subAgentName?: string;
};

type ChatSummary = {
  name: string;
  isTemporary?: boolean; // true for the active chat before its first turn is registered
  title?: string;
  summary?: string;
  created_at: number;
  updated_at: number;
};

type MessageFeedback = {
  message_id: string;
  rating: number; // 1 = up, -1 = down
  comment?: string;
  created_at: number;
  updated_at: number;
};

The package also exports the handler types AssistantActions, GetChatsHandler, CreateChatHandler, OpenChatHandler, DeleteChatHandler, MessageFeedbackHandler, and GetMessageFeedbackHandler.


Authentication

Pass a JWT as authToken. It is sent both as an Authorization: Bearer … header and as a WebSocket subprotocol (["bearer", token]), matching the server-side getAuthenticator(env). When verification fails, the connection status becomes "unauthorized".

When the agent refuses a caller with a reason (an AuthenticationError with { reason } on the server), useChat returns it as refusalReason, so a client can tell refusals apart without matching close messages:

const { status, refusalReason } = useChat({/* … */});

if (status === "unauthorized" && refusalReason === "access-denied") {
  // the user has no access: don't retry with a new token
}

With useAssistant, it's chat.refusalReason.


Tool approvals

useChat and useAssistant show a durable tool's step approval (step.requestApproval on the server) exactly as they show a tool's approval: its part has the same state (approval-requested, then approval-responded or output-denied) and approval, and chat.addToolApprovalResponse({ id, approved }) answers both. A client handles them with the same code.

getToolApproval(part) returns the approval with the descriptor the agent sent: the action's approvalSummary or the step's summary as summary, and its risk as risk.

import { getToolApproval, getToolPartState } from "@economic/agents-react";

if (getToolPartState(part) === "waiting-approval") {
  const approval = getToolApproval(part)!;

  // approval.descriptor?.summary, approval.descriptor?.risk ("low" | "medium" | "high")
  chat.addToolApprovalResponse({ id: approval.id, approved: true });
}

A rejected step approval goes back to the tool, which decides what happens next, so the part then shows the tool's result rather than staying denied.

版本与发布记录

@economic/agents-react 共发布 48 个版本,首次发布于 2026/04/13;过去 12 个月发布了 48 个版本。

版本发布日期距今
2.1.0latest2026/11/094 天前
2.0.02026/10/2618 天前
2.0.0-alpha.39514403335.1.0alpha2026/10/2123 天前
2.0.0-alpha.39497993435.1.02026/10/2123 天前
2.0.0-alpha.39466073931.1.02026/10/2123 天前
2.0.0-alpha.38489283394.1.02026/10/1430 天前

关于 @economic/agents-react 的常见问题

@economic/agents-react 是什么?

React hooks for connecting to agents built with @economic/agents. They wrap the Cloudflare agents and @cloudflare/ai-chat hooks and add typed connection state, message feedback, and the per-user multi-chat model used by `Assis

如何安装 @economic/agents-react?

在项目目录运行 npm install @economic/agents-react,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^19)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@economic/agents-react 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@economic/agents-react 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@economic/agents-react 可以商用吗?

@economic/agents-react 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@economic/agents-react 的下载量有多少?

根据 npm 官方下载统计,@economic/agents-react 在 2026/10/13 – 2026/11/11 这 30 天内被下载 2,668 次,日均约 89 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@economic/agents-react 还在维护吗?

最新版本 2.1.0 发布于 2026/11/09(4 天前);至今共发布 48 个版本,其中过去 12 个月发布了 48 个;首次发布于 2026/04/13。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。