@economic/agents-react 1.0.1 → 1.1.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 +331 -21
- package/dist/index.mjs +84 -105
- package/package.json +12 -5
package/dist/index.d.mts
CHANGED
|
@@ -1,30 +1,340 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
1
|
+
import * as _$agents_client0 from "agents/client";
|
|
2
|
+
import * as _$ai from "ai";
|
|
3
|
+
import * as _$_ai_sdk_react0 from "@ai-sdk/react";
|
|
3
4
|
|
|
5
|
+
//#region ../../node_modules/partysocket/ws-Cg2f-sDL.d.ts
|
|
6
|
+
//#region src/type-helper.d.ts
|
|
7
|
+
type TypedEventTarget<EventMap extends object> = {
|
|
8
|
+
new (): IntermediateEventTarget<EventMap>;
|
|
9
|
+
};
|
|
10
|
+
interface IntermediateEventTarget<EventMap> extends EventTarget {
|
|
11
|
+
addEventListener<K extends keyof EventMap>(type: K, callback: (event: EventMap[K] extends Event ? EventMap[K] : never) => EventMap[K] extends Event ? void : never, options?: boolean | AddEventListenerOptions): void;
|
|
12
|
+
addEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void;
|
|
13
|
+
removeEventListener<K extends keyof EventMap>(type: K, callback: (event: EventMap[K] extends Event ? EventMap[K] : never) => EventMap[K] extends Event ? void : never, options?: boolean | AddEventListenerOptions): void;
|
|
14
|
+
removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void;
|
|
15
|
+
} //#endregion
|
|
16
|
+
//#region src/ws.d.ts
|
|
17
|
+
declare class ErrorEvent extends Event {
|
|
18
|
+
message: string;
|
|
19
|
+
error: Error;
|
|
20
|
+
constructor(error: Error, target: any);
|
|
21
|
+
}
|
|
22
|
+
declare class CloseEvent extends Event {
|
|
23
|
+
code: number;
|
|
24
|
+
reason: string;
|
|
25
|
+
wasClean: boolean;
|
|
26
|
+
constructor(code: number | undefined, reason: string | undefined, target: any);
|
|
27
|
+
}
|
|
28
|
+
interface WebSocketEventMap {
|
|
29
|
+
close: CloseEvent;
|
|
30
|
+
error: ErrorEvent;
|
|
31
|
+
message: MessageEvent;
|
|
32
|
+
open: Event;
|
|
33
|
+
}
|
|
34
|
+
type Options = {
|
|
35
|
+
WebSocket?: any;
|
|
36
|
+
maxReconnectionDelay?: number;
|
|
37
|
+
minReconnectionDelay?: number;
|
|
38
|
+
reconnectionDelayGrowFactor?: number;
|
|
39
|
+
minUptime?: number;
|
|
40
|
+
connectionTimeout?: number;
|
|
41
|
+
maxRetries?: number;
|
|
42
|
+
maxEnqueuedMessages?: number;
|
|
43
|
+
startClosed?: boolean;
|
|
44
|
+
debug?: boolean;
|
|
45
|
+
debugLogger?: (...args: any[]) => void;
|
|
46
|
+
};
|
|
47
|
+
type UrlProvider = string | (() => string) | (() => Promise<string>);
|
|
48
|
+
type ProtocolsProvider = null | string | string[] | (() => string | string[] | null) | (() => Promise<string | string[] | null>);
|
|
49
|
+
type Message = string | ArrayBuffer | Blob | ArrayBufferView<ArrayBuffer>;
|
|
50
|
+
declare const ReconnectingWebSocket_base: TypedEventTarget<WebSocketEventMap>;
|
|
51
|
+
declare class ReconnectingWebSocket extends ReconnectingWebSocket_base {
|
|
52
|
+
private _ws;
|
|
53
|
+
private _retryCount;
|
|
54
|
+
private _uptimeTimeout;
|
|
55
|
+
private _connectTimeout;
|
|
56
|
+
private _shouldReconnect;
|
|
57
|
+
private _connectLock;
|
|
58
|
+
private _binaryType;
|
|
59
|
+
private _closeCalled;
|
|
60
|
+
private _messageQueue;
|
|
61
|
+
private _debugLogger;
|
|
62
|
+
protected _url: UrlProvider;
|
|
63
|
+
protected _protocols?: ProtocolsProvider;
|
|
64
|
+
protected _options: Options;
|
|
65
|
+
constructor(url: UrlProvider, protocols?: ProtocolsProvider, options?: Options);
|
|
66
|
+
static get CONNECTING(): number;
|
|
67
|
+
static get OPEN(): number;
|
|
68
|
+
static get CLOSING(): number;
|
|
69
|
+
static get CLOSED(): number;
|
|
70
|
+
get CONNECTING(): number;
|
|
71
|
+
get OPEN(): number;
|
|
72
|
+
get CLOSING(): number;
|
|
73
|
+
get CLOSED(): number;
|
|
74
|
+
get binaryType(): BinaryType;
|
|
75
|
+
set binaryType(value: BinaryType);
|
|
76
|
+
/**
|
|
77
|
+
* Returns the number or connection retries
|
|
78
|
+
*/
|
|
79
|
+
get retryCount(): number;
|
|
80
|
+
/**
|
|
81
|
+
* The number of bytes of data that have been queued using calls to send() but not yet
|
|
82
|
+
* transmitted to the network. This value resets to zero once all queued data has been sent.
|
|
83
|
+
* This value does not reset to zero when the connection is closed; if you keep calling send(),
|
|
84
|
+
* this will continue to climb. Read only
|
|
85
|
+
*/
|
|
86
|
+
get bufferedAmount(): number;
|
|
87
|
+
/**
|
|
88
|
+
* The extensions selected by the server. This is currently only the empty string or a list of
|
|
89
|
+
* extensions as negotiated by the connection
|
|
90
|
+
*/
|
|
91
|
+
get extensions(): string;
|
|
92
|
+
/**
|
|
93
|
+
* A string indicating the name of the sub-protocol the server selected;
|
|
94
|
+
* this will be one of the strings specified in the protocols parameter when creating the
|
|
95
|
+
* WebSocket object
|
|
96
|
+
*/
|
|
97
|
+
get protocol(): string;
|
|
98
|
+
/**
|
|
99
|
+
* The current state of the connection; this is one of the Ready state constants
|
|
100
|
+
*/
|
|
101
|
+
get readyState(): number;
|
|
102
|
+
/**
|
|
103
|
+
* The URL as resolved by the constructor
|
|
104
|
+
*/
|
|
105
|
+
get url(): string;
|
|
106
|
+
/**
|
|
107
|
+
* Whether the websocket object is now in reconnectable state
|
|
108
|
+
*/
|
|
109
|
+
get shouldReconnect(): boolean;
|
|
110
|
+
/**
|
|
111
|
+
* An event listener to be called when the WebSocket connection's readyState changes to CLOSED
|
|
112
|
+
*/
|
|
113
|
+
onclose: ((event: CloseEvent) => void) | null;
|
|
114
|
+
/**
|
|
115
|
+
* An event listener to be called when an error occurs
|
|
116
|
+
*/
|
|
117
|
+
onerror: ((event: ErrorEvent) => void) | null;
|
|
118
|
+
/**
|
|
119
|
+
* An event listener to be called when a message is received from the server
|
|
120
|
+
*/
|
|
121
|
+
onmessage: ((event: MessageEvent) => void) | null;
|
|
122
|
+
/**
|
|
123
|
+
* An event listener to be called when the WebSocket connection's readyState changes to OPEN;
|
|
124
|
+
* this indicates that the connection is ready to send and receive data
|
|
125
|
+
*/
|
|
126
|
+
onopen: ((event: Event) => void) | null;
|
|
127
|
+
/**
|
|
128
|
+
* Closes the WebSocket connection or connection attempt, if any. If the connection is already
|
|
129
|
+
* CLOSED, this method does nothing
|
|
130
|
+
*/
|
|
131
|
+
close(code?: number, reason?: string): void;
|
|
132
|
+
/**
|
|
133
|
+
* Closes the WebSocket connection or connection attempt and connects again.
|
|
134
|
+
* Resets retry counter;
|
|
135
|
+
*/
|
|
136
|
+
reconnect(code?: number, reason?: string): void;
|
|
137
|
+
/**
|
|
138
|
+
* Enqueue specified data to be transmitted to the server over the WebSocket connection
|
|
139
|
+
*/
|
|
140
|
+
send(data: Message): void;
|
|
141
|
+
private _debug;
|
|
142
|
+
private _getNextDelay;
|
|
143
|
+
private _wait;
|
|
144
|
+
private _getNextProtocols;
|
|
145
|
+
private _getNextUrl;
|
|
146
|
+
private _connect;
|
|
147
|
+
private _handleTimeout;
|
|
148
|
+
private _disconnect;
|
|
149
|
+
private _acceptOpen;
|
|
150
|
+
private _handleOpen;
|
|
151
|
+
private _handleMessage;
|
|
152
|
+
private _handleError;
|
|
153
|
+
private _handleClose;
|
|
154
|
+
private _removeListeners;
|
|
155
|
+
private _addListeners;
|
|
156
|
+
private _clearTimeouts;
|
|
157
|
+
} //#endregion
|
|
158
|
+
//#endregion
|
|
159
|
+
//#region ../../node_modules/partysocket/index.d.ts
|
|
4
160
|
//#region src/index.d.ts
|
|
5
|
-
type
|
|
6
|
-
|
|
7
|
-
|
|
161
|
+
type Maybe<T> = T | null | undefined;
|
|
162
|
+
type Params = Record<string, Maybe<string>>;
|
|
163
|
+
type PartySocketOptions = Omit<Options, "constructor"> & {
|
|
164
|
+
id?: string;
|
|
8
165
|
host: string;
|
|
166
|
+
room?: string;
|
|
167
|
+
party?: string;
|
|
9
168
|
basePath?: string;
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
169
|
+
prefix?: string;
|
|
170
|
+
protocol?: "ws" | "wss";
|
|
171
|
+
protocols?: ProtocolsProvider;
|
|
172
|
+
path?: string;
|
|
173
|
+
query?: Params | (() => Params | Promise<Params>);
|
|
174
|
+
disableNameValidation?: boolean;
|
|
175
|
+
};
|
|
176
|
+
type PartyFetchOptions = {
|
|
177
|
+
host: string;
|
|
178
|
+
room: string;
|
|
179
|
+
party?: string;
|
|
180
|
+
basePath?: string;
|
|
181
|
+
prefix?: string;
|
|
182
|
+
path?: string;
|
|
183
|
+
protocol?: "http" | "https";
|
|
184
|
+
query?: Params | (() => Params | Promise<Params>);
|
|
185
|
+
fetch?: typeof fetch;
|
|
186
|
+
};
|
|
187
|
+
declare class PartySocket extends ReconnectingWebSocket {
|
|
188
|
+
readonly partySocketOptions: PartySocketOptions;
|
|
189
|
+
_pk: string;
|
|
190
|
+
_pkurl: string;
|
|
191
|
+
name: string;
|
|
192
|
+
room?: string;
|
|
193
|
+
host: string;
|
|
194
|
+
path: string;
|
|
195
|
+
basePath?: string;
|
|
196
|
+
constructor(partySocketOptions: PartySocketOptions);
|
|
197
|
+
updateProperties(partySocketOptions: Partial<PartySocketOptions>): void;
|
|
198
|
+
private setWSProperties;
|
|
199
|
+
reconnect(code?: number | undefined, reason?: string | undefined): void;
|
|
200
|
+
get id(): string;
|
|
201
|
+
/**
|
|
202
|
+
* Exposes the static PartyKit room URL without applying query parameters.
|
|
203
|
+
* To access the currently connected WebSocket url, use PartySocket#url.
|
|
204
|
+
*/
|
|
205
|
+
get roomUrl(): string;
|
|
206
|
+
static fetch(options: PartyFetchOptions, init?: RequestInit): Promise<Response>;
|
|
207
|
+
} //#endregion
|
|
208
|
+
//#endregion
|
|
209
|
+
//#region src/types.d.ts
|
|
210
|
+
type AgentConnectionStatus = "connecting" | "connected" | "disconnected" | "unauthorized";
|
|
211
|
+
type AgentConnectionType = "agent" | "chat" | "assistant";
|
|
212
|
+
type AgentConnectionState = {
|
|
213
|
+
status: AgentConnectionStatus;
|
|
214
|
+
type: AgentConnectionType;
|
|
13
215
|
subAgentName?: string;
|
|
216
|
+
};
|
|
217
|
+
//#endregion
|
|
218
|
+
//#region src/useAgent.d.ts
|
|
219
|
+
interface UseAgentOptions {
|
|
220
|
+
host: string;
|
|
221
|
+
agentName: string;
|
|
222
|
+
id: string;
|
|
223
|
+
enabled?: boolean;
|
|
224
|
+
sub?: {
|
|
225
|
+
agent: string;
|
|
226
|
+
name: string;
|
|
227
|
+
}[];
|
|
228
|
+
authToken?: string;
|
|
229
|
+
}
|
|
230
|
+
declare function useAgent<T extends AgentConnectionState>(options: UseAgentOptions): Omit<PartySocket, "path"> & {
|
|
231
|
+
agent: string;
|
|
232
|
+
name: string;
|
|
233
|
+
path: ReadonlyArray<{
|
|
234
|
+
agent: string;
|
|
235
|
+
name: string;
|
|
236
|
+
}>;
|
|
237
|
+
identified: boolean;
|
|
238
|
+
ready: Promise<void>;
|
|
239
|
+
state: T | undefined;
|
|
240
|
+
setState: (state: T) => void;
|
|
241
|
+
call: <T_1 = unknown>(method: string, args?: unknown[], options?: _$agents_client0.CallOptions | _$agents_client0.StreamOptions) => Promise<T_1>;
|
|
242
|
+
stub: _$agents_client0.UntypedAgentStub;
|
|
243
|
+
getHttpUrl: () => string;
|
|
244
|
+
};
|
|
245
|
+
//#endregion
|
|
246
|
+
//#region src/useAssistant.d.ts
|
|
247
|
+
/** Conversation summary returned by the assistant's `getConversations` RPC. */
|
|
248
|
+
type Conversation = {
|
|
249
|
+
durable_object_name: string;
|
|
250
|
+
title?: string;
|
|
251
|
+
summary?: string;
|
|
252
|
+
created_at: number;
|
|
253
|
+
updated_at: number;
|
|
254
|
+
};
|
|
255
|
+
interface UseAssistantOptions<ToolContext extends Record<string, unknown> = Record<string, unknown>> {
|
|
256
|
+
host: string;
|
|
257
|
+
assistantName: string;
|
|
258
|
+
userId: string;
|
|
259
|
+
chatId?: string;
|
|
260
|
+
authToken?: string;
|
|
261
|
+
toolContext?: ToolContext;
|
|
262
|
+
}
|
|
263
|
+
declare function useAssistant<ToolContext extends Record<string, unknown>>(options: UseAssistantOptions<ToolContext>): {
|
|
264
|
+
chatId: string | undefined;
|
|
265
|
+
status: AgentConnectionStatus;
|
|
266
|
+
getConversations: () => Promise<Conversation[]>;
|
|
267
|
+
createConversation: () => Promise<string>;
|
|
268
|
+
openConversation: (chatId: string) => void;
|
|
269
|
+
deleteConversation: (chatId: string) => Promise<void>;
|
|
270
|
+
agent: Omit<PartySocket, "path"> & {
|
|
271
|
+
agent: string;
|
|
272
|
+
name: string;
|
|
273
|
+
path: ReadonlyArray<{
|
|
274
|
+
agent: string;
|
|
275
|
+
name: string;
|
|
276
|
+
}>;
|
|
277
|
+
identified: boolean;
|
|
278
|
+
ready: Promise<void>;
|
|
279
|
+
state: AgentConnectionState | undefined;
|
|
280
|
+
setState: (state: AgentConnectionState) => void;
|
|
281
|
+
call: <T = unknown>(method: string, args?: unknown[], options?: _$agents_client0.CallOptions | _$agents_client0.StreamOptions) => Promise<T>;
|
|
282
|
+
stub: _$agents_client0.UntypedAgentStub;
|
|
283
|
+
getHttpUrl: () => string;
|
|
284
|
+
};
|
|
285
|
+
chat: (Omit<_$_ai_sdk_react0.UseChatHelpers<_$ai.UIMessage<unknown, _$ai.UIDataTypes, _$ai.UITools>>, "addToolOutput"> & {
|
|
286
|
+
clearHistory: () => void;
|
|
287
|
+
addToolOutput: (opts: {
|
|
288
|
+
toolCallId: string;
|
|
289
|
+
toolName?: string;
|
|
290
|
+
output?: unknown;
|
|
291
|
+
state?: "output-available" | "output-error";
|
|
292
|
+
errorText?: string;
|
|
293
|
+
}) => void;
|
|
294
|
+
isServerStreaming: boolean;
|
|
295
|
+
isStreaming: boolean;
|
|
296
|
+
isToolContinuation: boolean;
|
|
297
|
+
}) | undefined;
|
|
298
|
+
};
|
|
299
|
+
//#endregion
|
|
300
|
+
//#region src/useChatAgent.d.ts
|
|
301
|
+
interface UseChatOptions<ToolContext extends Record<string, unknown>> {
|
|
302
|
+
host: string;
|
|
303
|
+
agentName: string;
|
|
304
|
+
id: string;
|
|
14
305
|
authToken?: string;
|
|
15
|
-
toolContext?:
|
|
16
|
-
connectionParams?: Record<string, string>;
|
|
17
|
-
welcomeMessage?: string;
|
|
18
|
-
onConnectionStatusChange?: (status: AgentConnectionStatus) => void;
|
|
19
|
-
onOpen?: () => void;
|
|
20
|
-
onClose?: (event: CloseEvent) => void;
|
|
21
|
-
onError?: (event: ErrorEvent) => void;
|
|
306
|
+
toolContext?: ToolContext;
|
|
22
307
|
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
308
|
+
declare function useChatAgent<ToolContext extends Record<string, unknown>>(options: UseChatOptions<ToolContext>): {
|
|
309
|
+
status: AgentConnectionStatus;
|
|
310
|
+
agent: Omit<PartySocket, "path"> & {
|
|
311
|
+
agent: string;
|
|
312
|
+
name: string;
|
|
313
|
+
path: ReadonlyArray<{
|
|
314
|
+
agent: string;
|
|
315
|
+
name: string;
|
|
316
|
+
}>;
|
|
317
|
+
identified: boolean;
|
|
318
|
+
ready: Promise<void>;
|
|
319
|
+
state: AgentConnectionState | undefined;
|
|
320
|
+
setState: (state: AgentConnectionState) => void;
|
|
321
|
+
call: <T = unknown>(method: string, args?: unknown[], options?: _$agents_client0.CallOptions | _$agents_client0.StreamOptions) => Promise<T>;
|
|
322
|
+
stub: _$agents_client0.UntypedAgentStub;
|
|
323
|
+
getHttpUrl: () => string;
|
|
324
|
+
};
|
|
325
|
+
chat: Omit<_$_ai_sdk_react0.UseChatHelpers<_$ai.UIMessage<unknown, _$ai.UIDataTypes, _$ai.UITools>>, "addToolOutput"> & {
|
|
326
|
+
clearHistory: () => void;
|
|
327
|
+
addToolOutput: (opts: {
|
|
328
|
+
toolCallId: string;
|
|
329
|
+
toolName?: string;
|
|
330
|
+
output?: unknown;
|
|
331
|
+
state?: "output-available" | "output-error";
|
|
332
|
+
errorText?: string;
|
|
333
|
+
}) => void;
|
|
334
|
+
isServerStreaming: boolean;
|
|
335
|
+
isStreaming: boolean;
|
|
336
|
+
isToolContinuation: boolean;
|
|
337
|
+
};
|
|
27
338
|
};
|
|
28
|
-
declare function useAIChatAgent(options: UseAIChatAgentOptions): UseAIChatAgentResult;
|
|
29
339
|
//#endregion
|
|
30
|
-
export { AgentConnectionStatus,
|
|
340
|
+
export { AgentConnectionState, AgentConnectionStatus, AgentConnectionType, Conversation, UseAgentOptions, UseAssistantOptions, UseChatOptions, useAgent, useAssistant, useChatAgent };
|
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 {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
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}`;
|
|
3
|
+
import { useState } from "react";
|
|
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
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
|
|
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:
|
|
40
|
-
sub
|
|
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
|
-
|
|
45
|
-
|
|
46
|
-
|
|
31
|
+
agentName: assistantName,
|
|
32
|
+
id: userId,
|
|
33
|
+
authToken
|
|
34
|
+
};
|
|
35
|
+
const [chatId, setChatId] = 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
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
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
|
|
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
|
-
|
|
94
|
-
|
|
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 {
|
|
100
|
+
export { useAgent, useAssistant, useChatAgent };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@economic/agents-react",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.1",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist"
|
|
@@ -18,8 +18,14 @@
|
|
|
18
18
|
"typecheck": "tsc --noEmit",
|
|
19
19
|
"prepublishOnly": "npm run build"
|
|
20
20
|
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@ai-sdk/react": "^3.0.182",
|
|
23
|
+
"@cloudflare/ai-chat": ">=0.7.2 <1.0.0",
|
|
24
|
+
"agents": ">=0.13.3 <1.0.0",
|
|
25
|
+
"ai": "^6.0.180",
|
|
26
|
+
"zod": "^4.4.3"
|
|
27
|
+
},
|
|
21
28
|
"devDependencies": {
|
|
22
|
-
"@cloudflare/ai-chat": "^0.7.2",
|
|
23
29
|
"@cloudflare/workers-types": "^4.20260527.1",
|
|
24
30
|
"@types/node": "^25.6.0",
|
|
25
31
|
"@typescript/native-preview": "7.0.0-dev.20260412.1",
|
|
@@ -28,8 +34,9 @@
|
|
|
28
34
|
"vitest": "^4.1.4"
|
|
29
35
|
},
|
|
30
36
|
"peerDependencies": {
|
|
31
|
-
"
|
|
32
|
-
|
|
33
|
-
|
|
37
|
+
"react": "^19"
|
|
38
|
+
},
|
|
39
|
+
"inlinedDependencies": {
|
|
40
|
+
"partysocket": "1.1.19"
|
|
34
41
|
}
|
|
35
42
|
}
|