@economic/agents-react 0.4.0 → 1.0.1

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.
package/dist/index.d.mts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { useAgentChat } from "@cloudflare/ai-chat/react";
2
2
  import { useAgent } from "agents/react";
3
- import { UIMessage } from "ai";
4
3
 
5
4
  //#region src/index.d.ts
6
5
  type AgentConnectionStatus = "connecting" | "connected" | "disconnected" | "unauthorized";
@@ -9,18 +8,21 @@ interface UseAIChatAgentOptions {
9
8
  host: string;
10
9
  basePath?: string;
11
10
  chatId: string;
11
+ /** When set with `subAgentName`, used as the coordinator agent instance name instead of `chatId`. */
12
+ userId?: string;
13
+ subAgentName?: string;
12
14
  authToken?: string;
13
15
  toolContext?: Record<string, unknown>;
14
16
  connectionParams?: Record<string, string>;
15
17
  welcomeMessage?: string;
16
18
  onConnectionStatusChange?: (status: AgentConnectionStatus) => void;
17
- onOpen?: (event: Event) => void;
19
+ onOpen?: () => void;
18
20
  onClose?: (event: CloseEvent) => void;
19
21
  onError?: (event: ErrorEvent) => void;
20
22
  }
21
23
  type UseAIChatAgentResult = {
22
24
  agent: ReturnType<typeof useAgent>;
23
- chat: ReturnType<typeof useAgentChat<unknown, UIMessage>>;
25
+ chat: ReturnType<typeof useAgentChat>;
24
26
  connectionStatus: AgentConnectionStatus;
25
27
  };
26
28
  declare function useAIChatAgent(options: UseAIChatAgentOptions): UseAIChatAgentResult;
package/dist/index.mjs CHANGED
@@ -2,8 +2,21 @@ import { useAgentChat } from "@cloudflare/ai-chat/react";
2
2
  import { useAgent } from "agents/react";
3
3
  import React from "react";
4
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}`;
17
+ }
5
18
  function useAIChatAgent(options) {
6
- const { agent: agentName, host, basePath, chatId, authToken, toolContext, connectionParams, welcomeMessage, onConnectionStatusChange, onOpen: onOpenProp, onClose: onCloseProp, onError: onErrorProp } = options;
19
+ const { agent: agentName, host, basePath, chatId, userId, subAgentName, authToken, toolContext, connectionParams, welcomeMessage, onConnectionStatusChange, onOpen: onOpenProp, onClose: onCloseProp, onError: onErrorProp } = options;
7
20
  const [connectionStatus, setConnectionStatus] = React.useState("connecting");
8
21
  const updateConnectionStatus = React.useCallback((status) => {
9
22
  setConnectionStatus(status);
@@ -15,16 +28,35 @@ function useAIChatAgent(options) {
15
28
  headers["Authorization"] = `Bearer ${authToken}`;
16
29
  protocols.push("bearer", authToken);
17
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({
37
+ host,
38
+ agent: agentName,
39
+ name: instanceName,
40
+ sub: subChain.length > 0 ? subChain : void 0
41
+ }), [
42
+ host,
43
+ agentName,
44
+ instanceName,
45
+ subChain
46
+ ]);
18
47
  const agent = useAgent({
19
48
  agent: agentName,
20
49
  host,
21
50
  basePath,
22
- name: chatId,
51
+ name: instanceName,
52
+ sub: subChain.length > 0 ? subChain : void 0,
23
53
  query: connectionParams ?? {},
24
54
  queryDeps: Object.keys(connectionParams ?? {}),
25
- onOpen: (event) => {
26
- updateConnectionStatus("connected");
27
- onOpenProp?.(event);
55
+ onStateUpdate(state) {
56
+ if (state.status === "connected") {
57
+ updateConnectionStatus("connected");
58
+ onOpenProp?.();
59
+ }
28
60
  },
29
61
  onClose: (event) => {
30
62
  if (event.code >= 3e3) {
@@ -39,10 +71,27 @@ function useAIChatAgent(options) {
39
71
  onError: onErrorProp,
40
72
  protocols
41
73
  });
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]);
42
90
  const chat = useAgentChat({
43
91
  agent,
44
92
  body: toolContext ?? {},
45
- headers
93
+ headers,
94
+ getInitialMessages: fetchInitialMessages
46
95
  });
47
96
  const hasSentWelcome = React.useRef(false);
48
97
  React.useEffect(() => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@economic/agents-react",
3
- "version": "0.4.0",
3
+ "version": "1.0.1",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist"
@@ -19,19 +19,17 @@
19
19
  "prepublishOnly": "npm run build"
20
20
  },
21
21
  "devDependencies": {
22
- "@cloudflare/ai-chat": "^0.6.2",
23
- "@cloudflare/workers-types": "^4.20260430.1",
22
+ "@cloudflare/ai-chat": "^0.7.2",
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"
30
29
  },
31
30
  "peerDependencies": {
32
- "@cloudflare/ai-chat": ">=0.6.0 <1.0.0",
33
- "agents": ">=0.12.0 <1.0.0",
34
- "ai": "^6.0.0",
31
+ "@cloudflare/ai-chat": ">=0.7.2 <1.0.0",
32
+ "agents": ">=0.13.3 <1.0.0",
35
33
  "react": "^19.2.5"
36
34
  }
37
35
  }