@economic/agents-react 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.mts +6102 -25
  2. package/dist/index.mjs +83 -104
  3. package/package.json +11 -4
package/dist/index.mjs CHANGED
@@ -1,121 +1,100 @@
1
+ import { useAgent as useAgent$1 } from "agents/react";
1
2
  import { useAgentChat } from "@cloudflare/ai-chat/react";
2
- import { useAgent } from "agents/react";
3
3
  import React from "react";
4
- //#region src/index.ts
5
- function agentNameToKebab(name) {
6
- if (name === name.toUpperCase() && name !== name.toLowerCase()) return name.toLowerCase().replace(/_/g, "-");
7
- let result = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
8
- result = result.startsWith("-") ? result.slice(1) : result;
9
- return result.replace(/_/g, "-").replace(/-$/, "");
10
- }
11
- function buildAgentHttpBaseUrl(options) {
12
- const hostPart = options.host.replace(/^https?:\/\//, "").replace(/\/$/, "");
13
- const protocol = hostPart.startsWith("localhost:") || hostPart.startsWith("127.0.0.1:") || hostPart.startsWith("192.168.") || hostPart.startsWith("10.") ? "http" : "https";
14
- let pathname = `/agents/${agentNameToKebab(options.agent)}/${encodeURIComponent(options.name)}`;
15
- for (const step of options.sub ?? []) pathname += `/sub/${agentNameToKebab(step.agent)}/${encodeURIComponent(step.name)}`;
16
- return `${protocol}://${hostPart}${pathname}`;
4
+ //#region src/util.ts
5
+ function getTokenArgs(authToken) {
6
+ if (!authToken) return {};
7
+ return {
8
+ headers: { Authorization: `Bearer ${authToken}` },
9
+ protocols: ["bearer", authToken]
10
+ };
17
11
  }
18
- function useAIChatAgent(options) {
19
- const { agent: agentName, host, basePath, chatId, userId, subAgentName, authToken, toolContext, connectionParams, welcomeMessage, onConnectionStatusChange, onOpen: onOpenProp, onClose: onCloseProp, onError: onErrorProp } = options;
20
- const [connectionStatus, setConnectionStatus] = React.useState("connecting");
21
- const updateConnectionStatus = React.useCallback((status) => {
22
- setConnectionStatus(status);
23
- onConnectionStatusChange?.(status);
24
- }, [onConnectionStatusChange]);
25
- let headers = {};
26
- let protocols = [];
27
- if (authToken) {
28
- headers["Authorization"] = `Bearer ${authToken}`;
29
- protocols.push("bearer", authToken);
30
- }
31
- const instanceName = userId ?? chatId;
32
- const subChain = React.useMemo(() => subAgentName ? [{
33
- agent: subAgentName,
34
- name: chatId
35
- }] : [], [subAgentName, chatId]);
36
- const messagesHttpBaseUrl = React.useMemo(() => buildAgentHttpBaseUrl({
12
+ //#endregion
13
+ //#region src/useAgent.ts
14
+ function useAgent(options) {
15
+ const { host, agentName, id, enabled, sub, authToken } = options;
16
+ return useAgent$1({
17
+ enabled,
37
18
  host,
38
19
  agent: agentName,
39
- name: instanceName,
40
- sub: subChain.length > 0 ? subChain : void 0
41
- }), [
20
+ name: id,
21
+ sub,
22
+ ...getTokenArgs(authToken)
23
+ });
24
+ }
25
+ //#endregion
26
+ //#region src/useAssistant.ts
27
+ function useAssistant(options) {
28
+ const { host, assistantName, userId, chatId: initialChatId, authToken, toolContext } = options;
29
+ const config = {
42
30
  host,
43
- agentName,
44
- instanceName,
45
- subChain
46
- ]);
31
+ agentName: assistantName,
32
+ id: userId,
33
+ authToken
34
+ };
35
+ const [chatId, setChatId] = React.useState(initialChatId);
36
+ const assistant = useAgent(config);
37
+ const getConversations = async () => {
38
+ return await assistant.call("getConversations");
39
+ };
40
+ const createConversation = async () => {
41
+ const chatId = await assistant.call("createConversation");
42
+ setChatId(chatId);
43
+ await getConversations();
44
+ return chatId;
45
+ };
46
+ const openConversation = (chatId) => {
47
+ setChatId(chatId);
48
+ };
49
+ const deleteConversation = async (chatId) => {
50
+ await assistant.call("deleteConversation", [chatId]);
51
+ setChatId(void 0);
52
+ await getConversations();
53
+ };
47
54
  const agent = useAgent({
48
- agent: agentName,
49
- host,
50
- basePath,
51
- name: instanceName,
52
- sub: subChain.length > 0 ? subChain : void 0,
53
- query: connectionParams ?? {},
54
- queryDeps: Object.keys(connectionParams ?? {}),
55
- onStateUpdate(state) {
56
- if (state.status === "connected") {
57
- updateConnectionStatus("connected");
58
- onOpenProp?.();
59
- }
60
- },
61
- onClose: (event) => {
62
- if (event.code >= 3e3) {
63
- updateConnectionStatus("unauthorized");
64
- agent.close();
65
- onCloseProp?.(event);
66
- return;
67
- }
68
- updateConnectionStatus("disconnected");
69
- onCloseProp?.(event);
70
- },
71
- onError: onErrorProp,
72
- protocols
55
+ ...config,
56
+ enabled: !!chatId,
57
+ sub: chatId ? [{
58
+ agent: assistant.state?.subAgentName ?? "",
59
+ name: chatId
60
+ }] : void 0
73
61
  });
74
- const fetchInitialMessages = React.useCallback(async (_options) => {
75
- const url = `${messagesHttpBaseUrl}/get-messages`;
76
- const response = await fetch(url, { headers });
77
- if (!response.ok) {
78
- console.warn(`[useAIChatAgent] Failed to fetch initial messages: ${response.status} ${response.statusText}`);
79
- return [];
80
- }
81
- const text = await response.text();
82
- if (!text.trim()) return [];
83
- try {
84
- return JSON.parse(text);
85
- } catch (error) {
86
- console.warn("[useAIChatAgent] Failed to parse initial messages JSON:", error);
87
- return [];
88
- }
89
- }, [headers, messagesHttpBaseUrl]);
62
+ const isChatReady = !!chatId && agent.state?.status === "connected";
90
63
  const chat = useAgentChat({
91
64
  agent,
92
65
  body: toolContext ?? {},
93
- headers,
94
- getInitialMessages: fetchInitialMessages
66
+ getInitialMessages: isChatReady ? void 0 : null
67
+ });
68
+ return {
69
+ chatId,
70
+ status: (chatId ? agent.state?.status : assistant.state?.status) ?? "connecting",
71
+ getConversations,
72
+ createConversation,
73
+ openConversation,
74
+ deleteConversation,
75
+ agent,
76
+ chat: isChatReady ? chat : void 0
77
+ };
78
+ }
79
+ //#endregion
80
+ //#region src/useChatAgent.ts
81
+ function useChatAgent(options) {
82
+ const { host, agentName, id, authToken, toolContext } = options;
83
+ const agent = useAgent({
84
+ host,
85
+ agentName,
86
+ id,
87
+ authToken
88
+ });
89
+ const chat = useAgentChat({
90
+ agent,
91
+ body: toolContext ?? {}
95
92
  });
96
- const hasSentWelcome = React.useRef(false);
97
- React.useEffect(() => {
98
- if (welcomeMessage && connectionStatus === "connected" && chat.messages.length === 0 && !hasSentWelcome.current) {
99
- hasSentWelcome.current = true;
100
- chat.setMessages([{
101
- id: "welcome-message",
102
- role: "assistant",
103
- parts: [{
104
- type: "text",
105
- text: welcomeMessage
106
- }]
107
- }]);
108
- }
109
- }, [
110
- connectionStatus,
111
- chat.messages.length,
112
- welcomeMessage
113
- ]);
114
93
  return {
94
+ status: agent.state?.status ?? "connecting",
115
95
  agent,
116
- chat,
117
- connectionStatus
96
+ chat
118
97
  };
119
98
  }
120
99
  //#endregion
121
- export { useAIChatAgent };
100
+ export { useAgent, useAssistant, useChatAgent };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@economic/agents-react",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist"
@@ -23,7 +23,6 @@
23
23
  "@cloudflare/workers-types": "^4.20260527.1",
24
24
  "@types/node": "^25.6.0",
25
25
  "@typescript/native-preview": "7.0.0-dev.20260412.1",
26
- "ai": "^6.0.175",
27
26
  "tsdown": "^0.22.0",
28
27
  "typescript": "^6.0.2",
29
28
  "vitest": "^4.1.4"
@@ -31,7 +30,15 @@
31
30
  "peerDependencies": {
32
31
  "@cloudflare/ai-chat": ">=0.7.2 <1.0.0",
33
32
  "agents": ">=0.13.3 <1.0.0",
34
- "ai": "^6.0.0",
35
- "react": "^19.2.5"
33
+ "react": "^19"
34
+ },
35
+ "inlinedDependencies": {
36
+ "@ai-sdk/provider": "3.0.10",
37
+ "@ai-sdk/provider-utils": "4.0.27",
38
+ "@ai-sdk/react": "3.0.182",
39
+ "@standard-schema/spec": "1.1.0",
40
+ "ai": "6.0.180",
41
+ "partysocket": "1.1.19",
42
+ "zod": "4.4.3"
36
43
  }
37
44
  }